code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.benchmark;
import java.io.IOException;
import java.net.URI;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import com.ning.http.client.Request;
public class TestNingHttpClient implements TestHttpAgent {
private AsyncHttpClient client;
public TestNingHttpClient() {
super();
}
public void init() throws Exception {
}
public void shutdown() throws Exception {
this.client.close();
}
Stats execute(final URI targetURI, byte[] content, int n, int c) throws Exception {
if (this.client != null) {
this.client.close();
}
AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder()
.setAllowPoolingConnection(true)
.setCompressionEnabled(false)
.setMaximumConnectionsPerHost(c)
.setMaximumConnectionsTotal(2000)
.setRequestTimeoutInMs(15000)
.build();
this.client = new AsyncHttpClient(config);
Stats stats = new Stats(n, c);
for (int i = 0; i < n; i++) {
Request request;
if (content == null) {
request = this.client.prepareGet(targetURI.toASCIIString())
.build();
} else {
request = this.client.preparePost(targetURI.toASCIIString())
.setBody(content)
.build();
}
try {
this.client.executeRequest(request, new SimpleAsyncHandler(stats));
} catch (IOException ex) {
}
}
stats.waitFor();
return stats;
}
public Stats get(final URI target, int n, int c) throws Exception {
return execute(target, null, n, c);
}
public Stats post(final URI target, byte[] content, int n, int c) throws Exception {
return execute(target, content, n, c);
}
public String getClientName() {
return "Ning Async HTTP client 1.4.0";
}
static class SimpleAsyncHandler implements AsyncHandler<Object> {
private final Stats stats;
private int status = 0;
private long contentLen = 0;
SimpleAsyncHandler(final Stats stats) {
super();
this.stats = stats;
}
public STATE onStatusReceived(final HttpResponseStatus responseStatus) throws Exception {
this.status = responseStatus.getStatusCode();
return STATE.CONTINUE;
}
public STATE onHeadersReceived(final HttpResponseHeaders headers) throws Exception {
return STATE.CONTINUE;
}
public STATE onBodyPartReceived(final HttpResponseBodyPart bodyPart) throws Exception {
this.contentLen += bodyPart.getBodyPartBytes().length;
return STATE.CONTINUE;
}
public Object onCompleted() throws Exception {
if (this.status == 200) {
this.stats.success(this.contentLen);
} else {
this.stats.failure(this.contentLen);
}
return STATE.CONTINUE;
}
public void onThrowable(final Throwable t) {
this.stats.failure(this.contentLen);
}
};
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
System.exit(-1);
}
URI targetURI = new URI(args[0]);
int n = Integer.parseInt(args[1]);
int c = 1;
if (args.length > 2) {
c = Integer.parseInt(args[2]);
}
TestNingHttpClient test = new TestNingHttpClient();
test.init();
try {
long startTime = System.currentTimeMillis();
Stats stats = test.get(targetURI, n, c);
long finishTime = System.currentTimeMillis();
Stats.printStats(targetURI, startTime, finishTime, stats);
} finally {
test.shutdown();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient-benchmark/src/main/java/org/apache/http/client/benchmark/TestNingHttpClient.java
|
Java
|
gpl3
| 5,492
|
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.benchmark;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.URI;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.VersionInfo;
public class TestHttpCore implements TestHttpAgent {
private final HttpParams params;
private final HttpProcessor httpproc;
private final HttpRequestExecutor httpexecutor;
private final ConnectionReuseStrategy connStrategy;
public TestHttpCore() {
super();
this.params = new SyncBasicHttpParams();
this.params.setParameter(HttpProtocolParams.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
this.params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE,
false);
this.params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK,
false);
this.params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE,
8 * 1024);
this.params.setIntParameter(HttpConnectionParams.SO_TIMEOUT,
15000);
this.httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent()
}, null);
this.httpexecutor = new HttpRequestExecutor();
this.connStrategy = new DefaultConnectionReuseStrategy();
}
public void init() {
}
public void shutdown() {
}
Stats execute(final URI target, final byte[] content, int n, int c) throws Exception {
HttpHost targetHost = new HttpHost(target.getHost(), target.getPort());
StringBuilder buffer = new StringBuilder();
buffer.append(target.getPath());
if (target.getQuery() != null) {
buffer.append("?");
buffer.append(target.getQuery());
}
String requestUri = buffer.toString();
Stats stats = new Stats(n, c);
WorkerThread[] workers = new WorkerThread[c];
for (int i = 0; i < workers.length; i++) {
workers[i] = new WorkerThread(stats, targetHost, requestUri, content);
}
for (int i = 0; i < workers.length; i++) {
workers[i].start();
}
for (int i = 0; i < workers.length; i++) {
workers[i].join();
}
return stats;
}
class WorkerThread extends Thread {
private final Stats stats;
private final HttpHost targetHost;
private final String requestUri;
private final byte[] content;
WorkerThread(final Stats stats,
final HttpHost targetHost, final String requestUri, final byte[] content) {
super();
this.stats = stats;
this.targetHost = targetHost;
this.requestUri = requestUri;
this.content = content;
}
@Override
public void run() {
byte[] buffer = new byte[4096];
HttpContext context = new BasicHttpContext();
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
try {
while (!this.stats.isComplete()) {
HttpRequest request;
if (this.content == null) {
BasicHttpRequest httpget = new BasicHttpRequest("GET", this.requestUri);
request = httpget;
} else {
BasicHttpEntityEnclosingRequest httppost = new BasicHttpEntityEnclosingRequest("POST",
this.requestUri);
httppost.setEntity(new ByteArrayEntity(this.content));
request = httppost;
}
long contentLen = 0;
try {
if (!conn.isOpen()) {
Socket socket = new Socket(
this.targetHost.getHostName(),
this.targetHost.getPort() > 0 ? this.targetHost.getPort() : 80);
conn.bind(socket, params);
}
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
httpexecutor.postProcess(response, httpproc, context);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
contentLen = 0;
if (instream != null) {
int l = 0;
while ((l = instream.read(buffer)) != -1) {
contentLen += l;
}
}
} finally {
instream.close();
}
}
if (!connStrategy.keepAlive(response, context)) {
conn.close();
}
for (HeaderIterator it = request.headerIterator(); it.hasNext();) {
it.next();
it.remove();
}
this.stats.success(contentLen);
} catch (IOException ex) {
this.stats.failure(contentLen);
} catch (HttpException ex) {
this.stats.failure(contentLen);
}
}
} finally {
try {
conn.shutdown();
} catch (IOException ignore) {}
}
}
}
public Stats get(final URI target, int n, int c) throws Exception {
return execute(target, null, n, c);
}
public Stats post(final URI target, byte[] content, int n, int c) throws Exception {
return execute(target, content, n, c);
}
public String getClientName() {
VersionInfo vinfo = VersionInfo.loadVersionInfo("org.apache.http",
Thread.currentThread().getContextClassLoader());
return "Apache HttpCore 4 (ver: " +
((vinfo != null) ? vinfo.getRelease() : VersionInfo.UNAVAILABLE) + ")";
}
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
System.exit(-1);
}
URI targetURI = new URI(args[0]);
int n = Integer.parseInt(args[1]);
int c = 1;
if (args.length > 2) {
c = Integer.parseInt(args[2]);
}
TestHttpCore test = new TestHttpCore();
test.init();
try {
long startTime = System.currentTimeMillis();
Stats stats = test.get(targetURI, n, c);
long finishTime = System.currentTimeMillis();
Stats.printStats(targetURI, startTime, finishTime, stats);
} finally {
test.shutdown();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient-benchmark/src/main/java/org/apache/http/client/benchmark/TestHttpCore.java
|
Java
|
gpl3
| 10,054
|
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.benchmark;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.VersionInfo;
public class TestHttpClient4 implements TestHttpAgent {
private final ThreadSafeClientConnManager mgr;
private final DefaultHttpClient httpclient;
public TestHttpClient4() {
super();
HttpParams params = new SyncBasicHttpParams();
params.setParameter(HttpProtocolParams.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE,
false);
params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK,
false);
params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE,
8 * 1024);
params.setIntParameter(HttpConnectionParams.SO_TIMEOUT,
15000);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
this.mgr = new ThreadSafeClientConnManager(schemeRegistry);
this.httpclient = new DefaultHttpClient(this.mgr, params);
this.httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
public boolean retryRequest(
final IOException exception, int executionCount, final HttpContext context) {
return false;
}
});
}
public void init() {
}
public void shutdown() {
this.mgr.shutdown();
}
Stats execute(final URI target, final byte[] content, int n, int c) throws Exception {
this.mgr.setMaxTotal(2000);
this.mgr.setDefaultMaxPerRoute(c);
Stats stats = new Stats(n, c);
WorkerThread[] workers = new WorkerThread[c];
for (int i = 0; i < workers.length; i++) {
workers[i] = new WorkerThread(stats, target, content);
}
for (int i = 0; i < workers.length; i++) {
workers[i].start();
}
for (int i = 0; i < workers.length; i++) {
workers[i].join();
}
return stats;
}
class WorkerThread extends Thread {
private final Stats stats;
private final URI target;
private final byte[] content;
WorkerThread(final Stats stats, final URI target, final byte[] content) {
super();
this.stats = stats;
this.target = target;
this.content = content;
}
@Override
public void run() {
byte[] buffer = new byte[4096];
while (!this.stats.isComplete()) {
HttpUriRequest request;
if (this.content == null) {
HttpGet httpget = new HttpGet(target);
request = httpget;
} else {
HttpPost httppost = new HttpPost(target);
httppost.setEntity(new ByteArrayEntity(content));
request = httppost;
}
long contentLen = 0;
try {
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
contentLen = 0;
if (instream != null) {
int l = 0;
while ((l = instream.read(buffer)) != -1) {
contentLen += l;
}
}
} finally {
instream.close();
}
}
this.stats.success(contentLen);
} catch (IOException ex) {
this.stats.failure(contentLen);
request.abort();
}
}
}
}
public Stats get(final URI target, int n, int c) throws Exception {
return execute(target, null, n ,c);
}
public Stats post(final URI target, byte[] content, int n, int c) throws Exception {
return execute(target, content, n, c);
}
public String getClientName() {
VersionInfo vinfo = VersionInfo.loadVersionInfo("org.apache.http.client",
Thread.currentThread().getContextClassLoader());
return "Apache HttpClient 4 (ver: " +
((vinfo != null) ? vinfo.getRelease() : VersionInfo.UNAVAILABLE) + ")";
}
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
System.exit(-1);
}
URI targetURI = new URI(args[0]);
int n = Integer.parseInt(args[1]);
int c = 1;
if (args.length > 2) {
c = Integer.parseInt(args[2]);
}
TestHttpClient4 test = new TestHttpClient4();
test.init();
try {
long startTime = System.currentTimeMillis();
Stats stats = test.get(targetURI, n, c);
long finishTime = System.currentTimeMillis();
Stats.printStats(targetURI, startTime, finishTime, stats);
} finally {
test.shutdown();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient-benchmark/src/main/java/org/apache/http/client/benchmark/TestHttpClient4.java
|
Java
|
gpl3
| 7,737
|
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.benchmark;
import java.io.IOException;
import java.net.URI;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpExchange;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.server.Server;
public class TestJettyHttpClient implements TestHttpAgent {
private final HttpClient client;
public TestJettyHttpClient() {
super();
this.client = new HttpClient();
this.client.setRequestBufferSize(8 * 1024);
this.client.setResponseBufferSize(8 * 1024);
this.client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
this.client.setTimeout(15000);
}
public void init() throws Exception {
this.client.start();
}
public void shutdown() throws Exception {
this.client.stop();
}
Stats execute(final URI targetURI, byte[] content, int n, int c) throws Exception {
this.client.setMaxConnectionsPerAddress(c);
Stats stats = new Stats(n, c);
for (int i = 0; i < n; i++) {
SimpleHttpExchange exchange = new SimpleHttpExchange(stats);
exchange.setURL(targetURI.toASCIIString());
if (content != null) {
exchange.setMethod("POST");
exchange.setRequestContent(new ByteArrayBuffer(content));
}
try {
this.client.send(exchange);
} catch (IOException ex) {
}
}
stats.waitFor();
return stats;
}
public Stats get(final URI target, int n, int c) throws Exception {
return execute(target, null, n, c);
}
public Stats post(final URI target, byte[] content, int n, int c) throws Exception {
return execute(target, content, n, c);
}
public String getClientName() {
return "Jetty " + Server.getVersion();
}
static class SimpleHttpExchange extends HttpExchange {
private final Stats stats;
private int status = 0;
private long contentLen = 0;
SimpleHttpExchange(final Stats stats) {
super();
this.stats = stats;
}
protected void onResponseStatus(
final Buffer version, int status, final Buffer reason) throws IOException {
this.status = status;
super.onResponseStatus(version, status, reason);
}
@Override
protected void onResponseContent(final Buffer content) throws IOException {
byte[] tmp = new byte[content.length()];
content.get(tmp, 0, tmp.length);
this.contentLen += tmp.length;
super.onResponseContent(content);
}
@Override
protected void onResponseComplete() throws IOException {
if (this.status == 200) {
this.stats.success(this.contentLen);
} else {
this.stats.failure(this.contentLen);
}
super.onResponseComplete();
}
@Override
protected void onConnectionFailed(final Throwable x) {
this.stats.failure(this.contentLen);
super.onConnectionFailed(x);
}
@Override
protected void onException(final Throwable x) {
this.stats.failure(this.contentLen);
super.onException(x);
}
};
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
System.exit(-1);
}
URI targetURI = new URI(args[0]);
int n = Integer.parseInt(args[1]);
int c = 1;
if (args.length > 2) {
c = Integer.parseInt(args[2]);
}
TestJettyHttpClient test = new TestJettyHttpClient();
test.init();
try {
long startTime = System.currentTimeMillis();
Stats stats = test.get(targetURI, n, c);
long finishTime = System.currentTimeMillis();
Stats.printStats(targetURI, startTime, finishTime, stats);
} finally {
test.shutdown();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient-benchmark/src/main/java/org/apache/http/client/benchmark/TestJettyHttpClient.java
|
Java
|
gpl3
| 5,433
|
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.benchmark;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.net.URI;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.ByteArrayOutputStream2;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
public class Benchmark {
public static void main(String[] args) throws Exception {
String ns = System.getProperty("hc.benchmark.n-requests", "200000");
String nc = System.getProperty("hc.benchmark.concurrent", "100");
String cls = System.getProperty("hc.benchmark.content-len", "2048");
int n = Integer.parseInt(ns);
int c = Integer.parseInt(nc);
int contentLen = Integer.parseInt(cls);
SocketConnector connector = new SocketConnector();
connector.setPort(0);
connector.setRequestBufferSize(12 * 1024);
connector.setResponseBufferSize(12 * 1024);
connector.setAcceptors(2);
connector.setAcceptQueueSize(c);
QueuedThreadPool threadpool = new QueuedThreadPool();
threadpool.setMinThreads(c);
threadpool.setMaxThreads(2000);
Server server = new Server();
server.addConnector(connector);
server.setThreadPool(threadpool);
server.setHandler(new RandomDataHandler());
server.start();
int port = connector.getLocalPort();
// Sleep a little
Thread.sleep(2000);
TestHttpAgent[] agents = new TestHttpAgent[] {
new TestHttpClient3(),
new TestHttpJRE(),
new TestHttpCore(),
new TestHttpClient4(),
new TestJettyHttpClient(),
new TestNingHttpClient()
};
byte[] content = new byte[contentLen];
int r = Math.abs(content.hashCode());
for (int i = 0; i < content.length; i++) {
content[i] = (byte) ((r + i) % 96 + 32);
}
URI target1 = new URI("http", null, "localhost", port, "/rnd", "c=" + contentLen, null);
URI target2 = new URI("http", null, "localhost", port, "/echo", null, null);
try {
for (TestHttpAgent agent: agents) {
agent.init();
try {
System.out.println("=================================");
System.out.println("HTTP agent: " + agent.getClientName());
System.out.println("---------------------------------");
System.out.println(n + " GET requests");
System.out.println("---------------------------------");
long startTime1 = System.currentTimeMillis();
Stats stats1 = agent.get(target1, n, c);
long finishTime1 = System.currentTimeMillis();
Stats.printStats(target1, startTime1, finishTime1, stats1);
System.out.println("---------------------------------");
System.out.println(n + " POST requests");
System.out.println("---------------------------------");
long startTime2 = System.currentTimeMillis();
Stats stats2 = agent.post(target2, content, n, c);
long finishTime2 = System.currentTimeMillis();
Stats.printStats(target2, startTime2, finishTime2, stats2);
} finally {
agent.shutdown();
}
agent.init();
System.out.println("---------------------------------");
}
} finally {
server.stop();
}
server.join();
}
static class RandomDataHandler extends AbstractHandler {
public RandomDataHandler() {
super();
}
public void handle(
final String target,
final Request baseRequest,
final HttpServletRequest request,
final HttpServletResponse response) throws IOException, ServletException {
if (target.equals("/rnd")) {
rnd(request, response);
} else if (target.equals("/echo")) {
echo(request, response);
} else {
response.setStatus(HttpStatus.NOT_FOUND_404);
Writer writer = response.getWriter();
writer.write("Target not found: " + target);
writer.flush();
}
}
private void rnd(
final HttpServletRequest request,
final HttpServletResponse response) throws IOException, ServletException {
int count = 100;
String s = request.getParameter("c");
try {
count = Integer.parseInt(s);
} catch (NumberFormatException ex) {
response.setStatus(500);
Writer writer = response.getWriter();
writer.write("Invalid query format: " + request.getQueryString());
writer.flush();
return;
}
response.setStatus(200);
response.setContentLength(count);
OutputStream outstream = response.getOutputStream();
byte[] tmp = new byte[1024];
int r = Math.abs(tmp.hashCode());
int remaining = count;
while (remaining > 0) {
int chunk = Math.min(tmp.length, remaining);
for (int i = 0; i < chunk; i++) {
tmp[i] = (byte) ((r + i) % 96 + 32);
}
outstream.write(tmp, 0, chunk);
remaining -= chunk;
}
outstream.flush();
}
private void echo(
final HttpServletRequest request,
final HttpServletResponse response) throws IOException, ServletException {
ByteArrayOutputStream2 buffer = new ByteArrayOutputStream2();
InputStream instream = request.getInputStream();
if (instream != null) {
IO.copy(instream, buffer);
buffer.flush();
}
byte[] content = buffer.getBuf();
response.setStatus(200);
response.setContentLength(content.length);
OutputStream outstream = response.getOutputStream();
outstream.write(content);
outstream.flush();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient-benchmark/src/main/java/org/apache/http/client/benchmark/Benchmark.java
|
Java
|
gpl3
| 7,901
|
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.benchmark;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class TestHttpJRE implements TestHttpAgent {
public TestHttpJRE() {
super();
}
public void init() {
}
public void shutdown() {
}
Stats execute(final URI targetURI, byte[] content, int n, int c) throws Exception {
System.setProperty("http.maxConnections", Integer.toString(c));
URL target = targetURI.toURL();
Stats stats = new Stats(n, c);
WorkerThread[] workers = new WorkerThread[c];
for (int i = 0; i < workers.length; i++) {
workers[i] = new WorkerThread(stats, target, content);
}
for (int i = 0; i < workers.length; i++) {
workers[i].start();
}
for (int i = 0; i < workers.length; i++) {
workers[i].join();
}
return stats;
}
class WorkerThread extends Thread {
private final Stats stats;
private final URL target;
private final byte[] content;
WorkerThread(final Stats stats, final URL target, final byte[] content) {
super();
this.stats = stats;
this.target = target;
this.content = content;
}
@Override
public void run() {
byte[] buffer = new byte[4096];
while (!this.stats.isComplete()) {
long contentLen = 0;
try {
HttpURLConnection conn = (HttpURLConnection) this.target.openConnection();
conn.setReadTimeout(15000);
if (this.content != null) {
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(this.content.length);
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
try {
out.write(this.content);
out.flush ();
} finally {
out.close();
}
}
InputStream instream = conn.getInputStream();
if (instream != null) {
try {
int l = 0;
while ((l = instream.read(buffer)) != -1) {
contentLen += l;
}
} finally {
instream.close();
}
}
if (conn.getResponseCode() == 200) {
this.stats.success(contentLen);
} else {
this.stats.failure(contentLen);
}
} catch (IOException ex) {
this.stats.failure(contentLen);
}
}
}
}
public Stats get(final URI target, int n, int c) throws Exception {
return execute(target, null, n, c);
}
public Stats post(final URI target, byte[] content, int n, int c) throws Exception {
return execute(target, content, n, c);
}
public String getClientName() {
return "JRE HTTP " + System.getProperty("java.version");
}
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
System.exit(-1);
}
URI targetURI = new URI(args[0]);
int n = Integer.parseInt(args[1]);
int c = 1;
if (args.length > 2) {
c = Integer.parseInt(args[2]);
}
TestHttpJRE test = new TestHttpJRE();
test.init();
try {
long startTime = System.currentTimeMillis();
Stats stats = test.get(targetURI, n, c);
long finishTime = System.currentTimeMillis();
Stats.printStats(targetURI, startTime, finishTime, stats);
} finally {
test.shutdown();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient-benchmark/src/main/java/org/apache/http/client/benchmark/TestHttpJRE.java
|
Java
|
gpl3
| 5,560
|
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.benchmark;
import java.net.URI;
public interface TestHttpAgent {
void init() throws Exception;
void shutdown() throws Exception;
String getClientName();
Stats get(URI target, int n, int c) throws Exception;
Stats post(URI target, byte[] content, int n, int c) throws Exception;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient-benchmark/src/main/java/org/apache/http/client/benchmark/TestHttpAgent.java
|
Java
|
gpl3
| 1,531
|
@import url("../../../css/hc-maven.css");
|
zzy157-running
|
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient-cache/src/site/resources/css/site.css
|
CSS
|
gpl3
| 42
|
/*
* Copyright (C) 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gdata.util.common.base;
import java.util.Collection;
import java.util.NoSuchElementException;
/**
* Simple static methods to be called at the start of your own methods to verify
* correct arguments and state. This allows constructs such as
* <pre>
* if (count <= 0) {
* throw new IllegalArgumentException("must be positive: " + count);
* }</pre>
*
* to be replaced with the more compact
* <pre>
* checkArgument(count > 0, "must be positive: %s", count);</pre>
*
* Note that the sense of the expression is inverted; with {@code Preconditions}
* you declare what you expect to be <i>true</i>, just as you do with an
* <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html">
* {@code assert}</a> or a JUnit {@code assertTrue()} call.
*
* <p>Take care not to confuse precondition checking with other similar types
* of checks! Precondition exceptions -- including those provided here, but also
* {@link IndexOutOfBoundsException}, {@link NoSuchElementException}, {@link
* UnsupportedOperationException} and others -- are used to signal that the
* <i>calling method</i> has made an error. This tells the caller that it should
* not have invoked the method when it did, with the arguments it did, or
* perhaps <i>ever</i>. Postcondition or other invariant failures should not
* throw these types of exceptions.
*
* <p><b>Note:</b> The methods of the {@code Preconditions} class are highly
* unusual in one way: they are <i>supposed to</i> throw exceptions, and promise
* in their specifications to do so even when given perfectly valid input. That
* is, {@code null} is a valid parameter to the method {@link
* #checkNotNull(Object)} -- and technically this parameter could be even marked
* as {@link Nullable} -- yet the method will still throw an exception anyway,
* because that's what its contract says to do.
*
* <p>This class may be used with the Google Web Toolkit (GWT).
*
*
*/
public final class Preconditions {
private Preconditions() {}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @throws IllegalArgumentException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code
* errorMessageTemplate} or {@code errorMessageArgs} is null (don't let
* this happen)
*/
public static void checkArgument(boolean expression,
String errorMessageTemplate, Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(
format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @throws IllegalStateException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code
* errorMessageTemplate} or {@code errorMessageArgs} is null (don't let
* this happen)
*/
public static void checkState(boolean expression,
String errorMessageTemplate, Object... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(
format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, String errorMessageTemplate,
Object... errorMessageArgs) {
if (reference == null) {
// If either of these parameters is null, the right thing happens anyway
throw new NullPointerException(
format(errorMessageTemplate, errorMessageArgs));
}
return reference;
}
/**
* Ensures that an {@code Iterable} object passed as a parameter to the
* calling method is not null and contains no null elements.
*
* @param iterable the iterable to check the contents of
* @return the non-null {@code iterable} reference just validated
* @throws NullPointerException if {@code iterable} is null or contains at
* least one null element
*/
public static <T extends Iterable<?>> T checkContentsNotNull(T iterable) {
if (containsOrIsNull(iterable)) {
throw new NullPointerException();
}
return iterable;
}
/**
* Ensures that an {@code Iterable} object passed as a parameter to the
* calling method is not null and contains no null elements.
*
* @param iterable the iterable to check the contents of
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @return the non-null {@code iterable} reference just validated
* @throws NullPointerException if {@code iterable} is null or contains at
* least one null element
*/
public static <T extends Iterable<?>> T checkContentsNotNull(
T iterable, Object errorMessage) {
if (containsOrIsNull(iterable)) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return iterable;
}
/**
* Ensures that an {@code Iterable} object passed as a parameter to the
* calling method is not null and contains no null elements.
*
* @param iterable the iterable to check the contents of
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @return the non-null {@code iterable} reference just validated
* @throws NullPointerException if {@code iterable} is null or contains at
* least one null element
*/
public static <T extends Iterable<?>> T checkContentsNotNull(T iterable,
String errorMessageTemplate, Object... errorMessageArgs) {
if (containsOrIsNull(iterable)) {
throw new NullPointerException(
format(errorMessageTemplate, errorMessageArgs));
}
return iterable;
}
private static boolean containsOrIsNull(Iterable<?> iterable) {
if (iterable == null) {
return true;
}
if (iterable instanceof Collection) {
Collection<?> collection = (Collection<?>) iterable;
try {
return collection.contains(null);
} catch (NullPointerException e) {
// A NPE implies that the collection doesn't contain null.
return false;
}
} else {
for (Object element : iterable) {
if (element == null) {
return true;
}
}
return false;
}
}
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array,
* list or string of size {@code size}. An element index may range from zero,
* inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list
* or string
* @param size the size of that array, list or string
* @throws IndexOutOfBoundsException if {@code index} is negative or is not
* less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkElementIndex(int index, int size) {
checkElementIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array,
* list or string of size {@code size}. An element index may range from zero,
* inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list
* or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @throws IndexOutOfBoundsException if {@code index} is negative or is not
* less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkElementIndex(int index, int size, String desc) {
checkArgument(size >= 0, "negative size: %s", size);
if (index < 0) {
throw new IndexOutOfBoundsException(
format("%s (%s) must not be negative", desc, index));
}
if (index >= size) {
throw new IndexOutOfBoundsException(
format("%s (%s) must be less than size (%s)", desc, index, size));
}
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array,
* list or string of size {@code size}. A position index may range from zero
* to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list
* or string
* @param size the size of that array, list or string
* @throws IndexOutOfBoundsException if {@code index} is negative or is
* greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkPositionIndex(int index, int size) {
checkPositionIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array,
* list or string of size {@code size}. A position index may range from zero
* to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list
* or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @throws IndexOutOfBoundsException if {@code index} is negative or is
* greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkPositionIndex(int index, int size, String desc) {
checkArgument(size >= 0, "negative size: %s", size);
if (index < 0) {
throw new IndexOutOfBoundsException(format(
"%s (%s) must not be negative", desc, index));
}
if (index > size) {
throw new IndexOutOfBoundsException(format(
"%s (%s) must not be greater than size (%s)", desc, index, size));
}
}
/**
* Ensures that {@code start} and {@code end} specify a valid <i>positions</i>
* in an array, list or string of size {@code size}, and are in order. A
* position index may range from zero to {@code size}, inclusive.
*
* @param start a user-supplied index identifying a starting position in an
* array, list or string
* @param end a user-supplied index identifying a ending position in an array,
* list or string
* @param size the size of that array, list or string
* @throws IndexOutOfBoundsException if either index is negative or is
* greater than {@code size}, or if {@code end} is less than {@code start}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkPositionIndexes(int start, int end, int size) {
checkPositionIndex(start, size, "start index");
checkPositionIndex(end, size, "end index");
if (end < start) {
throw new IndexOutOfBoundsException(format(
"end index (%s) must not be less than start index (%s)", end, start));
}
}
/**
* Substitutes each {@code %s} in {@code template} with an argument. These
* are matched by position - the first {@code %s} gets {@code args[0]}, etc.
* If there are more arguments than placeholders, the unmatched arguments will
* be appended to the end of the formatted message in square braces.
*
* @param template a non-null string containing 0 or more {@code %s}
* placeholders.
* @param args the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}. Arguments can be null.
*/
// VisibleForTesting
static String format(String template, Object... args) {
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(
template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append("]");
}
return builder.toString();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/com/google/gdata/util/common/base/Preconditions.java
|
Java
|
gpl3
| 18,838
|
/* Copyright (c) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gdata.util.common.base;
/**
* An object that converts literal text into a format safe for inclusion in a
* particular context (such as an XML document). Typically (but not always), the
* inverse process of "unescaping" the text is performed automatically by the
* relevant parser.
*
* <p>For example, an XML escaper would convert the literal string {@code
* "Foo<Bar>"} into {@code "Foo<Bar>"} to prevent {@code "<Bar>"} from
* being confused with an XML tag. When the resulting XML document is parsed,
* the parser API will return this text as the original literal string {@code
* "Foo<Bar>"}.
*
* <p>An {@code Escaper} instance is required to be stateless, and safe when
* used concurrently by multiple threads.
*
* <p>Several popular escapers are defined as constants in the class {@link
* CharEscapers}. To create your own escapers, use {@link
* CharEscaperBuilder}, or extend {@link CharEscaper} or {@code UnicodeEscaper}.
*
*
*/
public interface Escaper {
/**
* Returns the escaped form of a given literal string.
*
* <p>Note that this method may treat input characters differently depending on
* the specific escaper implementation.
* <ul>
* <li>{@link UnicodeEscaper} handles
* <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> correctly,
* including surrogate character pairs. If the input is badly formed the
* escaper should throw {@link IllegalArgumentException}.
* <li>{@link CharEscaper} handles Java characters independently and does not
* verify the input for well formed characters. A CharEscaper should not be
* used in situations where input is not guaranteed to be restricted to the
* Basic Multilingual Plane (BMP).
* </ul>
*
* @param string the literal string to be escaped
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if {@code string} contains badly formed
* UTF-16 or cannot be escaped for any other reason
*/
public String escape(String string);
/**
* Returns an {@code Appendable} instance which automatically escapes all
* text appended to it before passing the resulting text to an underlying
* {@code Appendable}.
*
* <p>Note that this method may treat input characters differently depending on
* the specific escaper implementation.
* <ul>
* <li>{@link UnicodeEscaper} handles
* <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> correctly,
* including surrogate character pairs. If the input is badly formed the
* escaper should throw {@link IllegalArgumentException}.
* <li>{@link CharEscaper} handles Java characters independently and does not
* verify the input for well formed characters. A CharEscaper should not be
* used in situations where input is not guaranteed to be restricted to the
* Basic Multilingual Plane (BMP).
* </ul>
*
* @param out the underlying {@code Appendable} to append escaped output to
* @return an {@code Appendable} which passes text to {@code out} after
* escaping it.
*/
public Appendable escape(Appendable out);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/com/google/gdata/util/common/base/Escaper.java
|
Java
|
gpl3
| 3,773
|
/* Copyright (c) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gdata.util.common.base;
/**
* A {@code UnicodeEscaper} that escapes some set of Java characters using
* the URI percent encoding scheme. The set of safe characters (those which
* remain unescaped) can be specified on construction.
*
* <p>For details on escaping URIs for use in web pages, see section 2.4 of
* <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
*
* <p>In most cases this class should not need to be used directly. If you
* have no special requirements for escaping your URIs, you should use either
* {@link CharEscapers#uriEscaper()} or
* {@link CharEscapers#uriEscaper(boolean)}.
*
* <p>When encoding a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0"
* through "9" remain the same.
* <li>Any additionally specified safe characters remain the same.
* <li>If {@code plusForSpace} was specified, the space character " " is
* converted into a plus sign "+".
* <li>All other characters are converted into one or more bytes using UTF-8
* encoding and each byte is then represented by the 3-character string
* "%XY", where "XY" is the two-digit, uppercase, hexadecimal representation
* of the byte value.
* </ul>
*
* <p>RFC 2396 specifies the set of unreserved characters as "-", "_", ".", "!",
* "~", "*", "'", "(" and ")". It goes on to state:
*
* <p><i>Unreserved characters can be escaped without changing the semantics
* of the URI, but this should not be done unless the URI is being used
* in a context that does not allow the unescaped character to appear.</i>
*
* <p>For performance reasons the only currently supported character encoding of
* this class is UTF-8.
*
* <p><b>Note</b>: This escaper produces uppercase hexidecimal sequences. From
* <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>:<br>
* <i>"URI producers and normalizers should use uppercase hexadecimal digits
* for all percent-encodings."</i>
*
*
*/
public class PercentEscaper extends UnicodeEscaper {
/**
* A string of safe characters that mimics the behavior of
* {@link java.net.URLEncoder}.
*
*/
public static final String SAFECHARS_URLENCODER = "-_.*";
/**
* A string of characters that do not need to be encoded when used in URI
* path segments, as specified in RFC 3986. Note that some of these
* characters do need to be escaped when used in other parts of the URI.
*/
public static final String SAFEPATHCHARS_URLENCODER = "-_.!~*'()@:$&,;=";
/**
* A string of characters that do not need to be encoded when used in URI
* query strings, as specified in RFC 3986. Note that some of these
* characters do need to be escaped when used in other parts of the URI.
*/
public static final String SAFEQUERYSTRINGCHARS_URLENCODER
= "-_.!~*'()@:$,;/?:";
// In some uri escapers spaces are escaped to '+'
private static final char[] URI_ESCAPED_SPACE = { '+' };
private static final char[] UPPER_HEX_DIGITS =
"0123456789ABCDEF".toCharArray();
/**
* If true we should convert space to the {@code +} character.
*/
private final boolean plusForSpace;
/**
* An array of flags where for any {@code char c} if {@code safeOctets[c]} is
* true then {@code c} should remain unmodified in the output. If
* {@code c > safeOctets.length} then it should be escaped.
*/
private final boolean[] safeOctets;
/**
* Constructs a URI escaper with the specified safe characters and optional
* handling of the space character.
*
* @param safeChars a non null string specifying additional safe characters
* for this escaper (the ranges 0..9, a..z and A..Z are always safe and
* should not be specified here)
* @param plusForSpace true if ASCII space should be escaped to {@code +}
* rather than {@code %20}
* @throws IllegalArgumentException if any of the parameters were invalid
*/
public PercentEscaper(String safeChars, boolean plusForSpace) {
// Avoid any misunderstandings about the behavior of this escaper
if (safeChars.matches(".*[0-9A-Za-z].*")) {
throw new IllegalArgumentException(
"Alphanumeric characters are always 'safe' and should not be " +
"explicitly specified");
}
// Avoid ambiguous parameters. Safe characters are never modified so if
// space is a safe character then setting plusForSpace is meaningless.
if (plusForSpace && safeChars.contains(" ")) {
throw new IllegalArgumentException(
"plusForSpace cannot be specified when space is a 'safe' character");
}
if (safeChars.contains("%")) {
throw new IllegalArgumentException(
"The '%' character cannot be specified as 'safe'");
}
this.plusForSpace = plusForSpace;
this.safeOctets = createSafeOctets(safeChars);
}
/**
* Creates a boolean[] with entries corresponding to the character values
* for 0-9, A-Z, a-z and those specified in safeChars set to true. The array
* is as small as is required to hold the given character information.
*/
private static boolean[] createSafeOctets(String safeChars) {
int maxChar = 'z';
char[] safeCharArray = safeChars.toCharArray();
for (char c : safeCharArray) {
maxChar = Math.max(c, maxChar);
}
boolean[] octets = new boolean[maxChar + 1];
for (int c = '0'; c <= '9'; c++) {
octets[c] = true;
}
for (int c = 'A'; c <= 'Z'; c++) {
octets[c] = true;
}
for (int c = 'a'; c <= 'z'; c++) {
octets[c] = true;
}
for (char c : safeCharArray) {
octets[c] = true;
}
return octets;
}
/*
* Overridden for performance. For unescaped strings this improved the
* performance of the uri escaper from ~760ns to ~400ns as measured by
* {@link CharEscapersBenchmark}.
*/
@Override
protected int nextEscapeIndex(CharSequence csq, int index, int end) {
for (; index < end; index++) {
char c = csq.charAt(index);
if (c >= safeOctets.length || !safeOctets[c]) {
break;
}
}
return index;
}
/*
* Overridden for performance. For unescaped strings this improved the
* performance of the uri escaper from ~400ns to ~170ns as measured by
* {@link CharEscapersBenchmark}.
*/
@Override
public String escape(String s) {
int slen = s.length();
for (int index = 0; index < slen; index++) {
char c = s.charAt(index);
if (c >= safeOctets.length || !safeOctets[c]) {
return escapeSlow(s, index);
}
}
return s;
}
/**
* Escapes the given Unicode code point in UTF-8.
*/
@Override
protected char[] escape(int cp) {
// We should never get negative values here but if we do it will throw an
// IndexOutOfBoundsException, so at least it will get spotted.
if (cp < safeOctets.length && safeOctets[cp]) {
return null;
} else if (cp == ' ' && plusForSpace) {
return URI_ESCAPED_SPACE;
} else if (cp <= 0x7F) {
// Single byte UTF-8 characters
// Start with "%--" and fill in the blanks
char[] dest = new char[3];
dest[0] = '%';
dest[2] = UPPER_HEX_DIGITS[cp & 0xF];
dest[1] = UPPER_HEX_DIGITS[cp >>> 4];
return dest;
} else if (cp <= 0x7ff) {
// Two byte UTF-8 characters [cp >= 0x80 && cp <= 0x7ff]
// Start with "%--%--" and fill in the blanks
char[] dest = new char[6];
dest[0] = '%';
dest[3] = '%';
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[1] = UPPER_HEX_DIGITS[0xC | cp];
return dest;
} else if (cp <= 0xffff) {
// Three byte UTF-8 characters [cp >= 0x800 && cp <= 0xffff]
// Start with "%E-%--%--" and fill in the blanks
char[] dest = new char[9];
dest[0] = '%';
dest[1] = 'E';
dest[3] = '%';
dest[6] = '%';
dest[8] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp];
return dest;
} else if (cp <= 0x10ffff) {
char[] dest = new char[12];
// Four byte UTF-8 characters [cp >= 0xffff && cp <= 0x10ffff]
// Start with "%F-%--%--%--" and fill in the blanks
dest[0] = '%';
dest[1] = 'F';
dest[3] = '%';
dest[6] = '%';
dest[9] = '%';
dest[11] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[10] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[8] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp & 0x7];
return dest;
} else {
// If this ever happens it is due to bug in UnicodeEscaper, not bad input.
throw new IllegalArgumentException(
"Invalid unicode character value " + cp);
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/com/google/gdata/util/common/base/PercentEscaper.java
|
Java
|
gpl3
| 9,895
|
/* Copyright (c) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gdata.util.common.base;
import static com.google.gdata.util.common.base.Preconditions.checkNotNull;
import java.io.IOException;
/**
* An {@link Escaper} that converts literal text into a format safe for
* inclusion in a particular context (such as an XML document). Typically (but
* not always), the inverse process of "unescaping" the text is performed
* automatically by the relevant parser.
*
* <p>For example, an XML escaper would convert the literal string {@code
* "Foo<Bar>"} into {@code "Foo<Bar>"} to prevent {@code "<Bar>"} from
* being confused with an XML tag. When the resulting XML document is parsed,
* the parser API will return this text as the original literal string {@code
* "Foo<Bar>"}.
*
* <p><b>Note:</b> This class is similar to {@link CharEscaper} but with one
* very important difference. A CharEscaper can only process Java
* <a href="http://en.wikipedia.org/wiki/UTF-16">UTF16</a> characters in
* isolation and may not cope when it encounters surrogate pairs. This class
* facilitates the correct escaping of all Unicode characters.
*
* <p>As there are important reasons, including potential security issues, to
* handle Unicode correctly if you are considering implementing a new escaper
* you should favor using UnicodeEscaper wherever possible.
*
* <p>A {@code UnicodeEscaper} instance is required to be stateless, and safe
* when used concurrently by multiple threads.
*
* <p>Several popular escapers are defined as constants in the class {@link
* CharEscapers}. To create your own escapers extend this class and implement
* the {@link #escape(int)} method.
*
*
*/
public abstract class UnicodeEscaper implements Escaper {
/** The amount of padding (chars) to use when growing the escape buffer. */
private static final int DEST_PAD = 32;
/**
* Returns the escaped form of the given Unicode code point, or {@code null}
* if this code point does not need to be escaped. When called as part of an
* escaping operation, the given code point is guaranteed to be in the range
* {@code 0 <= cp <= Character#MAX_CODE_POINT}.
*
* <p>If an empty array is returned, this effectively strips the input
* character from the resulting text.
*
* <p>If the character does not need to be escaped, this method should return
* {@code null}, rather than an array containing the character representation
* of the code point. This enables the escaping algorithm to perform more
* efficiently.
*
* <p>If the implementation of this method cannot correctly handle a
* particular code point then it should either throw an appropriate runtime
* exception or return a suitable replacement character. It must never
* silently discard invalid input as this may constitute a security risk.
*
* @param cp the Unicode code point to escape if necessary
* @return the replacement characters, or {@code null} if no escaping was
* needed
*/
protected abstract char[] escape(int cp);
/**
* Scans a sub-sequence of characters from a given {@link CharSequence},
* returning the index of the next character that requires escaping.
*
* <p><b>Note:</b> When implementing an escaper, it is a good idea to override
* this method for efficiency. The base class implementation determines
* successive Unicode code points and invokes {@link #escape(int)} for each of
* them. If the semantics of your escaper are such that code points in the
* supplementary range are either all escaped or all unescaped, this method
* can be implemented more efficiently using {@link CharSequence#charAt(int)}.
*
* <p>Note however that if your escaper does not escape characters in the
* supplementary range, you should either continue to validate the correctness
* of any surrogate characters encountered or provide a clear warning to users
* that your escaper does not validate its input.
*
* <p>See {@link PercentEscaper} for an example.
*
* @param csq a sequence of characters
* @param start the index of the first character to be scanned
* @param end the index immediately after the last character to be scanned
* @throws IllegalArgumentException if the scanned sub-sequence of {@code csq}
* contains invalid surrogate pairs
*/
protected int nextEscapeIndex(CharSequence csq, int start, int end) {
int index = start;
while (index < end) {
int cp = codePointAt(csq, index, end);
if (cp < 0 || escape(cp) != null) {
break;
}
index += Character.isSupplementaryCodePoint(cp) ? 2 : 1;
}
return index;
}
/**
* Returns the escaped form of a given literal string.
*
* <p>If you are escaping input in arbitrary successive chunks, then it is not
* generally safe to use this method. If an input string ends with an
* unmatched high surrogate character, then this method will throw
* {@link IllegalArgumentException}. You should either ensure your input is
* valid <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> before
* calling this method or use an escaped {@link Appendable} (as returned by
* {@link #escape(Appendable)}) which can cope with arbitrarily split input.
*
* <p><b>Note:</b> When implementing an escaper it is a good idea to override
* this method for efficiency by inlining the implementation of
* {@link #nextEscapeIndex(CharSequence, int, int)} directly. Doing this for
* {@link PercentEscaper} more than doubled the performance for unescaped
* strings (as measured by {@link CharEscapersBenchmark}).
*
* @param string the literal string to be escaped
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if invalid surrogate characters are
* encountered
*/
public String escape(String string) {
int end = string.length();
int index = nextEscapeIndex(string, 0, end);
return index == end ? string : escapeSlow(string, index);
}
/**
* Returns the escaped form of a given literal string, starting at the given
* index. This method is called by the {@link #escape(String)} method when it
* discovers that escaping is required. It is protected to allow subclasses
* to override the fastpath escaping function to inline their escaping test.
* See {@link CharEscaperBuilder} for an example usage.
*
* <p>This method is not reentrant and may only be invoked by the top level
* {@link #escape(String)} method.
*
* @param s the literal string to be escaped
* @param index the index to start escaping from
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if invalid surrogate characters are
* encountered
*/
protected final String escapeSlow(String s, int index) {
int end = s.length();
// Get a destination buffer and setup some loop variables.
char[] dest = DEST_TL.get();
int destIndex = 0;
int unescapedChunkStart = 0;
while (index < end) {
int cp = codePointAt(s, index, end);
if (cp < 0) {
throw new IllegalArgumentException(
"Trailing high surrogate at end of input");
}
char[] escaped = escape(cp);
if (escaped != null) {
int charsSkipped = index - unescapedChunkStart;
// This is the size needed to add the replacement, not the full
// size needed by the string. We only regrow when we absolutely must.
int sizeNeeded = destIndex + charsSkipped + escaped.length;
if (dest.length < sizeNeeded) {
int destLength = sizeNeeded + (end - index) + DEST_PAD;
dest = growBuffer(dest, destIndex, destLength);
}
// If we have skipped any characters, we need to copy them now.
if (charsSkipped > 0) {
s.getChars(unescapedChunkStart, index, dest, destIndex);
destIndex += charsSkipped;
}
if (escaped.length > 0) {
System.arraycopy(escaped, 0, dest, destIndex, escaped.length);
destIndex += escaped.length;
}
}
unescapedChunkStart
= index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1);
index = nextEscapeIndex(s, unescapedChunkStart, end);
}
// Process trailing unescaped characters - no need to account for escaped
// length or padding the allocation.
int charsSkipped = end - unescapedChunkStart;
if (charsSkipped > 0) {
int endIndex = destIndex + charsSkipped;
if (dest.length < endIndex) {
dest = growBuffer(dest, destIndex, endIndex);
}
s.getChars(unescapedChunkStart, end, dest, destIndex);
destIndex = endIndex;
}
return new String(dest, 0, destIndex);
}
/**
* Returns an {@code Appendable} instance which automatically escapes all
* text appended to it before passing the resulting text to an underlying
* {@code Appendable}.
*
* <p>Unlike {@link #escape(String)} it is permitted to append arbitrarily
* split input to this Appendable, including input that is split over a
* surrogate pair. In this case the pending high surrogate character will not
* be processed until the corresponding low surrogate is appended. This means
* that a trailing high surrogate character at the end of the input cannot be
* detected and will be silently ignored. This is unavoidable since the
* Appendable interface has no {@code close()} method, and it is impossible to
* determine when the last characters have been appended.
*
* <p>The methods of the returned object will propagate any exceptions thrown
* by the underlying {@code Appendable}.
*
* <p>For well formed <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a>
* the escaping behavior is identical to that of {@link #escape(String)} and
* the following code is equivalent to (but much slower than)
* {@code escaper.escape(string)}: <pre>{@code
*
* StringBuilder sb = new StringBuilder();
* escaper.escape(sb).append(string);
* return sb.toString();}</pre>
*
* @param out the underlying {@code Appendable} to append escaped output to
* @return an {@code Appendable} which passes text to {@code out} after
* escaping it
* @throws NullPointerException if {@code out} is null
* @throws IllegalArgumentException if invalid surrogate characters are
* encountered
*
*/
public Appendable escape(final Appendable out) {
checkNotNull(out);
return new Appendable() {
int pendingHighSurrogate = -1;
char[] decodedChars = new char[2];
public Appendable append(CharSequence csq) throws IOException {
return append(csq, 0, csq.length());
}
public Appendable append(CharSequence csq, int start, int end)
throws IOException {
int index = start;
if (index < end) {
// This is a little subtle: index must never reference the middle of a
// surrogate pair but unescapedChunkStart can. The first time we enter
// the loop below it is possible that index != unescapedChunkStart.
int unescapedChunkStart = index;
if (pendingHighSurrogate != -1) {
// Our last append operation ended halfway through a surrogate pair
// so we have to do some extra work first.
char c = csq.charAt(index++);
if (!Character.isLowSurrogate(c)) {
throw new IllegalArgumentException(
"Expected low surrogate character but got " + c);
}
char[] escaped =
escape(Character.toCodePoint((char) pendingHighSurrogate, c));
if (escaped != null) {
// Emit the escaped character and adjust unescapedChunkStart to
// skip the low surrogate we have consumed.
outputChars(escaped, escaped.length);
unescapedChunkStart += 1;
} else {
// Emit pending high surrogate (unescaped) but do not modify
// unescapedChunkStart as we must still emit the low surrogate.
out.append((char) pendingHighSurrogate);
}
pendingHighSurrogate = -1;
}
while (true) {
// Find and append the next subsequence of unescaped characters.
index = nextEscapeIndex(csq, index, end);
if (index > unescapedChunkStart) {
out.append(csq, unescapedChunkStart, index);
}
if (index == end) {
break;
}
// If we are not finished, calculate the next code point.
int cp = codePointAt(csq, index, end);
if (cp < 0) {
// Our sequence ended half way through a surrogate pair so just
// record the state and exit.
pendingHighSurrogate = -cp;
break;
}
// Escape the code point and output the characters.
char[] escaped = escape(cp);
if (escaped != null) {
outputChars(escaped, escaped.length);
} else {
// This shouldn't really happen if nextEscapeIndex is correct but
// we should cope with false positives.
int len = Character.toChars(cp, decodedChars, 0);
outputChars(decodedChars, len);
}
// Update our index past the escaped character and continue.
index += (Character.isSupplementaryCodePoint(cp) ? 2 : 1);
unescapedChunkStart = index;
}
}
return this;
}
public Appendable append(char c) throws IOException {
if (pendingHighSurrogate != -1) {
// Our last append operation ended halfway through a surrogate pair
// so we have to do some extra work first.
if (!Character.isLowSurrogate(c)) {
throw new IllegalArgumentException(
"Expected low surrogate character but got '" + c +
"' with value " + (int) c);
}
char[] escaped =
escape(Character.toCodePoint((char) pendingHighSurrogate, c));
if (escaped != null) {
outputChars(escaped, escaped.length);
} else {
out.append((char) pendingHighSurrogate);
out.append(c);
}
pendingHighSurrogate = -1;
} else if (Character.isHighSurrogate(c)) {
// This is the start of a (split) surrogate pair.
pendingHighSurrogate = c;
} else {
if (Character.isLowSurrogate(c)) {
throw new IllegalArgumentException(
"Unexpected low surrogate character '" + c +
"' with value " + (int) c);
}
// This is a normal (non surrogate) char.
char[] escaped = escape(c);
if (escaped != null) {
outputChars(escaped, escaped.length);
} else {
out.append(c);
}
}
return this;
}
private void outputChars(char[] chars, int len) throws IOException {
for (int n = 0; n < len; n++) {
out.append(chars[n]);
}
}
};
}
/**
* Returns the Unicode code point of the character at the given index.
*
* <p>Unlike {@link Character#codePointAt(CharSequence, int)} or
* {@link String#codePointAt(int)} this method will never fail silently when
* encountering an invalid surrogate pair.
*
* <p>The behaviour of this method is as follows:
* <ol>
* <li>If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown.
* <li><b>If the character at the specified index is not a surrogate, it is
* returned.</b>
* <li>If the first character was a high surrogate value, then an attempt is
* made to read the next character.
* <ol>
* <li><b>If the end of the sequence was reached, the negated value of
* the trailing high surrogate is returned.</b>
* <li><b>If the next character was a valid low surrogate, the code point
* value of the high/low surrogate pair is returned.</b>
* <li>If the next character was not a low surrogate value, then
* {@link IllegalArgumentException} is thrown.
* </ol>
* <li>If the first character was a low surrogate value,
* {@link IllegalArgumentException} is thrown.
* </ol>
*
* @param seq the sequence of characters from which to decode the code point
* @param index the index of the first character to decode
* @param end the index beyond the last valid character to decode
* @return the Unicode code point for the given index or the negated value of
* the trailing high surrogate character at the end of the sequence
*/
protected static final int codePointAt(CharSequence seq, int index, int end) {
if (index < end) {
char c1 = seq.charAt(index++);
if (c1 < Character.MIN_HIGH_SURROGATE ||
c1 > Character.MAX_LOW_SURROGATE) {
// Fast path (first test is probably all we need to do)
return c1;
} else if (c1 <= Character.MAX_HIGH_SURROGATE) {
// If the high surrogate was the last character, return its inverse
if (index == end) {
return -c1;
}
// Otherwise look for the low surrogate following it
char c2 = seq.charAt(index);
if (Character.isLowSurrogate(c2)) {
return Character.toCodePoint(c1, c2);
}
throw new IllegalArgumentException(
"Expected low surrogate but got char '" + c2 +
"' with value " + (int) c2 + " at index " + index);
} else {
throw new IllegalArgumentException(
"Unexpected low surrogate character '" + c1 +
"' with value " + (int) c1 + " at index " + (index - 1));
}
}
throw new IndexOutOfBoundsException("Index exceeds specified range");
}
/**
* Helper method to grow the character buffer as needed, this only happens
* once in a while so it's ok if it's in a method call. If the index passed
* in is 0 then no copying will be done.
*/
private static final char[] growBuffer(char[] dest, int index, int size) {
char[] copy = new char[size];
if (index > 0) {
System.arraycopy(dest, 0, copy, 0, index);
}
return copy;
}
/**
* A thread-local destination buffer to keep us from creating new buffers.
* The starting size is 1024 characters. If we grow past this we don't
* put it back in the threadlocal, we just keep going and grow as needed.
*/
private static final ThreadLocal<char[]> DEST_TL = new ThreadLocal<char[]>() {
@Override
protected char[] initialValue() {
return new char[1024];
}
};
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/com/google/gdata/util/common/base/UnicodeEscaper.java
|
Java
|
gpl3
| 19,518
|
/*
* Copyright (c) 2009 Matthias Kaeppler Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package oauth.signpost;
import java.io.Serializable;
import java.util.Map;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import oauth.signpost.http.HttpParameters;
/**
* <p>
* Supplies an interface that can be used to retrieve request and access tokens
* from an OAuth 1.0(a) service provider. A provider object requires an
* {@link OAuthConsumer} to sign the token request message; after a token has
* been retrieved, the consumer is automatically updated with the token and the
* corresponding secret.
* </p>
* <p>
* To initiate the token exchange, create a new provider instance and configure
* it with the URLs the service provider exposes for requesting tokens and
* resource authorization, e.g.:
* </p>
*
* <pre>
* OAuthProvider provider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
* "http://twitter.com/oauth/access_token", "http://twitter.com/oauth/authorize");
* </pre>
* <p>
* Depending on the HTTP library you use, you may need a different provider
* type, refer to the website documentation for how to do that.
* </p>
* <p>
* To receive a request token which the user must authorize, you invoke it using
* a consumer instance and a callback URL:
* </p>
* <p>
*
* <pre>
* String url = provider.retrieveRequestToken(consumer, "http://www.example.com/callback");
* </pre>
*
* </p>
* <p>
* That url must be opened in a Web browser, where the user can grant access to
* the resources in question. If that succeeds, the service provider will
* redirect to the callback URL and append the blessed request token.
* </p>
* <p>
* That token must now be exchanged for an access token, as such:
* </p>
* <p>
*
* <pre>
* provider.retrieveAccessToken(consumer, nullOrVerifierCode);
* </pre>
*
* </p>
* <p>
* where nullOrVerifierCode is either null if your provided a callback URL in
* the previous step, or the pin code issued by the service provider to the user
* if the request was out-of-band (cf. {@link OAuth#OUT_OF_BAND}.
* </p>
* <p>
* The consumer used during token handshakes is now ready for signing.
* </p>
*
* @see DefaultOAuthProvider
* @see DefaultOAuthConsumer
* @see OAuthProviderListener
*/
public interface OAuthProvider extends Serializable {
/**
* Queries the service provider for a request token.
* <p>
* <b>Pre-conditions:</b> the given {@link OAuthConsumer} must have a valid
* consumer key and consumer secret already set.
* </p>
* <p>
* <b>Post-conditions:</b> the given {@link OAuthConsumer} will have an
* unauthorized request token and token secret set.
* </p>
*
* @param consumer
* the {@link OAuthConsumer} that should be used to sign the request
* @param callbackUrl
* Pass an actual URL if your app can receive callbacks and you want
* to get informed about the result of the authorization process.
* Pass {@link OAuth.OUT_OF_BAND} if the service provider implements
* OAuth 1.0a and your app cannot receive callbacks. Pass null if the
* service provider implements OAuth 1.0 and your app cannot receive
* callbacks. Please note that some services (among them Twitter)
* will fail authorization if you pass a callback URL but register
* your application as a desktop app (which would only be able to
* handle OOB requests).
* @return The URL to which the user must be sent in order to authorize the
* consumer. It includes the unauthorized request token (and in the
* case of OAuth 1.0, the callback URL -- 1.0a clients send along
* with the token request).
* @throws OAuthMessageSignerException
* if signing the request failed
* @throws OAuthNotAuthorizedException
* if the service provider rejected the consumer
* @throws OAuthExpectationFailedException
* if required parameters were not correctly set by the consumer or
* service provider
* @throws OAuthCommunicationException
* if server communication failed
*/
public String retrieveRequestToken(OAuthConsumer consumer, String callbackUrl)
throws OAuthMessageSignerException, OAuthNotAuthorizedException,
OAuthExpectationFailedException, OAuthCommunicationException;
/**
* Queries the service provider for an access token.
* <p>
* <b>Pre-conditions:</b> the given {@link OAuthConsumer} must have a valid
* consumer key, consumer secret, authorized request token and token secret
* already set.
* </p>
* <p>
* <b>Post-conditions:</b> the given {@link OAuthConsumer} will have an
* access token and token secret set.
* </p>
*
* @param consumer
* the {@link OAuthConsumer} that should be used to sign the request
* @param oauthVerifier
* <b>NOTE: Only applies to service providers implementing OAuth
* 1.0a. Set to null if the service provider is still using OAuth
* 1.0.</b> The verification code issued by the service provider
* after the the user has granted the consumer authorization. If the
* callback method provided in the previous step was
* {@link OAuth.OUT_OF_BAND}, then you must ask the user for this
* value. If your app has received a callback, the verfication code
* was passed as part of that request instead.
* @throws OAuthMessageSignerException
* if signing the request failed
* @throws OAuthNotAuthorizedException
* if the service provider rejected the consumer
* @throws OAuthExpectationFailedException
* if required parameters were not correctly set by the consumer or
* service provider
* @throws OAuthCommunicationException
* if server communication failed
*/
public void retrieveAccessToken(OAuthConsumer consumer, String oauthVerifier)
throws OAuthMessageSignerException, OAuthNotAuthorizedException,
OAuthExpectationFailedException, OAuthCommunicationException;
/**
* Any additional non-OAuth parameters returned in the response body of a
* token request can be obtained through this method. These parameters will
* be preserved until the next token request is issued. The return value is
* never null.
*/
public HttpParameters getResponseParameters();
/**
* Subclasses must use this setter to preserve any non-OAuth query
* parameters contained in the server response. It's the caller's
* responsibility that any OAuth parameters be removed beforehand.
*
* @param parameters
* the map of query parameters served by the service provider in the
* token response
*/
public void setResponseParameters(HttpParameters parameters);
/**
* Use this method to set custom HTTP headers to be used for the requests
* which are sent to retrieve tokens. @deprecated THIS METHOD HAS BEEN
* DEPRECATED. Use {@link OAuthProviderListener} to customize requests.
*
* @param header
* The header name (e.g. 'WWW-Authenticate')
* @param value
* The header value (e.g. 'realm=www.example.com')
*/
@Deprecated
public void setRequestHeader(String header, String value);
/**
* @deprecated THIS METHOD HAS BEEN DEPRECATED. Use
* {@link OAuthProviderListener} to customize requests.
* @return all request headers set via {@link #setRequestHeader}
*/
@Deprecated
public Map<String, String> getRequestHeaders();
/**
* @param isOAuth10aProvider
* set to true if the service provider supports OAuth 1.0a. Note that
* you need only call this method if you reconstruct a provider
* object in between calls to retrieveRequestToken() and
* retrieveAccessToken() (i.e. if the object state isn't preserved).
* If instead those two methods are called on the same provider
* instance, this flag will be deducted automatically based on the
* server response during retrieveRequestToken(), so you can simply
* ignore this method.
*/
public void setOAuth10a(boolean isOAuth10aProvider);
/**
* @return true if the service provider supports OAuth 1.0a. Note that the
* value returned here is only meaningful after you have already
* performed the token handshake, otherwise there is no way to
* determine what version of the OAuth protocol the service provider
* implements.
*/
public boolean isOAuth10a();
public String getRequestTokenEndpointUrl();
public String getAccessTokenEndpointUrl();
public String getAuthorizationWebsiteUrl();
public void setListener(OAuthProviderListener listener);
public void removeListener(OAuthProviderListener listener);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/OAuthProvider.java
|
Java
|
gpl3
| 10,024
|
package oauth.signpost;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpResponse;
/**
* Provides hooks into the token request handling procedure executed by
* {@link OAuthProvider}.
*
* @author Matthias Kaeppler
*/
public interface OAuthProviderListener {
/**
* Called after the request has been created and default headers added, but
* before the request has been signed.
*
* @param request
* the request to be sent
* @throws Exception
*/
void prepareRequest(HttpRequest request) throws Exception;
/**
* Called after the request has been signed, but before it's being sent.
*
* @param request
* the request to be sent
* @throws Exception
*/
void prepareSubmission(HttpRequest request) throws Exception;
/**
* Called when the server response has been received. You can implement this
* to manually handle the response data.
*
* @param request
* the request that was sent
* @param response
* the response that was received
* @return returning true means you have handled the response, and the
* provider will return immediately. Return false to let the event
* propagate and let the provider execute its default response
* handling.
* @throws Exception
*/
boolean onResponseReceived(HttpRequest request, HttpResponse response) throws Exception;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/OAuthProviderListener.java
|
Java
|
gpl3
| 1,489
|
/* Copyright (c) 2009 Matthias Kaeppler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oauth.signpost;
import java.io.Serializable;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.http.HttpParameters;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.signature.AuthorizationHeaderSigningStrategy;
import oauth.signpost.signature.HmacSha1MessageSigner;
import oauth.signpost.signature.OAuthMessageSigner;
import oauth.signpost.signature.PlainTextMessageSigner;
import oauth.signpost.signature.QueryStringSigningStrategy;
import oauth.signpost.signature.SigningStrategy;
/**
* <p>
* Exposes a simple interface to sign HTTP requests using a given OAuth token
* and secret. Refer to {@link OAuthProvider} how to retrieve a valid token and
* token secret.
* </p>
* <p>
* HTTP messages are signed as follows:
* <p>
*
* <pre>
* // exchange the arguments with the actual token/secret pair
* OAuthConsumer consumer = new DefaultOAuthConsumer("1234", "5678");
*
* URL url = new URL("http://example.com/protected.xml");
* HttpURLConnection request = (HttpURLConnection) url.openConnection();
*
* consumer.sign(request);
*
* request.connect();
* </pre>
*
* </p>
* </p>
*
* @author Matthias Kaeppler
*/
public interface OAuthConsumer extends Serializable {
/**
* Sets the message signer that should be used to generate the OAuth
* signature.
*
* @param messageSigner
* the signer
* @see HmacSha1MessageSigner
* @see PlainTextMessageSigner
*/
public void setMessageSigner(OAuthMessageSigner messageSigner);
/**
* Allows you to add parameters (typically OAuth parameters such as
* oauth_callback or oauth_verifier) which will go directly into the signer,
* i.e. you don't have to put them into the request first. The consumer's
* {@link SigningStrategy} will then take care of writing them to the
* correct part of the request before it is sent. Note that these parameters
* are expected to already be percent encoded -- they will be simply merged
* as-is.
*
* @param additionalParameters
* the parameters
*/
public void setAdditionalParameters(HttpParameters additionalParameters);
/**
* Defines which strategy should be used to write a signature to an HTTP
* request.
*
* @param signingStrategy
* the strategy
* @see AuthorizationHeaderSigningStrategy
* @see QueryStringSigningStrategy
*/
public void setSigningStrategy(SigningStrategy signingStrategy);
/**
* <p>
* Causes the consumer to always include the oauth_token parameter to be
* sent, even if blank. If you're seeing 401s during calls to
* {@link OAuthProvider#retrieveRequestToken}, try setting this to true.
* </p>
*
* @param enable
* true or false
*/
public void setSendEmptyTokens(boolean enable);
/**
* Signs the given HTTP request by writing an OAuth signature (and other
* required OAuth parameters) to it. Where these parameters are written
* depends on the current {@link SigningStrategy}.
*
* @param request
* the request to sign
* @return the request object passed as an argument
* @throws OAuthMessageSignerException
* @throws OAuthExpectationFailedException
* @throws OAuthCommunicationException
*/
public HttpRequest sign(HttpRequest request) throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException;
/**
* <p>
* Signs the given HTTP request by writing an OAuth signature (and other
* required OAuth parameters) to it. Where these parameters are written
* depends on the current {@link SigningStrategy}.
* </p>
* This method accepts HTTP library specific request objects; the consumer
* implementation must ensure that only those request types are passed which
* it supports.
*
* @param request
* the request to sign
* @return the request object passed as an argument
* @throws OAuthMessageSignerException
* @throws OAuthExpectationFailedException
* @throws OAuthCommunicationException
*/
public HttpRequest sign(Object request) throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException;
/**
* <p>
* "Signs" the given URL by appending all OAuth parameters to it which are
* required for message signing. The assumed HTTP method is GET.
* Essentially, this is equivalent to signing an HTTP GET request, but it
* can be useful if your application requires clickable links to protected
* resources, i.e. when your application does not have access to the actual
* request that is being sent.
* </p>
*
* @param url
* the input URL. May have query parameters.
* @return the input URL, with all necessary OAuth parameters attached as a
* query string. Existing query parameters are preserved.
* @throws OAuthMessageSignerException
* @throws OAuthExpectationFailedException
* @throws OAuthCommunicationException
*/
public String sign(String url) throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException;
/**
* Sets the OAuth token and token secret used for message signing.
*
* @param token
* the token
* @param tokenSecret
* the token secret
*/
public void setTokenWithSecret(String token, String tokenSecret);
public String getToken();
public String getTokenSecret();
public String getConsumerKey();
public String getConsumerSecret();
/**
* Returns all parameters collected from the HTTP request during message
* signing (this means the return value may be NULL before a call to
* {@link #sign}), plus all required OAuth parameters that were added
* because the request didn't contain them beforehand. In other words, this
* is the exact set of parameters that were used for creating the message
* signature.
*
* @return the request parameters used for message signing
*/
public HttpParameters getRequestParameters();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/OAuthConsumer.java
|
Java
|
gpl3
| 7,051
|
/* Copyright (c) 2008, 2009 Netflix, Matthias Kaeppler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oauth.signpost.http;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import oauth.signpost.OAuth;
/**
* A multi-map of HTTP request parameters. Each key references a
* {@link SortedSet} of parameters collected from the request during message
* signing. Parameter values are sorted as per {@linkplain http
* ://oauth.net/core/1.0a/#anchor13}. Every key/value pair will be
* percent-encoded upon insertion. This class has special semantics tailored to
* being useful for message signing; it's not a general purpose collection class
* to handle request parameters.
*
* @author Matthias Kaeppler
*/
@SuppressWarnings("serial")
public class HttpParameters implements Map<String, SortedSet<String>>, Serializable {
private TreeMap<String, SortedSet<String>> wrappedMap = new TreeMap<String, SortedSet<String>>();
public SortedSet<String> put(String key, SortedSet<String> value) {
return wrappedMap.put(key, value);
}
public SortedSet<String> put(String key, SortedSet<String> values, boolean percentEncode) {
if (percentEncode) {
remove(key);
for (String v : values) {
put(key, v, true);
}
return get(key);
} else {
return wrappedMap.put(key, values);
}
}
/**
* Convenience method to add a single value for the parameter specified by
* 'key'.
*
* @param key
* the parameter name
* @param value
* the parameter value
* @return the value
*/
public String put(String key, String value) {
return put(key, value, false);
}
/**
* Convenience method to add a single value for the parameter specified by
* 'key'.
*
* @param key
* the parameter name
* @param value
* the parameter value
* @param percentEncode
* whether key and value should be percent encoded before being
* inserted into the map
* @return the value
*/
public String put(String key, String value, boolean percentEncode) {
SortedSet<String> values = wrappedMap.get(key);
if (values == null) {
values = new TreeSet<String>();
wrappedMap.put(percentEncode ? OAuth.percentEncode(key) : key, values);
}
if (value != null) {
value = percentEncode ? OAuth.percentEncode(value) : value;
values.add(value);
}
return value;
}
/**
* Convenience method to allow for storing null values. {@link #put} doesn't
* allow null values, because that would be ambiguous.
*
* @param key
* the parameter name
* @param nullString
* can be anything, but probably... null?
* @return null
*/
public String putNull(String key, String nullString) {
return put(key, nullString);
}
public void putAll(Map<? extends String, ? extends SortedSet<String>> m) {
wrappedMap.putAll(m);
}
public void putAll(Map<? extends String, ? extends SortedSet<String>> m, boolean percentEncode) {
if (percentEncode) {
for (String key : m.keySet()) {
put(key, m.get(key), true);
}
} else {
wrappedMap.putAll(m);
}
}
public void putAll(String[] keyValuePairs, boolean percentEncode) {
for (int i = 0; i < keyValuePairs.length - 1; i += 2) {
this.put(keyValuePairs[i], keyValuePairs[i + 1], percentEncode);
}
}
/**
* Convenience method to merge a Map<String, List<String>>.
*
* @param m
* the map
*/
public void putMap(Map<String, List<String>> m) {
for (String key : m.keySet()) {
SortedSet<String> vals = get(key);
if (vals == null) {
vals = new TreeSet<String>();
put(key, vals);
}
vals.addAll(m.get(key));
}
}
public SortedSet<String> get(Object key) {
return wrappedMap.get(key);
}
/**
* Convenience method for {@link #getFirst(key, false)}.
*
* @param key
* the parameter name (must be percent encoded if it contains unsafe
* characters!)
* @return the first value found for this parameter
*/
public String getFirst(Object key) {
return getFirst(key, false);
}
/**
* Returns the first value from the set of all values for the given
* parameter name. If the key passed to this method contains special
* characters, you MUST first percent encode it using
* {@link OAuth#percentEncode(String)}, otherwise the lookup will fail
* (that's because upon storing values in this map, keys get
* percent-encoded).
*
* @param key
* the parameter name (must be percent encoded if it contains unsafe
* characters!)
* @param percentDecode
* whether the value being retrieved should be percent decoded
* @return the first value found for this parameter
*/
public String getFirst(Object key, boolean percentDecode) {
SortedSet<String> values = wrappedMap.get(key);
if (values == null || values.isEmpty()) {
return null;
}
String value = values.first();
return percentDecode ? OAuth.percentDecode(value) : value;
}
/**
* Concatenates all values for the given key to a list of key/value pairs
* suitable for use in a URL query string.
*
* @param key
* the parameter name
* @return the query string
*/
public String getAsQueryString(Object key) {
StringBuilder sb = new StringBuilder();
key = OAuth.percentEncode((String) key);
Set<String> values = wrappedMap.get(key);
if (values == null) {
return key + "=";
}
Iterator<String> iter = values.iterator();
while (iter.hasNext()) {
sb.append(key + "=" + iter.next());
if (iter.hasNext()) {
sb.append("&");
}
}
return sb.toString();
}
public String getAsHeaderElement(String key) {
String value = getFirst(key);
if (value == null) {
return null;
}
return key + "=\"" + value + "\"";
}
public boolean containsKey(Object key) {
return wrappedMap.containsKey(key);
}
public boolean containsValue(Object value) {
for (Set<String> values : wrappedMap.values()) {
if (values.contains(value)) {
return true;
}
}
return false;
}
public int size() {
int count = 0;
for (String key : wrappedMap.keySet()) {
count += wrappedMap.get(key).size();
}
return count;
}
public boolean isEmpty() {
return wrappedMap.isEmpty();
}
public void clear() {
wrappedMap.clear();
}
public SortedSet<String> remove(Object key) {
return wrappedMap.remove(key);
}
public Set<String> keySet() {
return wrappedMap.keySet();
}
public Collection<SortedSet<String>> values() {
return wrappedMap.values();
}
public Set<java.util.Map.Entry<String, SortedSet<String>>> entrySet() {
return wrappedMap.entrySet();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/http/HttpParameters.java
|
Java
|
gpl3
| 8,242
|
package oauth.signpost.http;
import java.io.IOException;
import java.io.InputStream;
public interface HttpResponse {
int getStatusCode() throws IOException;
String getReasonPhrase() throws Exception;
InputStream getContent() throws IOException;
/**
* Returns the underlying response object, in case you need to work on it
* directly.
*
* @return the wrapped response object
*/
Object unwrap();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/http/HttpResponse.java
|
Java
|
gpl3
| 448
|
package oauth.signpost.http;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.HttpURLConnectionRequestAdapter;
/**
* A concise description of an HTTP request. Contains methods to access all
* those parts of an HTTP request which Signpost needs to sign a message. If you
* want to extend Signpost to sign a different kind of HTTP request than those
* currently supported, you'll have to write an adapter which implements this
* interface and a custom {@link OAuthConsumer} which performs the wrapping.
*
* @see HttpURLConnectionRequestAdapter
* @author Matthias Kaeppler
*/
public interface HttpRequest {
String getMethod();
String getRequestUrl();
void setRequestUrl(String url);
void setHeader(String name, String value);
String getHeader(String name);
Map<String, String> getAllHeaders();
InputStream getMessagePayload() throws IOException;
String getContentType();
/**
* Returns the wrapped request object, in case you must work directly on it.
*
* @return the wrapped request object
*/
Object unwrap();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/http/HttpRequest.java
|
Java
|
gpl3
| 1,186
|
/* Copyright (c) 2009 Matthias Kaeppler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oauth.signpost;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import oauth.signpost.basic.UrlStringRequestAdapter;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.http.HttpParameters;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.signature.AuthorizationHeaderSigningStrategy;
import oauth.signpost.signature.HmacSha1MessageSigner;
import oauth.signpost.signature.OAuthMessageSigner;
import oauth.signpost.signature.QueryStringSigningStrategy;
import oauth.signpost.signature.SigningStrategy;
/**
* ABC for consumer implementations. If you're developing a custom consumer you
* will probably inherit from this class to save you a lot of work.
*
* @author Matthias Kaeppler
*/
public abstract class AbstractOAuthConsumer implements OAuthConsumer {
private static final long serialVersionUID = 1L;
private String consumerKey, consumerSecret;
private String token;
private OAuthMessageSigner messageSigner;
private SigningStrategy signingStrategy;
// these are params that may be passed to the consumer directly (i.e.
// without going through the request object)
private HttpParameters additionalParameters;
// these are the params which will be passed to the message signer
private HttpParameters requestParameters;
private boolean sendEmptyTokens;
public AbstractOAuthConsumer(String consumerKey, String consumerSecret) {
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
setMessageSigner(new HmacSha1MessageSigner());
setSigningStrategy(new AuthorizationHeaderSigningStrategy());
}
public void setMessageSigner(OAuthMessageSigner messageSigner) {
this.messageSigner = messageSigner;
messageSigner.setConsumerSecret(consumerSecret);
}
public void setSigningStrategy(SigningStrategy signingStrategy) {
this.signingStrategy = signingStrategy;
}
public void setAdditionalParameters(HttpParameters additionalParameters) {
this.additionalParameters = additionalParameters;
}
public HttpRequest sign(HttpRequest request) throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException {
if (consumerKey == null) {
throw new OAuthExpectationFailedException("consumer key not set");
}
if (consumerSecret == null) {
throw new OAuthExpectationFailedException("consumer secret not set");
}
requestParameters = new HttpParameters();
try {
if (additionalParameters != null) {
requestParameters.putAll(additionalParameters, false);
}
collectHeaderParameters(request, requestParameters);
collectQueryParameters(request, requestParameters);
collectBodyParameters(request, requestParameters);
// add any OAuth params that haven't already been set
completeOAuthParameters(requestParameters);
requestParameters.remove(OAuth.OAUTH_SIGNATURE);
} catch (IOException e) {
throw new OAuthCommunicationException(e);
}
String signature = messageSigner.sign(request, requestParameters);
OAuth.debugOut("signature", signature);
signingStrategy.writeSignature(signature, request, requestParameters);
OAuth.debugOut("Auth header", request.getHeader("Authorization"));
OAuth.debugOut("Request URL", request.getRequestUrl());
return request;
}
public HttpRequest sign(Object request) throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException {
return sign(wrap(request));
}
public String sign(String url) throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException {
HttpRequest request = new UrlStringRequestAdapter(url);
// switch to URL signing
SigningStrategy oldStrategy = this.signingStrategy;
this.signingStrategy = new QueryStringSigningStrategy();
sign(request);
// revert to old strategy
this.signingStrategy = oldStrategy;
return request.getRequestUrl();
}
/**
* Adapts the given request object to a Signpost {@link HttpRequest}. How
* this is done depends on the consumer implementation.
*
* @param request
* the native HTTP request instance
* @return the adapted request
*/
protected abstract HttpRequest wrap(Object request);
public void setTokenWithSecret(String token, String tokenSecret) {
this.token = token;
messageSigner.setTokenSecret(tokenSecret);
}
public String getToken() {
return token;
}
public String getTokenSecret() {
return messageSigner.getTokenSecret();
}
public String getConsumerKey() {
return this.consumerKey;
}
public String getConsumerSecret() {
return this.consumerSecret;
}
/**
* <p>
* Helper method that adds any OAuth parameters to the given request
* parameters which are missing from the current request but required for
* signing. A good example is the oauth_nonce parameter, which is typically
* not provided by the client in advance.
* </p>
* <p>
* It's probably not a very good idea to override this method. If you want
* to generate different nonces or timestamps, override
* {@link #generateNonce()} or {@link #generateTimestamp()} instead.
* </p>
*
* @param out
* the request parameter which should be completed
*/
protected void completeOAuthParameters(HttpParameters out) {
if (!out.containsKey(OAuth.OAUTH_CONSUMER_KEY)) {
out.put(OAuth.OAUTH_CONSUMER_KEY, consumerKey, true);
}
if (!out.containsKey(OAuth.OAUTH_SIGNATURE_METHOD)) {
out.put(OAuth.OAUTH_SIGNATURE_METHOD, messageSigner.getSignatureMethod(), true);
}
if (!out.containsKey(OAuth.OAUTH_TIMESTAMP)) {
out.put(OAuth.OAUTH_TIMESTAMP, generateTimestamp(), true);
}
if (!out.containsKey(OAuth.OAUTH_NONCE)) {
out.put(OAuth.OAUTH_NONCE, generateNonce(), true);
}
if (!out.containsKey(OAuth.OAUTH_VERSION)) {
out.put(OAuth.OAUTH_VERSION, OAuth.VERSION_1_0, true);
}
if (!out.containsKey(OAuth.OAUTH_TOKEN)) {
if (token != null && !token.equals("") || sendEmptyTokens) {
out.put(OAuth.OAUTH_TOKEN, token, true);
}
}
}
public HttpParameters getRequestParameters() {
return requestParameters;
}
public void setSendEmptyTokens(boolean enable) {
this.sendEmptyTokens = enable;
}
/**
* Collects OAuth Authorization header parameters as per OAuth Core 1.0 spec
* section 9.1.1
*/
protected void collectHeaderParameters(HttpRequest request, HttpParameters out) {
HttpParameters headerParams = OAuth.oauthHeaderToParamsMap(request.getHeader(OAuth.HTTP_AUTHORIZATION_HEADER));
out.putAll(headerParams, false);
}
/**
* Collects x-www-form-urlencoded body parameters as per OAuth Core 1.0 spec
* section 9.1.1
*/
protected void collectBodyParameters(HttpRequest request, HttpParameters out)
throws IOException {
// collect x-www-form-urlencoded body params
String contentType = request.getContentType();
if (contentType != null && contentType.startsWith(OAuth.FORM_ENCODED)) {
InputStream payload = request.getMessagePayload();
out.putAll(OAuth.decodeForm(payload), true);
}
}
/**
* Collects HTTP GET query string parameters as per OAuth Core 1.0 spec
* section 9.1.1
*/
protected void collectQueryParameters(HttpRequest request, HttpParameters out) {
String url = request.getRequestUrl();
int q = url.indexOf('?');
if (q >= 0) {
// Combine the URL query string with the other parameters:
out.putAll(OAuth.decodeForm(url.substring(q + 1)), true);
}
}
protected String generateTimestamp() {
return Long.toString(System.currentTimeMillis() / 1000L);
}
protected String generateNonce() {
return Long.toString(new Random().nextLong());
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/AbstractOAuthConsumer.java
|
Java
|
gpl3
| 9,250
|
/*
* Copyright (c) 2009 Matthias Kaeppler Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package oauth.signpost;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import oauth.signpost.http.HttpParameters;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpResponse;
/**
* ABC for all provider implementations. If you're writing a custom provider,
* you will probably inherit from this class, since it takes a lot of work from
* you.
*
* @author Matthias Kaeppler
*/
public abstract class AbstractOAuthProvider implements OAuthProvider {
private static final long serialVersionUID = 1L;
private String requestTokenEndpointUrl;
private String accessTokenEndpointUrl;
private String authorizationWebsiteUrl;
private HttpParameters responseParameters;
private Map<String, String> defaultHeaders;
private boolean isOAuth10a;
private transient OAuthProviderListener listener;
public AbstractOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl,
String authorizationWebsiteUrl) {
this.requestTokenEndpointUrl = requestTokenEndpointUrl;
this.accessTokenEndpointUrl = accessTokenEndpointUrl;
this.authorizationWebsiteUrl = authorizationWebsiteUrl;
this.responseParameters = new HttpParameters();
this.defaultHeaders = new HashMap<String, String>();
}
public String retrieveRequestToken(OAuthConsumer consumer, String callbackUrl)
throws OAuthMessageSignerException, OAuthNotAuthorizedException,
OAuthExpectationFailedException, OAuthCommunicationException {
// invalidate current credentials, if any
consumer.setTokenWithSecret(null, null);
// 1.0a expects the callback to be sent while getting the request token.
// 1.0 service providers would simply ignore this parameter.
retrieveToken(consumer, requestTokenEndpointUrl, OAuth.OAUTH_CALLBACK, callbackUrl);
String callbackConfirmed = responseParameters.getFirst(OAuth.OAUTH_CALLBACK_CONFIRMED);
responseParameters.remove(OAuth.OAUTH_CALLBACK_CONFIRMED);
isOAuth10a = Boolean.TRUE.toString().equals(callbackConfirmed);
// 1.0 service providers expect the callback as part of the auth URL,
// Do not send when 1.0a.
if (isOAuth10a) {
return OAuth.addQueryParameters(authorizationWebsiteUrl, OAuth.OAUTH_TOKEN,
consumer.getToken());
} else {
return OAuth.addQueryParameters(authorizationWebsiteUrl, OAuth.OAUTH_TOKEN,
consumer.getToken(), OAuth.OAUTH_CALLBACK, callbackUrl);
}
}
public void retrieveAccessToken(OAuthConsumer consumer, String oauthVerifier)
throws OAuthMessageSignerException, OAuthNotAuthorizedException,
OAuthExpectationFailedException, OAuthCommunicationException {
if (consumer.getToken() == null || consumer.getTokenSecret() == null) {
throw new OAuthExpectationFailedException(
"Authorized request token or token secret not set. "
+ "Did you retrieve an authorized request token before?");
}
if (isOAuth10a && oauthVerifier != null) {
retrieveToken(consumer, accessTokenEndpointUrl, OAuth.OAUTH_VERIFIER, oauthVerifier);
} else {
retrieveToken(consumer, accessTokenEndpointUrl);
}
}
/**
* <p>
* Implemented by subclasses. The responsibility of this method is to
* contact the service provider at the given endpoint URL and fetch a
* request or access token. What kind of token is retrieved solely depends
* on the URL being used.
* </p>
* <p>
* Correct implementations of this method must guarantee the following
* post-conditions:
* <ul>
* <li>the {@link OAuthConsumer} passed to this method must have a valid
* {@link OAuth#OAUTH_TOKEN} and {@link OAuth#OAUTH_TOKEN_SECRET} set by
* calling {@link OAuthConsumer#setTokenWithSecret(String, String)}</li>
* <li>{@link #getResponseParameters()} must return the set of query
* parameters served by the service provider in the token response, with all
* OAuth specific parameters being removed</li>
* </ul>
* </p>
*
* @param consumer
* the {@link OAuthConsumer} that should be used to sign the request
* @param endpointUrl
* the URL at which the service provider serves the OAuth token that
* is to be fetched
* @param additionalParameters
* you can pass parameters here (typically OAuth parameters such as
* oauth_callback or oauth_verifier) which will go directly into the
* signer, i.e. you don't have to put them into the request first,
* just so the consumer pull them out again. Pass them sequentially
* in key/value order.
* @throws OAuthMessageSignerException
* if signing the token request fails
* @throws OAuthCommunicationException
* if a network communication error occurs
* @throws OAuthNotAuthorizedException
* if the server replies 401 - Unauthorized
* @throws OAuthExpectationFailedException
* if an expectation has failed, e.g. because the server didn't
* reply in the expected format
*/
protected void retrieveToken(OAuthConsumer consumer, String endpointUrl,
String... additionalParameters) throws OAuthMessageSignerException,
OAuthCommunicationException, OAuthNotAuthorizedException,
OAuthExpectationFailedException {
Map<String, String> defaultHeaders = getRequestHeaders();
if (consumer.getConsumerKey() == null || consumer.getConsumerSecret() == null) {
throw new OAuthExpectationFailedException("Consumer key or secret not set");
}
HttpRequest request = null;
HttpResponse response = null;
try {
request = createRequest(endpointUrl);
for (String header : defaultHeaders.keySet()) {
request.setHeader(header, defaultHeaders.get(header));
}
if (additionalParameters != null) {
HttpParameters httpParams = new HttpParameters();
httpParams.putAll(additionalParameters, true);
consumer.setAdditionalParameters(httpParams);
}
if (this.listener != null) {
this.listener.prepareRequest(request);
}
consumer.sign(request);
if (this.listener != null) {
this.listener.prepareSubmission(request);
}
response = sendRequest(request);
int statusCode = response.getStatusCode();
boolean requestHandled = false;
if (this.listener != null) {
requestHandled = this.listener.onResponseReceived(request, response);
}
if (requestHandled) {
return;
}
if (statusCode >= 300) {
handleUnexpectedResponse(statusCode, response);
}
HttpParameters responseParams = OAuth.decodeForm(response.getContent());
String token = responseParams.getFirst(OAuth.OAUTH_TOKEN);
String secret = responseParams.getFirst(OAuth.OAUTH_TOKEN_SECRET);
responseParams.remove(OAuth.OAUTH_TOKEN);
responseParams.remove(OAuth.OAUTH_TOKEN_SECRET);
setResponseParameters(responseParams);
if (token == null || secret == null) {
throw new OAuthExpectationFailedException(
"Request token or token secret not set in server reply. "
+ "The service provider you use is probably buggy.");
}
consumer.setTokenWithSecret(token, secret);
} catch (OAuthNotAuthorizedException e) {
throw e;
} catch (OAuthExpectationFailedException e) {
throw e;
} catch (Exception e) {
throw new OAuthCommunicationException(e);
} finally {
try {
closeConnection(request, response);
} catch (Exception e) {
throw new OAuthCommunicationException(e);
}
}
}
protected void handleUnexpectedResponse(int statusCode, HttpResponse response) throws Exception {
if (response == null) {
return;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getContent()));
StringBuilder responseBody = new StringBuilder();
String line = reader.readLine();
while (line != null) {
responseBody.append(line);
line = reader.readLine();
}
switch (statusCode) {
case 401:
throw new OAuthNotAuthorizedException(responseBody.toString());
default:
throw new OAuthCommunicationException("Service provider responded in error: "
+ statusCode + " (" + response.getReasonPhrase() + ")", responseBody.toString());
}
}
/**
* Overrride this method if you want to customize the logic for building a
* request object for the given endpoint URL.
*
* @param endpointUrl
* the URL to which the request will go
* @return the request object
* @throws Exception
* if something breaks
*/
protected abstract HttpRequest createRequest(String endpointUrl) throws Exception;
/**
* Override this method if you want to customize the logic for how the given
* request is sent to the server.
*
* @param request
* the request to send
* @return the response to the request
* @throws Exception
* if something breaks
*/
protected abstract HttpResponse sendRequest(HttpRequest request) throws Exception;
/**
* Called when the connection is being finalized after receiving the
* response. Use this to do any cleanup / resource freeing.
*
* @param request
* the request that has been sent
* @param response
* the response that has been received
* @throws Exception
* if something breaks
*/
protected void closeConnection(HttpRequest request, HttpResponse response) throws Exception {
// NOP
}
public HttpParameters getResponseParameters() {
return responseParameters;
}
/**
* Returns a single query parameter as served by the service provider in a
* token reply. You must call {@link #setResponseParameters} with the set of
* parameters before using this method.
*
* @param key
* the parameter name
* @return the parameter value
*/
protected String getResponseParameter(String key) {
return responseParameters.getFirst(key);
}
public void setResponseParameters(HttpParameters parameters) {
this.responseParameters = parameters;
}
public void setOAuth10a(boolean isOAuth10aProvider) {
this.isOAuth10a = isOAuth10aProvider;
}
public boolean isOAuth10a() {
return isOAuth10a;
}
public String getRequestTokenEndpointUrl() {
return this.requestTokenEndpointUrl;
}
public String getAccessTokenEndpointUrl() {
return this.accessTokenEndpointUrl;
}
public String getAuthorizationWebsiteUrl() {
return this.authorizationWebsiteUrl;
}
public void setRequestHeader(String header, String value) {
defaultHeaders.put(header, value);
}
public Map<String, String> getRequestHeaders() {
return defaultHeaders;
}
public void setListener(OAuthProviderListener listener) {
this.listener = listener;
}
public void removeListener(OAuthProviderListener listener) {
this.listener = null;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/AbstractOAuthProvider.java
|
Java
|
gpl3
| 12,885
|
package oauth.signpost.signature;
import java.io.Serializable;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpParameters;
/**
* <p>
* Defines how an OAuth signature string is written to a request.
* </p>
* <p>
* Unlike {@link OAuthMessageSigner}, which is concerned with <i>how</i> to
* generate a signature, this class is concered with <i>where</i> to write it
* (e.g. HTTP header or query string).
* </p>
*
* @author Matthias Kaeppler
*/
public interface SigningStrategy extends Serializable {
/**
* Writes an OAuth signature and all remaining required parameters to an
* HTTP message.
*
* @param signature
* the signature to write
* @param request
* the request to sign
* @param requestParameters
* the request parameters
* @return whatever has been written to the request, e.g. an Authorization
* header field
*/
String writeSignature(String signature, HttpRequest request, HttpParameters requestParameters);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/signature/SigningStrategy.java
|
Java
|
gpl3
| 1,058
|
/* Copyright (c) 2009 Matthias Kaeppler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oauth.signpost.signature;
import java.io.IOException;
import java.io.Serializable;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpParameters;
import org.apache.commons.codec.binary.Base64;
public abstract class OAuthMessageSigner implements Serializable {
private static final long serialVersionUID = 4445779788786131202L;
private transient Base64 base64;
private String consumerSecret;
private String tokenSecret;
public OAuthMessageSigner() {
this.base64 = new Base64();
}
public abstract String sign(HttpRequest request, HttpParameters requestParameters)
throws OAuthMessageSignerException;
public abstract String getSignatureMethod();
public String getConsumerSecret() {
return consumerSecret;
}
public String getTokenSecret() {
return tokenSecret;
}
public void setConsumerSecret(String consumerSecret) {
this.consumerSecret = consumerSecret;
}
public void setTokenSecret(String tokenSecret) {
this.tokenSecret = tokenSecret;
}
protected byte[] decodeBase64(String s) {
return base64.decode(s.getBytes());
}
protected String base64Encode(byte[] b) {
return new String(base64.encode(b));
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.base64 = new Base64();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/signature/OAuthMessageSigner.java
|
Java
|
gpl3
| 2,154
|
package oauth.signpost.signature;
import oauth.signpost.OAuth;
import oauth.signpost.http.HttpParameters;
import oauth.signpost.http.HttpRequest;
/**
* Writes to a URL query string. <strong>Note that this currently ONLY works
* when signing a URL directly, not with HTTP request objects.</strong> That's
* because most HTTP request implementations do not allow the client to change
* the URL once the request has been instantiated, so there is no way to append
* parameters to it.
*
* @author Matthias Kaeppler
*/
public class QueryStringSigningStrategy implements SigningStrategy {
private static final long serialVersionUID = 1L;
public String writeSignature(String signature, HttpRequest request,
HttpParameters requestParameters) {
// add the signature
StringBuilder sb = new StringBuilder(OAuth.addQueryParameters(request.getRequestUrl(),
OAuth.OAUTH_SIGNATURE, signature));
// add the optional OAuth parameters
if (requestParameters.containsKey(OAuth.OAUTH_TOKEN)) {
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_TOKEN));
}
if (requestParameters.containsKey(OAuth.OAUTH_CALLBACK)) {
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_CALLBACK));
}
if (requestParameters.containsKey(OAuth.OAUTH_VERIFIER)) {
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_VERIFIER));
}
// add the remaining OAuth params
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_CONSUMER_KEY));
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_VERSION));
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_SIGNATURE_METHOD));
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_TIMESTAMP));
sb.append("&");
sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_NONCE));
String signedUrl = sb.toString();
request.setRequestUrl(signedUrl);
return signedUrl;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/signature/QueryStringSigningStrategy.java
|
Java
|
gpl3
| 2,219
|
/*
* Copyright (c) 2009 Matthias Kaeppler Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package oauth.signpost.signature;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;
import oauth.signpost.OAuth;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpParameters;
public class SignatureBaseString {
private HttpRequest request;
private HttpParameters requestParameters;
/**
* Constructs a new SBS instance that will operate on the given request
* object and parameter set.
*
* @param request
* the HTTP request
* @param requestParameters
* the set of request parameters from the Authorization header, query
* string and form body
*/
public SignatureBaseString(HttpRequest request, HttpParameters requestParameters) {
this.request = request;
this.requestParameters = requestParameters;
}
/**
* Builds the signature base string from the data this instance was
* configured with.
*
* @return the signature base string
* @throws OAuthMessageSignerException
*/
public String generate() throws OAuthMessageSignerException {
try {
String normalizedUrl = normalizeRequestUrl();
String normalizedParams = normalizeRequestParameters();
return request.getMethod() + '&' + OAuth.percentEncode(normalizedUrl) + '&'
+ OAuth.percentEncode(normalizedParams);
} catch (Exception e) {
throw new OAuthMessageSignerException(e);
}
}
public String normalizeRequestUrl() throws URISyntaxException {
URI uri = new URI(request.getRequestUrl());
String scheme = uri.getScheme().toLowerCase();
String authority = uri.getAuthority().toLowerCase();
boolean dropPort = (scheme.equals("http") && uri.getPort() == 80)
|| (scheme.equals("https") && uri.getPort() == 443);
if (dropPort) {
// find the last : in the authority
int index = authority.lastIndexOf(":");
if (index >= 0) {
authority = authority.substring(0, index);
}
}
String path = uri.getRawPath();
if (path == null || path.length() <= 0) {
path = "/"; // conforms to RFC 2616 section 3.2.2
}
// we know that there is no query and no fragment here.
return scheme + "://" + authority + path;
}
/**
* Normalizes the set of request parameters this instance was configured
* with, as per OAuth spec section 9.1.1.
*
* @param parameters
* the set of request parameters
* @return the normalized params string
* @throws IOException
*/
public String normalizeRequestParameters() throws IOException {
if (requestParameters == null) {
return "";
}
StringBuilder sb = new StringBuilder();
Iterator<String> iter = requestParameters.keySet().iterator();
for (int i = 0; iter.hasNext(); i++) {
String param = iter.next();
if (OAuth.OAUTH_SIGNATURE.equals(param) || "realm".equals(param)) {
continue;
}
if (i > 0) {
sb.append("&");
}
sb.append(requestParameters.getAsQueryString(param));
}
return sb.toString();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/signature/SignatureBaseString.java
|
Java
|
gpl3
| 4,046
|
/* Copyright (c) 2009 Matthias Kaeppler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oauth.signpost.signature;
import oauth.signpost.OAuth;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpParameters;
@SuppressWarnings("serial")
public class PlainTextMessageSigner extends OAuthMessageSigner {
@Override
public String getSignatureMethod() {
return "PLAINTEXT";
}
@Override
public String sign(HttpRequest request, HttpParameters requestParams)
throws OAuthMessageSignerException {
return OAuth.percentEncode(getConsumerSecret()) + '&'
+ OAuth.percentEncode(getTokenSecret());
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/signature/PlainTextMessageSigner.java
|
Java
|
gpl3
| 1,259
|
package oauth.signpost.signature;
import oauth.signpost.OAuth;
import oauth.signpost.http.HttpParameters;
import oauth.signpost.http.HttpRequest;
/**
* Writes to the HTTP Authorization header field.
*
* @author Matthias Kaeppler
*/
public class AuthorizationHeaderSigningStrategy implements SigningStrategy {
private static final long serialVersionUID = 1L;
public String writeSignature(String signature, HttpRequest request,
HttpParameters requestParameters) {
StringBuilder sb = new StringBuilder();
sb.append("OAuth ");
if (requestParameters.containsKey("realm")) {
sb.append(requestParameters.getAsHeaderElement("realm"));
sb.append(", ");
}
if (requestParameters.containsKey(OAuth.OAUTH_TOKEN)) {
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_TOKEN));
sb.append(", ");
}
if (requestParameters.containsKey(OAuth.OAUTH_CALLBACK)) {
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_CALLBACK));
sb.append(", ");
}
if (requestParameters.containsKey(OAuth.OAUTH_VERIFIER)) {
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_VERIFIER));
sb.append(", ");
}
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_CONSUMER_KEY));
sb.append(", ");
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_VERSION));
sb.append(", ");
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_SIGNATURE_METHOD));
sb.append(", ");
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_TIMESTAMP));
sb.append(", ");
sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_NONCE));
sb.append(", ");
sb.append(OAuth.toHeaderElement(OAuth.OAUTH_SIGNATURE, signature));
String header = sb.toString();
request.setHeader(OAuth.HTTP_AUTHORIZATION_HEADER, header);
return header;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/signature/AuthorizationHeaderSigningStrategy.java
|
Java
|
gpl3
| 2,039
|
/* Copyright (c) 2009 Matthias Kaeppler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oauth.signpost.signature;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import oauth.signpost.OAuth;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpParameters;
@SuppressWarnings("serial")
public class HmacSha1MessageSigner extends OAuthMessageSigner {
private static final String MAC_NAME = "HmacSHA1";
@Override
public String getSignatureMethod() {
return "HMAC-SHA1";
}
@Override
public String sign(HttpRequest request, HttpParameters requestParams)
throws OAuthMessageSignerException {
try {
String keyString = OAuth.percentEncode(getConsumerSecret()) + '&'
+ OAuth.percentEncode(getTokenSecret());
byte[] keyBytes = keyString.getBytes(OAuth.ENCODING);
SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME);
Mac mac = Mac.getInstance(MAC_NAME);
mac.init(key);
String sbs = new SignatureBaseString(request, requestParams).generate();
OAuth.debugOut("SBS", sbs);
byte[] text = sbs.getBytes(OAuth.ENCODING);
return base64Encode(mac.doFinal(text)).trim();
} catch (GeneralSecurityException e) {
throw new OAuthMessageSignerException(e);
} catch (UnsupportedEncodingException e) {
throw new OAuthMessageSignerException(e);
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/signature/HmacSha1MessageSigner.java
|
Java
|
gpl3
| 2,200
|
package oauth.signpost.basic;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import oauth.signpost.http.HttpRequest;
public class HttpURLConnectionRequestAdapter implements HttpRequest {
protected HttpURLConnection connection;
public HttpURLConnectionRequestAdapter(HttpURLConnection connection) {
this.connection = connection;
}
public String getMethod() {
return connection.getRequestMethod();
}
public String getRequestUrl() {
return connection.getURL().toExternalForm();
}
public void setRequestUrl(String url) {
// can't do
}
public void setHeader(String name, String value) {
connection.setRequestProperty(name, value);
}
public String getHeader(String name) {
return connection.getRequestProperty(name);
}
public Map<String, String> getAllHeaders() {
Map<String, List<String>> origHeaders = connection.getRequestProperties();
Map<String, String> headers = new HashMap<String, String>(origHeaders.size());
for (String name : origHeaders.keySet()) {
List<String> values = origHeaders.get(name);
if (!values.isEmpty()) {
headers.put(name, values.get(0));
}
}
return headers;
}
public InputStream getMessagePayload() throws IOException {
return null;
}
public String getContentType() {
return connection.getRequestProperty("Content-Type");
}
public HttpURLConnection unwrap() {
return connection;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/basic/HttpURLConnectionRequestAdapter.java
|
Java
|
gpl3
| 1,681
|
package oauth.signpost.basic;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import oauth.signpost.http.HttpResponse;
public class HttpURLConnectionResponseAdapter implements HttpResponse {
private HttpURLConnection connection;
public HttpURLConnectionResponseAdapter(HttpURLConnection connection) {
this.connection = connection;
}
public InputStream getContent() throws IOException {
return connection.getInputStream();
}
public int getStatusCode() throws IOException {
return connection.getResponseCode();
}
public String getReasonPhrase() throws Exception {
return connection.getResponseMessage();
}
public Object unwrap() {
return connection;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/basic/HttpURLConnectionResponseAdapter.java
|
Java
|
gpl3
| 788
|
/*
* Copyright (c) 2009 Matthias Kaeppler Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package oauth.signpost.basic;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import oauth.signpost.AbstractOAuthProvider;
import oauth.signpost.http.HttpRequest;
import oauth.signpost.http.HttpResponse;
/**
* This default implementation uses {@link java.net.HttpURLConnection} type GET
* requests to receive tokens from a service provider.
*
* @author Matthias Kaeppler
*/
public class DefaultOAuthProvider extends AbstractOAuthProvider {
private static final long serialVersionUID = 1L;
public DefaultOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl,
String authorizationWebsiteUrl) {
super(requestTokenEndpointUrl, accessTokenEndpointUrl, authorizationWebsiteUrl);
}
protected HttpRequest createRequest(String endpointUrl) throws MalformedURLException,
IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(endpointUrl).openConnection();
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Content-Length", "0");
return new HttpURLConnectionRequestAdapter(connection);
}
protected HttpResponse sendRequest(HttpRequest request) throws IOException {
HttpURLConnection connection = (HttpURLConnection) request.unwrap();
connection.connect();
return new HttpURLConnectionResponseAdapter(connection);
}
@Override
protected void closeConnection(HttpRequest request, HttpResponse response) {
HttpURLConnection connection = (HttpURLConnection) request.unwrap();
if (connection != null) {
connection.disconnect();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/basic/DefaultOAuthProvider.java
|
Java
|
gpl3
| 2,366
|
/* Copyright (c) 2009 Matthias Kaeppler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oauth.signpost.basic;
import java.net.HttpURLConnection;
import oauth.signpost.AbstractOAuthConsumer;
import oauth.signpost.http.HttpRequest;
/**
* The default implementation for an OAuth consumer. Only supports signing
* {@link java.net.HttpURLConnection} type requests.
*
* @author Matthias Kaeppler
*/
public class DefaultOAuthConsumer extends AbstractOAuthConsumer {
private static final long serialVersionUID = 1L;
public DefaultOAuthConsumer(String consumerKey, String consumerSecret) {
super(consumerKey, consumerSecret);
}
@Override
protected HttpRequest wrap(Object request) {
if (!(request instanceof HttpURLConnection)) {
throw new IllegalArgumentException(
"The default consumer expects requests of type java.net.HttpURLConnection");
}
return new HttpURLConnectionRequestAdapter((HttpURLConnection) request);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/basic/DefaultOAuthConsumer.java
|
Java
|
gpl3
| 1,536
|
package oauth.signpost.basic;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Map;
import oauth.signpost.http.HttpRequest;
public class UrlStringRequestAdapter implements HttpRequest {
private String url;
public UrlStringRequestAdapter(String url) {
this.url = url;
}
public String getMethod() {
return "GET";
}
public String getRequestUrl() {
return url;
}
public void setRequestUrl(String url) {
this.url = url;
}
public void setHeader(String name, String value) {
}
public String getHeader(String name) {
return null;
}
public Map<String, String> getAllHeaders() {
return Collections.emptyMap();
}
public InputStream getMessagePayload() throws IOException {
return null;
}
public String getContentType() {
return null;
}
public Object unwrap() {
return url;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/basic/UrlStringRequestAdapter.java
|
Java
|
gpl3
| 990
|
/* Copyright (c) 2009 Matthias Kaeppler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oauth.signpost.exception;
@SuppressWarnings("serial")
public class OAuthNotAuthorizedException extends OAuthException {
private static final String ERROR = "Authorization failed (server replied with a 401). "
+ "This can happen if the consumer key was not correct or "
+ "the signatures did not match.";
private String responseBody;
public OAuthNotAuthorizedException() {
super(ERROR);
}
public OAuthNotAuthorizedException(String responseBody) {
super(ERROR);
this.responseBody = responseBody;
}
public String getResponseBody() {
return responseBody;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/exception/OAuthNotAuthorizedException.java
|
Java
|
gpl3
| 1,267
|
/* Copyright (c) 2009 Matthias Kaeppler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oauth.signpost.exception;
@SuppressWarnings("serial")
public class OAuthCommunicationException extends OAuthException {
private String responseBody;
public OAuthCommunicationException(Exception cause) {
super("Communication with the service provider failed: "
+ cause.getLocalizedMessage(), cause);
}
public OAuthCommunicationException(String message, String responseBody) {
super(message);
this.responseBody = responseBody;
}
public String getResponseBody() {
return responseBody;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/exception/OAuthCommunicationException.java
|
Java
|
gpl3
| 1,189
|
/* Copyright (c) 2009 Matthias Kaeppler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oauth.signpost.exception;
@SuppressWarnings("serial")
public class OAuthMessageSignerException extends OAuthException {
public OAuthMessageSignerException(String message) {
super(message);
}
public OAuthMessageSignerException(Exception cause) {
super(cause);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/exception/OAuthMessageSignerException.java
|
Java
|
gpl3
| 909
|
/* Copyright (c) 2009 Matthias Kaeppler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oauth.signpost.exception;
@SuppressWarnings("serial")
public class OAuthExpectationFailedException extends OAuthException {
public OAuthExpectationFailedException(String message) {
super(message);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/exception/OAuthExpectationFailedException.java
|
Java
|
gpl3
| 829
|
package oauth.signpost.exception;
@SuppressWarnings("serial")
public abstract class OAuthException extends Exception {
public OAuthException(String message) {
super(message);
}
public OAuthException(Throwable cause) {
super(cause);
}
public OAuthException(String message, Throwable cause) {
super(message, cause);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/exception/OAuthException.java
|
Java
|
gpl3
| 370
|
/* Copyright (c) 2008, 2009 Netflix, Matthias Kaeppler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oauth.signpost;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import oauth.signpost.http.HttpParameters;
import com.google.gdata.util.common.base.PercentEscaper;
public class OAuth {
public static final String VERSION_1_0 = "1.0";
public static final String ENCODING = "UTF-8";
public static final String FORM_ENCODED = "application/x-www-form-urlencoded";
public static final String HTTP_AUTHORIZATION_HEADER = "Authorization";
public static final String OAUTH_CONSUMER_KEY = "oauth_consumer_key";
public static final String OAUTH_TOKEN = "oauth_token";
public static final String OAUTH_TOKEN_SECRET = "oauth_token_secret";
public static final String OAUTH_SIGNATURE_METHOD = "oauth_signature_method";
public static final String OAUTH_SIGNATURE = "oauth_signature";
public static final String OAUTH_TIMESTAMP = "oauth_timestamp";
public static final String OAUTH_NONCE = "oauth_nonce";
public static final String OAUTH_VERSION = "oauth_version";
public static final String OAUTH_CALLBACK = "oauth_callback";
public static final String OAUTH_CALLBACK_CONFIRMED = "oauth_callback_confirmed";
public static final String OAUTH_VERIFIER = "oauth_verifier";
/**
* Pass this value as the callback "url" upon retrieving a request token if
* your application cannot receive callbacks (e.g. because it's a desktop
* app). This will tell the service provider that verification happens
* out-of-band, which basically means that it will generate a PIN code (the
* OAuth verifier) and display that to your user. You must obtain this code
* from your user and pass it to
* {@link OAuthProvider#retrieveAccessToken(OAuthConsumer, String)} in order
* to complete the token handshake.
*/
public static final String OUT_OF_BAND = "oob";
private static final PercentEscaper percentEncoder = new PercentEscaper(
"-._~", false);
public static String percentEncode(String s) {
if (s == null) {
return "";
}
return percentEncoder.escape(s);
}
public static String percentDecode(String s) {
try {
if (s == null) {
return "";
}
return URLDecoder.decode(s, ENCODING);
// This implements http://oauth.pbwiki.com/FlexibleDecoding
} catch (java.io.UnsupportedEncodingException wow) {
throw new RuntimeException(wow.getMessage(), wow);
}
}
/**
* Construct a x-www-form-urlencoded document containing the given sequence
* of name/value pairs. Use OAuth percent encoding (not exactly the encoding
* mandated by x-www-form-urlencoded).
*/
public static <T extends Map.Entry<String, String>> void formEncode(Collection<T> parameters,
OutputStream into) throws IOException {
if (parameters != null) {
boolean first = true;
for (Map.Entry<String, String> entry : parameters) {
if (first) {
first = false;
} else {
into.write('&');
}
into.write(percentEncode(safeToString(entry.getKey())).getBytes());
into.write('=');
into.write(percentEncode(safeToString(entry.getValue())).getBytes());
}
}
}
/**
* Construct a x-www-form-urlencoded document containing the given sequence
* of name/value pairs. Use OAuth percent encoding (not exactly the encoding
* mandated by x-www-form-urlencoded).
*/
public static <T extends Map.Entry<String, String>> String formEncode(Collection<T> parameters)
throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
formEncode(parameters, b);
return new String(b.toByteArray());
}
/** Parse a form-urlencoded document. */
public static HttpParameters decodeForm(String form) {
HttpParameters params = new HttpParameters();
if (isEmpty(form)) {
return params;
}
for (String nvp : form.split("\\&")) {
int equals = nvp.indexOf('=');
String name;
String value;
if (equals < 0) {
name = percentDecode(nvp);
value = null;
} else {
name = percentDecode(nvp.substring(0, equals));
value = percentDecode(nvp.substring(equals + 1));
}
params.put(name, value);
}
return params;
}
public static HttpParameters decodeForm(InputStream content)
throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
content));
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
sb.append(line);
line = reader.readLine();
}
return decodeForm(sb.toString());
}
/**
* Construct a Map containing a copy of the given parameters. If several
* parameters have the same name, the Map will contain the first value,
* only.
*/
public static <T extends Map.Entry<String, String>> Map<String, String> toMap(Collection<T> from) {
HashMap<String, String> map = new HashMap<String, String>();
if (from != null) {
for (Map.Entry<String, String> entry : from) {
String key = entry.getKey();
if (!map.containsKey(key)) {
map.put(key, entry.getValue());
}
}
}
return map;
}
public static final String safeToString(Object from) {
return (from == null) ? null : from.toString();
}
public static boolean isEmpty(String str) {
return (str == null) || (str.length() == 0);
}
/**
* Appends a list of key/value pairs to the given URL, e.g.:
*
* <pre>
* String url = OAuth.addQueryParameters("http://example.com?a=1", b, 2, c, 3);
* </pre>
*
* which yields:
*
* <pre>
* http://example.com?a=1&b=2&c=3
* </pre>
*
* All parameters will be encoded according to OAuth's percent encoding
* rules.
*
* @param url
* the URL
* @param kvPairs
* the list of key/value pairs
* @return
*/
public static String addQueryParameters(String url, String... kvPairs) {
String queryDelim = url.contains("?") ? "&" : "?";
StringBuilder sb = new StringBuilder(url + queryDelim);
for (int i = 0; i < kvPairs.length; i += 2) {
if (i > 0) {
sb.append("&");
}
sb.append(OAuth.percentEncode(kvPairs[i]) + "="
+ OAuth.percentEncode(kvPairs[i + 1]));
}
return sb.toString();
}
public static String addQueryParameters(String url, Map<String, String> params) {
String[] kvPairs = new String[params.size() * 2];
int idx = 0;
for (String key : params.keySet()) {
kvPairs[idx] = key;
kvPairs[idx + 1] = params.get(key);
idx += 2;
}
return addQueryParameters(url, kvPairs);
}
/**
* Builds an OAuth header from the given list of header fields. All
* parameters starting in 'oauth_*' will be percent encoded.
*
* <pre>
* String authHeader = OAuth.prepareOAuthHeader("realm", "http://example.com", "oauth_token", "x%y");
* </pre>
*
* which yields:
*
* <pre>
* OAuth realm="http://example.com", oauth_token="x%25y"
* </pre>
*
* @param kvPairs
* the list of key/value pairs
* @return a string eligible to be used as an OAuth HTTP Authorization
* header.
*/
public static String prepareOAuthHeader(String... kvPairs) {
StringBuilder sb = new StringBuilder("OAuth ");
for (int i = 0; i < kvPairs.length; i += 2) {
if (i > 0) {
sb.append(", ");
}
String value = kvPairs[i].startsWith("oauth_") ? OAuth
.percentEncode(kvPairs[i + 1]) : kvPairs[i + 1];
sb.append(OAuth.percentEncode(kvPairs[i]) + "=\"" + value + "\"");
}
return sb.toString();
}
public static HttpParameters oauthHeaderToParamsMap(String oauthHeader) {
HttpParameters params = new HttpParameters();
if (oauthHeader == null || !oauthHeader.startsWith("OAuth ")) {
return params;
}
oauthHeader = oauthHeader.substring("OAuth ".length());
String[] elements = oauthHeader.split(",");
for (String keyValuePair : elements) {
String[] keyValue = keyValuePair.split("=");
params.put(keyValue[0].trim(), keyValue[1].replace("\"", "").trim());
}
return params;
}
/**
* Helper method to concatenate a parameter and its value to a pair that can
* be used in an HTTP header. This method percent encodes both parts before
* joining them.
*
* @param name
* the OAuth parameter name, e.g. oauth_token
* @param value
* the OAuth parameter value, e.g. 'hello oauth'
* @return a name/value pair, e.g. oauth_token="hello%20oauth"
*/
public static String toHeaderElement(String name, String value) {
return OAuth.percentEncode(name) + "=\"" + OAuth.percentEncode(value) + "\"";
}
public static void debugOut(String key, String value) {
if (System.getProperty("debug") != null) {
System.out.println("[SIGNPOST] " + key + ": " + value);
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-core/src/main/java/oauth/signpost/OAuth.java
|
Java
|
gpl3
| 10,723
|
/*
* Copyright (c) 2009 Matthias Kaeppler Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package oauth.signpost.commonshttp;
import java.io.IOException;
import oauth.signpost.AbstractOAuthProvider;
import oauth.signpost.http.HttpRequest;
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.client.methods.HttpUriRequest;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
/**
* This implementation uses the Apache Commons {@link HttpClient} 4.x HTTP
* implementation to fetch OAuth tokens from a service provider. Android users
* should use this provider implementation in favor of the default one, since
* the latter is known to cause problems with Android's Apache Harmony
* underpinnings.
*
* @author Matthias Kaeppler
*/
public class CommonsHttpOAuthProvider extends AbstractOAuthProvider {
private static final long serialVersionUID = 1L;
private transient HttpClient httpClient;
public CommonsHttpOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl,
String authorizationWebsiteUrl) {
super(requestTokenEndpointUrl, accessTokenEndpointUrl, authorizationWebsiteUrl);
this.httpClient = new DefaultHttpClient();
}
public CommonsHttpOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl,
String authorizationWebsiteUrl, HttpClient httpClient) {
super(requestTokenEndpointUrl, accessTokenEndpointUrl, authorizationWebsiteUrl);
this.httpClient = httpClient;
}
public void setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
}
@Override
protected HttpRequest createRequest(String endpointUrl) throws Exception {
HttpPost request = new HttpPost(endpointUrl);
return new HttpRequestAdapter(request);
}
@Override
protected oauth.signpost.http.HttpResponse sendRequest(HttpRequest request) throws Exception {
HttpResponse response = httpClient.execute((HttpUriRequest) request.unwrap());
return new HttpResponseAdapter(response);
}
@Override
protected void closeConnection(HttpRequest request, oauth.signpost.http.HttpResponse response)
throws Exception {
if (response != null) {
HttpEntity entity = ((HttpResponse) response.unwrap()).getEntity();
if (entity != null) {
try {
// free the connection
entity.consumeContent();
} catch (IOException e) {
// this means HTTP keep-alive is not possible
e.printStackTrace();
}
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-commonshttp4/src/main/java/oauth/signpost/commonshttp/CommonsHttpOAuthProvider.java
|
Java
|
gpl3
| 3,318
|
/* Copyright (c) 2009 Matthias Kaeppler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oauth.signpost.commonshttp;
import oauth.signpost.AbstractOAuthConsumer;
import oauth.signpost.http.HttpRequest;
/**
* Supports signing HTTP requests of type {@link org.apache.ogt.http.HttpRequest}.
*
* @author Matthias Kaeppler
*/
public class CommonsHttpOAuthConsumer extends AbstractOAuthConsumer {
private static final long serialVersionUID = 1L;
public CommonsHttpOAuthConsumer(String consumerKey, String consumerSecret) {
super(consumerKey, consumerSecret);
}
@Override
protected HttpRequest wrap(Object request) {
if (!(request instanceof org.apache.ogt.http.HttpRequest)) {
throw new IllegalArgumentException(
"This consumer expects requests of type "
+ org.apache.ogt.http.HttpRequest.class.getCanonicalName());
}
return new HttpRequestAdapter((org.apache.ogt.http.client.methods.HttpUriRequest) request);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-commonshttp4/src/main/java/oauth/signpost/commonshttp/CommonsHttpOAuthConsumer.java
|
Java
|
gpl3
| 1,557
|
package oauth.signpost.commonshttp;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.client.methods.HttpUriRequest;
public class HttpRequestAdapter implements oauth.signpost.http.HttpRequest {
private HttpUriRequest request;
private HttpEntity entity;
public HttpRequestAdapter(HttpUriRequest request) {
this.request = request;
if (request instanceof HttpEntityEnclosingRequest) {
entity = ((HttpEntityEnclosingRequest) request).getEntity();
}
}
public String getMethod() {
return request.getRequestLine().getMethod();
}
public String getRequestUrl() {
return request.getURI().toString();
}
public void setRequestUrl(String url) {
throw new RuntimeException(new UnsupportedOperationException());
}
public String getHeader(String name) {
Header header = request.getFirstHeader(name);
if (header == null) {
return null;
}
return header.getValue();
}
public void setHeader(String name, String value) {
request.setHeader(name, value);
}
public Map<String, String> getAllHeaders() {
Header[] origHeaders = request.getAllHeaders();
HashMap<String, String> headers = new HashMap<String, String>();
for (Header h : origHeaders) {
headers.put(h.getName(), h.getValue());
}
return headers;
}
public String getContentType() {
if (entity == null) {
return null;
}
Header header = entity.getContentType();
if (header == null) {
return null;
}
return header.getValue();
}
public InputStream getMessagePayload() throws IOException {
if (entity == null) {
return null;
}
return entity.getContent();
}
public Object unwrap() {
return request;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-commonshttp4/src/main/java/oauth/signpost/commonshttp/HttpRequestAdapter.java
|
Java
|
gpl3
| 2,124
|
package oauth.signpost.commonshttp;
import java.io.IOException;
import java.io.InputStream;
import oauth.signpost.http.HttpResponse;
public class HttpResponseAdapter implements HttpResponse {
private org.apache.ogt.http.HttpResponse response;
public HttpResponseAdapter(org.apache.ogt.http.HttpResponse response) {
this.response = response;
}
public InputStream getContent() throws IOException {
return response.getEntity().getContent();
}
public int getStatusCode() throws IOException {
return response.getStatusLine().getStatusCode();
}
public String getReasonPhrase() throws Exception {
return response.getStatusLine().getReasonPhrase();
}
public Object unwrap() {
return response;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/signpost/signpost-commonshttp4/src/main/java/oauth/signpost/commonshttp/HttpResponseAdapter.java
|
Java
|
gpl3
| 782
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark.httpcore;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
class RandomDataHandler implements HttpRequestHandler {
public RandomDataHandler() {
super();
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + " method not supported");
}
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
EntityUtils.consume(entity);
}
String target = request.getRequestLine().getUri();
int count = 100;
int idx = target.indexOf('?');
if (idx != -1) {
String s = target.substring(idx + 1);
if (s.startsWith("c=")) {
s = s.substring(2);
try {
count = Integer.parseInt(s);
} catch (NumberFormatException ex) {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
response.setEntity(new StringEntity("Invalid query format: " + s,
"text/plain", "ASCII"));
return;
}
}
}
response.setStatusCode(HttpStatus.SC_OK);
RandomEntity body = new RandomEntity(count);
response.setEntity(body);
}
static class RandomEntity extends AbstractHttpEntity {
private int count;
private final byte[] buf;
public RandomEntity(int count) {
super();
this.count = count;
this.buf = new byte[1024];
setContentType("text/plain");
}
public InputStream getContent() throws IOException, IllegalStateException {
throw new IllegalStateException("Method not supported");
}
public long getContentLength() {
return this.count;
}
public boolean isRepeatable() {
return true;
}
public boolean isStreaming() {
return false;
}
public void writeTo(final OutputStream outstream) throws IOException {
int r = Math.abs(this.buf.hashCode());
int remaining = this.count;
while (remaining > 0) {
int chunk = Math.min(this.buf.length, remaining);
for (int i = 0; i < chunk; i++) {
this.buf[i] = (byte) ((r + i) % 96 + 32);
}
outstream.write(this.buf, 0, chunk);
remaining -= chunk;
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/httpcore/RandomDataHandler.java
|
Java
|
gpl3
| 4,674
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark.httpcore;
import java.io.IOException;
import org.apache.http.HttpServerConnection;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpService;
class HttpWorker extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
private final HttpWorkerCallback workercallback;
private volatile boolean shutdown;
private volatile Exception exception;
public HttpWorker(
final HttpService httpservice,
final HttpServerConnection conn,
final HttpWorkerCallback workercallback) {
super();
this.httpservice = httpservice;
this.conn = conn;
this.workercallback = workercallback;
}
public boolean isShutdown() {
return this.shutdown;
}
public Exception getException() {
return this.exception;
}
@Override
public void run() {
this.workercallback.started(this);
try {
HttpContext context = new BasicHttpContext();
while (!Thread.interrupted() && !this.shutdown) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (Exception ex) {
this.exception = ex;
} finally {
terminate();
this.workercallback.shutdown(this);
}
}
public void terminate() {
if (this.shutdown) {
return;
}
this.shutdown = true;
try {
this.conn.shutdown();
} catch (IOException ex) {
if (this.exception != null) {
this.exception = ex;
}
}
}
public void awaitTermination(long millis) throws InterruptedException {
this.join(millis);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/httpcore/HttpWorker.java
|
Java
|
gpl3
| 3,048
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark.httpcore;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Locale;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.entity.BufferingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.entity.ProducingNHttpEntity;
import org.apache.http.nio.protocol.NHttpRequestHandler;
import org.apache.http.nio.protocol.NHttpResponseTrigger;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
class NRandomDataHandler implements NHttpRequestHandler {
public NRandomDataHandler() {
super();
}
public ConsumingNHttpEntity entityRequest(
final HttpEntityEnclosingRequest request,
final HttpContext context) throws HttpException, IOException {
// Use buffering entity for simplicity
return new BufferingNHttpEntity(request.getEntity(), new HeapByteBufferAllocator());
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final NHttpResponseTrigger trigger,
final HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + " method not supported");
}
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
EntityUtils.consume(entity);
}
String target = request.getRequestLine().getUri();
int count = 100;
int idx = target.indexOf('?');
if (idx != -1) {
String s = target.substring(idx + 1);
if (s.startsWith("c=")) {
s = s.substring(2);
try {
count = Integer.parseInt(s);
} catch (NumberFormatException ex) {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
response.setEntity(new StringEntity("Invalid query format: " + s,
"text/plain", "ASCII"));
return;
}
}
}
response.setStatusCode(HttpStatus.SC_OK);
RandomEntity body = new RandomEntity(count);
response.setEntity(body);
trigger.submitResponse(response);
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + " method not supported");
}
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
EntityUtils.consume(entity);
}
String target = request.getRequestLine().getUri();
int count = 100;
int idx = target.indexOf('?');
if (idx != -1) {
String s = target.substring(idx + 1);
if (s.startsWith("c=")) {
s = s.substring(2);
try {
count = Integer.parseInt(s);
} catch (NumberFormatException ex) {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
response.setEntity(new StringEntity("Invalid query format: " + s,
"text/plain", "ASCII"));
return;
}
}
}
response.setStatusCode(HttpStatus.SC_OK);
RandomEntity body = new RandomEntity(count);
response.setEntity(body);
}
static class RandomEntity extends AbstractHttpEntity implements ProducingNHttpEntity {
private final int count;
private final ByteBuffer buf;
private int remaining;
public RandomEntity(int count) {
super();
this.count = count;
this.remaining = count;
this.buf = ByteBuffer.allocate(1024);
setContentType("text/plain");
}
public InputStream getContent() throws IOException, IllegalStateException {
throw new IllegalStateException("Method not supported");
}
public long getContentLength() {
return this.count;
}
public boolean isRepeatable() {
return true;
}
public boolean isStreaming() {
return false;
}
public void writeTo(final OutputStream outstream) throws IOException {
throw new IllegalStateException("Method not supported");
}
public void produceContent(
final ContentEncoder encoder, final IOControl ioctrl) throws IOException {
int r = Math.abs(this.buf.hashCode());
int chunk = Math.min(this.buf.remaining(), this.remaining);
if (chunk > 0) {
for (int i = 0; i < chunk; i++) {
byte b = (byte) ((r + i) % 96 + 32);
this.buf.put(b);
}
}
this.buf.flip();
int bytesWritten = encoder.write(this.buf);
this.remaining -= bytesWritten;
if (this.remaining == 0 && this.buf.remaining() == 0) {
encoder.complete();
}
this.buf.compact();
}
public void finish() throws IOException {
this.remaining = this.count;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/httpcore/NRandomDataHandler.java
|
Java
|
gpl3
| 7,571
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark.httpcore;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.ListenerEndpoint;
import org.apache.http.nio.reactor.ListeningIOReactor;
public class NHttpListener extends Thread {
private final ListeningIOReactor ioreactor;
private final IOEventDispatch ioEventDispatch;
private volatile Exception exception;
public NHttpListener(
final ListeningIOReactor ioreactor,
final IOEventDispatch ioEventDispatch) throws IOException {
super();
this.ioreactor = ioreactor;
this.ioEventDispatch = ioEventDispatch;
}
@Override
public void run() {
try {
this.ioreactor.execute(this.ioEventDispatch);
} catch (Exception ex) {
this.exception = ex;
}
}
public void listen(final InetSocketAddress address) throws InterruptedException {
ListenerEndpoint endpoint = this.ioreactor.listen(address);
endpoint.waitFor();
}
public void terminate() {
try {
this.ioreactor.shutdown();
} catch (IOException ex) {
}
}
public Exception getException() {
return this.exception;
}
public void awaitTermination(long millis) throws InterruptedException {
this.join(millis);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/httpcore/NHttpListener.java
|
Java
|
gpl3
| 2,601
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark.httpcore;
interface HttpWorkerCallback {
void started(HttpWorker worker);
void shutdown(HttpWorker worker);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/httpcore/HttpWorkerCallback.java
|
Java
|
gpl3
| 1,339
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark.httpcore;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.benchmark.HttpServer;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.DefaultServerIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.nio.protocol.AsyncNHttpServiceHandler;
import org.apache.http.nio.protocol.NHttpRequestHandlerRegistry;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.http.util.VersionInfo;
public class HttpCoreNIOServer implements HttpServer {
private final int port;
private final NHttpListener listener;
public HttpCoreNIOServer(int port) throws IOException {
if (port <= 0) {
throw new IllegalArgumentException("Server port may not be negative or null");
}
this.port = port;
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 10000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 12 * 1024)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpCore-NIO-Test/1.1");
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
AsyncNHttpServiceHandler handler = new AsyncNHttpServiceHandler(
httpproc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
params);
NHttpRequestHandlerRegistry reqistry = new NHttpRequestHandlerRegistry();
reqistry.register("/rnd", new NRandomDataHandler());
handler.setHandlerResolver(reqistry);
ListeningIOReactor ioreactor = new DefaultListeningIOReactor(2, params);
IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params);
this.listener = new NHttpListener(ioreactor, ioEventDispatch);
}
public String getName() {
return "HttpCore (NIO)";
}
public String getVersion() {
VersionInfo vinfo = VersionInfo.loadVersionInfo("org.apache.http",
Thread.currentThread().getContextClassLoader());
return vinfo.getRelease();
}
public void start() throws Exception {
this.listener.start();
this.listener.listen(new InetSocketAddress(this.port));
}
public void shutdown() {
this.listener.terminate();
try {
this.listener.awaitTermination(1000);
} catch (InterruptedException ex) {
}
Exception ex = this.listener.getException();
if (ex != null) {
System.out.println("Error: " + ex.getMessage());
}
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("Usage: <port>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
final HttpCoreNIOServer server = new HttpCoreNIOServer(port);
System.out.println("Listening on port: " + port);
server.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
server.shutdown();
}
});
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/httpcore/HttpCoreNIOServer.java
|
Java
|
gpl3
| 5,387
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark.httpcore;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.protocol.HttpService;
class HttpListener extends Thread {
private final ServerSocket serversocket;
private final HttpService httpservice;
private final HttpWorkerCallback workercallback;
private volatile boolean shutdown;
private volatile Exception exception;
public HttpListener(
final ServerSocket serversocket,
final HttpService httpservice,
final HttpWorkerCallback workercallback) {
super();
this.serversocket = serversocket;
this.httpservice = httpservice;
this.workercallback = workercallback;
}
public boolean isShutdown() {
return this.shutdown;
}
public Exception getException() {
return this.exception;
}
@Override
public void run() {
while (!Thread.interrupted() && !this.shutdown) {
try {
// Set up HTTP connection
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(socket, this.httpservice.getParams());
// Start worker thread
HttpWorker t = new HttpWorker(this.httpservice, conn, this.workercallback);
t.start();
} catch (InterruptedIOException ex) {
terminate();
} catch (IOException ex) {
this.exception = ex;
terminate();
}
}
}
public void terminate() {
if (this.shutdown) {
return;
}
this.shutdown = true;
try {
this.serversocket.close();
} catch (IOException ex) {
if (this.exception != null) {
this.exception = ex;
}
}
}
public void awaitTermination(long millis) throws InterruptedException {
this.join(millis);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/httpcore/HttpListener.java
|
Java
|
gpl3
| 3,352
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark.httpcore;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.benchmark.HttpServer;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
import org.apache.http.protocol.HttpService;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.http.util.VersionInfo;
public class HttpCoreServer implements HttpServer {
private final Queue<HttpWorker> workers;
private final HttpListener listener;
public HttpCoreServer(int port) throws IOException {
super();
if (port <= 0) {
throw new IllegalArgumentException("Server port may not be negative or null");
}
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 10000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 12 * 1024)
.setIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 1024)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpCore-Test/1.1");
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("/rnd", new RandomDataHandler());
HttpService httpservice = new HttpService(
httpproc,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory(),
reqistry,
params);
this.workers = new ConcurrentLinkedQueue<HttpWorker>();
this.listener = new HttpListener(
new ServerSocket(port),
httpservice,
new StdHttpWorkerCallback(this.workers));
}
public String getName() {
return "HttpCore (blocking I/O)";
}
public String getVersion() {
VersionInfo vinfo = VersionInfo.loadVersionInfo("org.apache.http",
Thread.currentThread().getContextClassLoader());
return vinfo.getRelease();
}
public void start() {
this.listener.start();
}
public void shutdown() {
this.listener.terminate();
try {
this.listener.awaitTermination(1000);
} catch (InterruptedException ex) {
}
Exception ex = this.listener.getException();
if (ex != null) {
System.out.println("Error: " + ex.getMessage());
}
while (!this.workers.isEmpty()) {
HttpWorker worker = this.workers.remove();
worker.terminate();
try {
worker.awaitTermination(1000);
} catch (InterruptedException iex) {
}
ex = worker.getException();
if (ex != null) {
System.out.println("Error: " + ex.getMessage());
}
}
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("Usage: <port>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
final HttpCoreServer server = new HttpCoreServer(port);
System.out.println("Listening on port: " + port);
server.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
server.shutdown();
}
});
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/httpcore/HttpCoreServer.java
|
Java
|
gpl3
| 5,551
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark.httpcore;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.Queue;
import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpException;
class StdHttpWorkerCallback implements HttpWorkerCallback {
private final Queue<HttpWorker> queue;
public StdHttpWorkerCallback(final Queue<HttpWorker> queue) {
super();
this.queue = queue;
}
public void started(final HttpWorker worker) {
this.queue.add(worker);
}
public void shutdown(final HttpWorker worker) {
this.queue.remove(worker);
Exception ex = worker.getException();
if (ex != null) {
if (ex instanceof HttpException) {
System.err.println("HTTP protocol error: " + ex.getMessage());
} else if (ex instanceof SocketTimeoutException) {
// ignore
} else if (ex instanceof ConnectionClosedException) {
// ignore
} else if (ex instanceof IOException) {
System.err.println("I/O error: " + ex);
} else {
System.err.println("Unexpected error: " + ex.getMessage());
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/httpcore/StdHttpWorkerCallback.java
|
Java
|
gpl3
| 2,427
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark;
import java.net.URL;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.http.benchmark.httpcore.HttpCoreNIOServer;
import org.apache.http.benchmark.httpcore.HttpCoreServer;
import org.apache.http.benchmark.jetty.JettyNIOServer;
import org.apache.http.benchmark.jetty.JettyServer;
import org.apache.http.benchmark.CommandLineUtils;
import org.apache.http.benchmark.Config;
import org.apache.http.benchmark.HttpBenchmark;
public class Benchmark {
private static final int PORT = 8989;
public static void main(String[] args) throws Exception {
Config config = new Config();
if (args.length > 0) {
Options options = CommandLineUtils.getOptions();
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption('h')) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("Benchmark [options]", options);
System.exit(1);
}
CommandLineUtils.parseCommandLine(cmd, config);
} else {
config.setKeepAlive(true);
config.setRequests(20000);
config.setThreads(25);
}
URL target = new URL("http", "localhost", PORT, "/rnd?c=2048");
config.setUrl(target);
Benchmark benchmark = new Benchmark();
benchmark.run(new JettyServer(PORT), config);
benchmark.run(new HttpCoreServer(PORT), config);
benchmark.run(new JettyNIOServer(PORT), config);
benchmark.run(new HttpCoreNIOServer(PORT), config);
}
public Benchmark() {
super();
}
public void run(final HttpServer server, final Config config) throws Exception {
server.start();
try {
System.out.println("---------------------------------------------------------------");
System.out.println(server.getName() + "; version: " + server.getVersion());
System.out.println("---------------------------------------------------------------");
HttpBenchmark ab = new HttpBenchmark(config);
ab.execute();
System.out.println("---------------------------------------------------------------");
} finally {
server.shutdown();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/Benchmark.java
|
Java
|
gpl3
| 3,722
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark;
public interface HttpServer {
String getName();
String getVersion();
void start() throws Exception;
void shutdown();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/HttpServer.java
|
Java
|
gpl3
| 1,361
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark.jetty;
import java.io.IOException;
import org.apache.http.benchmark.HttpServer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
public class JettyNIOServer implements HttpServer {
private final Server server;
public JettyNIOServer(int port) throws IOException {
super();
if (port <= 0) {
throw new IllegalArgumentException("Server port may not be negative or null");
}
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(port);
connector.setRequestBufferSize(12 * 1024);
connector.setResponseBufferSize(12 * 1024);
connector.setAcceptors(2);
QueuedThreadPool threadpool = new QueuedThreadPool();
threadpool.setMinThreads(25);
threadpool.setMaxThreads(200);
this.server = new Server();
this.server.addConnector(connector);
this.server.setThreadPool(threadpool);
this.server.setHandler(new RandomDataHandler());
}
public String getName() {
return "Jetty (NIO)";
}
public String getVersion() {
return Server.getVersion();
}
public void start() throws Exception {
this.server.start();
}
public void shutdown() {
try {
this.server.stop();
} catch (Exception ex) {
}
try {
this.server.join();
} catch (InterruptedException ex) {
}
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("Usage: <port>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
final JettyNIOServer server = new JettyNIOServer(port);
System.out.println("Listening on port: " + port);
server.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
server.shutdown();
}
});
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/jetty/JettyNIOServer.java
|
Java
|
gpl3
| 3,329
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark.jetty;
import java.io.IOException;
import org.apache.http.benchmark.HttpServer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
public class JettyServer implements HttpServer {
private final Server server;
public JettyServer(int port) throws IOException {
super();
if (port <= 0) {
throw new IllegalArgumentException("Server port may not be negative or null");
}
SocketConnector connector = new SocketConnector();
connector.setPort(port);
connector.setRequestBufferSize(12 * 1024);
connector.setResponseBufferSize(12 * 1024);
connector.setAcceptors(2);
QueuedThreadPool threadpool = new QueuedThreadPool();
threadpool.setMinThreads(25);
threadpool.setMaxThreads(200);
this.server = new Server();
this.server.addConnector(connector);
this.server.setThreadPool(threadpool);
this.server.setHandler(new RandomDataHandler());
}
public String getName() {
return "Jetty (blocking I/O)";
}
public String getVersion() {
return Server.getVersion();
}
public void start() throws Exception {
this.server.start();
}
public void shutdown() {
try {
this.server.stop();
} catch (Exception ex) {
}
try {
this.server.join();
} catch (InterruptedException ex) {
}
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("Usage: <port>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
final JettyServer server = new JettyServer(port);
System.out.println("Listening on port: " + port);
server.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
server.shutdown();
}
});
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/jetty/JettyServer.java
|
Java
|
gpl3
| 3,305
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark.jetty;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
class RandomDataHandler extends AbstractHandler {
public RandomDataHandler() {
super();
}
public void handle(
final String target,
final Request baseRequest,
final HttpServletRequest request,
final HttpServletResponse response) throws IOException, ServletException {
if (target.equals("/rnd")) {
rnd(request, response);
} else {
response.setStatus(HttpStatus.NOT_FOUND_404);
Writer writer = response.getWriter();
writer.write("Target not found: " + target);
writer.flush();
}
}
private void rnd(
final HttpServletRequest request,
final HttpServletResponse response) throws IOException, ServletException {
int count = 100;
String s = request.getParameter("c");
try {
count = Integer.parseInt(s);
} catch (NumberFormatException ex) {
response.setStatus(500);
Writer writer = response.getWriter();
writer.write("Invalid query format: " + request.getQueryString());
writer.flush();
return;
}
response.setStatus(200);
response.setContentLength(count);
OutputStream outstream = response.getOutputStream();
byte[] tmp = new byte[1024];
int r = Math.abs(tmp.hashCode());
int remaining = count;
while (remaining > 0) {
int chunk = Math.min(tmp.length, remaining);
for (int i = 0; i < chunk; i++) {
tmp[i] = (byte) ((r + i) % 96 + 32);
}
outstream.write(tmp, 0, chunk);
remaining -= chunk;
}
outstream.flush();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-benchmark/src/main/java/org/apache/http/benchmark/jetty/RandomDataHandler.java
|
Java
|
gpl3
| 3,339
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark;
import org.apache.http.HttpHost;
import java.text.NumberFormat;
public class ResultProcessor {
static NumberFormat nf2 = NumberFormat.getInstance();
static NumberFormat nf3 = NumberFormat.getInstance();
static NumberFormat nf6 = NumberFormat.getInstance();
static {
nf2.setMaximumFractionDigits(2);
nf2.setMinimumFractionDigits(2);
nf3.setMaximumFractionDigits(3);
nf3.setMinimumFractionDigits(3);
nf6.setMaximumFractionDigits(6);
nf6.setMinimumFractionDigits(6);
}
static String printResults(BenchmarkWorker[] workers, HttpHost host,
String uri, long contentLength) {
double totalTimeNano = 0;
long successCount = 0;
long failureCount = 0;
long writeErrors = 0;
long keepAliveCount = 0;
long totalBytesRcvd = 0;
Stats stats = workers[0].getStats();
for (int i = 0; i < workers.length; i++) {
Stats s = workers[i].getStats();
totalTimeNano += s.getDuration();
successCount += s.getSuccessCount();
failureCount += s.getFailureCount();
writeErrors += s.getWriteErrors();
keepAliveCount += s.getKeepAliveCount();
totalBytesRcvd += s.getTotalBytesRecv();
}
int threads = workers.length;
double totalTimeMs = (totalTimeNano / threads) / 1000000; // convert nano secs to milli secs
double timePerReqMs = totalTimeMs / successCount;
double totalTimeSec = totalTimeMs / 1000;
double reqsPerSec = successCount / totalTimeSec;
long totalBytesSent = contentLength * successCount;
long totalBytes = totalBytesRcvd + (totalBytesSent > 0 ? totalBytesSent : 0);
StringBuilder sb = new StringBuilder(1024);
printAndAppend(sb,"\nServer Software:\t\t" + stats.getServerName());
printAndAppend(sb, "Server Hostname:\t\t" + host.getHostName());
printAndAppend(sb, "Server Port:\t\t\t" +
(host.getPort() > 0 ? host.getPort() : uri.startsWith("https") ? "443" : "80") + "\n");
printAndAppend(sb, "Document Path:\t\t\t" + uri);
printAndAppend(sb, "Document Length:\t\t" + stats.getContentLength() + " bytes\n");
printAndAppend(sb, "Concurrency Level:\t\t" + workers.length);
printAndAppend(sb, "Time taken for tests:\t\t" + nf6.format(totalTimeSec) + " seconds");
printAndAppend(sb, "Complete requests:\t\t" + successCount);
printAndAppend(sb, "Failed requests:\t\t" + failureCount);
printAndAppend(sb, "Write errors:\t\t\t" + writeErrors);
printAndAppend(sb, "Kept alive:\t\t\t" + keepAliveCount);
printAndAppend(sb, "Total transferred:\t\t" + totalBytes + " bytes");
printAndAppend(sb, "Requests per second:\t\t" + nf2.format(reqsPerSec) + " [#/sec] (mean)");
printAndAppend(sb, "Time per request:\t\t" + nf3.format(timePerReqMs * workers.length) + " [ms] (mean)");
printAndAppend(sb, "Time per request:\t\t" + nf3.format(timePerReqMs) +
" [ms] (mean, across all concurrent requests)");
printAndAppend(sb, "Transfer rate:\t\t\t" +
nf2.format(totalBytesRcvd/1000/totalTimeSec) + " [Kbytes/sec] received");
printAndAppend(sb, "\t\t\t\t" +
(totalBytesSent > 0 ? nf2.format(totalBytesSent/1000/totalTimeSec) : -1) + " kb/s sent");
printAndAppend(sb, "\t\t\t\t" +
nf2.format(totalBytes/1000/totalTimeSec) + " kb/s total");
return sb.toString();
}
private static void printAndAppend(StringBuilder sb, String s) {
System.out.println(s);
sb.append(s).append("\r\n");
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-ab/src/main/java/org/apache/http/benchmark/ResultProcessor.java
|
Java
|
gpl3
| 4,942
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark;
/**
* Helper to gather statistics for an {@link HttpBenchmark HttpBenchmark}.
*
*
* @since 4.0
*/
public class Stats {
private long startTime = -1; // nano seconds - does not represent an actual time
private long finishTime = -1; // nano seconds - does not represent an actual time
private int successCount = 0;
private int failureCount = 0;
private int writeErrors = 0;
private int keepAliveCount = 0;
private String serverName = null;
private long totalBytesRecv = 0;
private long contentLength = -1;
public Stats() {
super();
}
public void start() {
this.startTime = System.nanoTime();
}
public void finish() {
this.finishTime = System.nanoTime();
}
public long getFinishTime() {
return this.finishTime;
}
public long getStartTime() {
return this.startTime;
}
/**
* Total execution time measured in nano seconds
*
* @return duration in nanoseconds
*/
public long getDuration() {
// we are using System.nanoTime() and the return values could be negative
// but its only the difference that we are concerned about
return this.finishTime - this.startTime;
}
public void incSuccessCount() {
this.successCount++;
}
public int getSuccessCount() {
return this.successCount;
}
public void incFailureCount() {
this.failureCount++;
}
public int getFailureCount() {
return this.failureCount;
}
public void incWriteErrors() {
this.writeErrors++;
}
public int getWriteErrors() {
return this.writeErrors;
}
public void incKeepAliveCount() {
this.keepAliveCount++;
}
public int getKeepAliveCount() {
return this.keepAliveCount;
}
public long getTotalBytesRecv() {
return this.totalBytesRecv;
}
public void incTotalBytesRecv(int n) {
this.totalBytesRecv += n;
}
public long getContentLength() {
return this.contentLength;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public String getServerName() {
return this.serverName;
}
public void setServerName(final String serverName) {
this.serverName = serverName;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-ab/src/main/java/org/apache/http/benchmark/Stats.java
|
Java
|
gpl3
| 3,593
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
public class CommandLineUtils {
public static Options getOptions() {
Option iopt = new Option("i", false, "Do HEAD requests instead of GET (deprecated)");
iopt.setRequired(false);
Option oopt = new Option("o", false, "Use HTTP/S 1.0 instead of 1.1 (default)");
oopt.setRequired(false);
Option kopt = new Option("k", false, "Enable the HTTP KeepAlive feature, " +
"i.e., perform multiple requests within one HTTP session. " +
"Default is no KeepAlive");
kopt.setRequired(false);
Option uopt = new Option("u", false, "Chunk entity. Default is false");
uopt.setRequired(false);
Option xopt = new Option("x", false, "Use Expect-Continue. Default is false");
xopt.setRequired(false);
Option gopt = new Option("g", false, "Accept GZip. Default is false");
gopt.setRequired(false);
Option nopt = new Option("n", true, "Number of requests to perform for the " +
"benchmarking session. The default is to just perform a single " +
"request which usually leads to non-representative benchmarking " +
"results");
nopt.setRequired(false);
nopt.setArgName("requests");
Option copt = new Option("c", true, "Concurrency while performing the " +
"benchmarking session. The default is to just use a single thread/client");
copt.setRequired(false);
copt.setArgName("concurrency");
Option popt = new Option("p", true, "File containing data to POST or PUT");
popt.setRequired(false);
popt.setArgName("Payload file");
Option mopt = new Option("m", true, "HTTP Method. Default is POST. " +
"Possible options are GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE");
mopt.setRequired(false);
mopt.setArgName("HTTP method");
Option Topt = new Option("T", true, "Content-type header to use for POST/PUT data");
Topt.setRequired(false);
Topt.setArgName("content-type");
Option topt = new Option("t", true, "Client side socket timeout (in ms) - default 60 Secs");
topt.setRequired(false);
topt.setArgName("socket-Timeout");
Option Hopt = new Option("H", true, "Add arbitrary header line, " +
"eg. 'Accept-Encoding: gzip' inserted after all normal " +
"header lines. (repeatable as -H \"h1: v1\",\"h2: v2\" etc)");
Hopt.setRequired(false);
Hopt.setArgName("header");
Option vopt = new Option("v", true, "Set verbosity level - 4 and above " +
"prints response content, 3 and above prints " +
"information on headers, 2 and above prints response codes (404, 200, " +
"etc.), 1 and above prints warnings and info");
vopt.setRequired(false);
vopt.setArgName("verbosity");
Option hopt = new Option("h", false, "Display usage information");
nopt.setRequired(false);
Options options = new Options();
options.addOption(iopt);
options.addOption(mopt);
options.addOption(uopt);
options.addOption(xopt);
options.addOption(gopt);
options.addOption(kopt);
options.addOption(nopt);
options.addOption(copt);
options.addOption(popt);
options.addOption(Topt);
options.addOption(vopt);
options.addOption(Hopt);
options.addOption(hopt);
options.addOption(topt);
options.addOption(oopt);
return options;
}
public static void parseCommandLine(CommandLine cmd, Config config) {
if (cmd.hasOption('v')) {
String s = cmd.getOptionValue('v');
try {
config.setVerbosity(Integer.parseInt(s));
} catch (NumberFormatException ex) {
printError("Invalid verbosity level: " + s);
}
}
if (cmd.hasOption('k')) {
config.setKeepAlive(true);
}
if (cmd.hasOption('c')) {
String s = cmd.getOptionValue('c');
try {
config.setThreads(Integer.parseInt(s));
} catch (NumberFormatException ex) {
printError("Invalid number for concurrency: " + s);
}
}
if (cmd.hasOption('n')) {
String s = cmd.getOptionValue('n');
try {
config.setRequests(Integer.parseInt(s));
} catch (NumberFormatException ex) {
printError("Invalid number of requests: " + s);
}
}
if (cmd.hasOption('p')) {
File file = new File(cmd.getOptionValue('p'));
if (!file.exists()) {
printError("File not found: " + file);
}
config.setPayloadFile(file);
}
if (cmd.hasOption('T')) {
config.setContentType(cmd.getOptionValue('T'));
}
if (cmd.hasOption('i')) {
config.setHeadInsteadOfGet(true);
}
if (cmd.hasOption('H')) {
String headerStr = cmd.getOptionValue('H');
config.setHeaders(headerStr.split(","));
}
if (cmd.hasOption('t')) {
String t = cmd.getOptionValue('t');
try {
config.setSocketTimeout(Integer.parseInt(t));
} catch (NumberFormatException ex) {
printError("Invalid socket timeout: " + t);
}
}
if (cmd.hasOption('o')) {
config.setUseHttp1_0(true);
}
if (cmd.hasOption('m')) {
config.setMethod(cmd.getOptionValue('m'));
} else if (cmd.hasOption('p')) {
config.setMethod("POST");
}
if (cmd.hasOption('u')) {
config.setUseChunking(true);
}
if (cmd.hasOption('x')) {
config.setUseExpectContinue(true);
}
if (cmd.hasOption('g')) {
config.setUseAcceptGZip(true);
}
String[] cmdargs = cmd.getArgs();
if (cmdargs.length > 0) {
try {
config.setUrl(new URL(cmdargs[0]));
} catch (MalformedURLException e) {
printError("Invalid request URL : " + cmdargs[0]);
}
}
}
static void showUsage(final Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("HttpBenchmark [options] [http://]hostname[:port]/path?query", options);
}
static void printError(String msg) {
System.err.println(msg);
showUsage(getOptions());
System.exit(-1);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-ab/src/main/java/org/apache/http/benchmark/CommandLineUtils.java
|
Java
|
gpl3
| 8,146
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpVersion;
import org.apache.http.entity.FileEntity;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
/**
* Main program of the HTTP benchmark.
*
*
* @since 4.0
*/
public class HttpBenchmark {
private final Config config;
private HttpParams params = null;
private HttpRequest[] request = null;
private HttpHost host = null;
private long contentLength = -1;
public static void main(String[] args) throws Exception {
Options options = CommandLineUtils.getOptions();
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
if (args.length == 0 || cmd.hasOption('h') || cmd.getArgs().length != 1) {
CommandLineUtils.showUsage(options);
System.exit(1);
}
Config config = new Config();
CommandLineUtils.parseCommandLine(cmd, config);
if (config.getUrl() == null) {
CommandLineUtils.showUsage(options);
System.exit(1);
}
HttpBenchmark httpBenchmark = new HttpBenchmark(config);
httpBenchmark.execute();
}
public HttpBenchmark(final Config config) {
super();
this.config = config != null ? config : new Config();
}
private void prepare() throws UnsupportedEncodingException {
// prepare http params
params = getHttpParams(config.getSocketTimeout(), config.isUseHttp1_0(), config.isUseExpectContinue());
URL url = config.getUrl();
host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
HttpEntity entity = null;
// Prepare requests for each thread
if (config.getPayloadFile() != null) {
entity = new FileEntity(config.getPayloadFile(), config.getContentType());
((FileEntity) entity).setChunked(config.isUseChunking());
contentLength = config.getPayloadFile().length();
} else if (config.getPayloadText() != null) {
entity = new StringEntity(config.getPayloadText(), config.getContentType(), "UTF-8");
((StringEntity) entity).setChunked(config.isUseChunking());
contentLength = config.getPayloadText().getBytes().length;
}
request = new HttpRequest[config.getThreads()];
for (int i = 0; i < request.length; i++) {
if ("POST".equals(config.getMethod())) {
BasicHttpEntityEnclosingRequest httppost =
new BasicHttpEntityEnclosingRequest("POST", url.getPath());
httppost.setEntity(entity);
request[i] = httppost;
} else if ("PUT".equals(config.getMethod())) {
BasicHttpEntityEnclosingRequest httpput =
new BasicHttpEntityEnclosingRequest("PUT", url.getPath());
httpput.setEntity(entity);
request[i] = httpput;
} else {
String path = url.getPath();
if (url.getQuery() != null && url.getQuery().length() > 0) {
path += "?" + url.getQuery();
} else if (path.trim().length() == 0) {
path = "/";
}
request[i] = new BasicHttpRequest(config.getMethod(), path);
}
}
if (!config.isKeepAlive()) {
for (int i = 0; i < request.length; i++) {
request[i].addHeader(new DefaultHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE));
}
}
String[] headers = config.getHeaders();
if (headers != null) {
for (int i = 0; i < headers.length; i++) {
String s = headers[i];
int pos = s.indexOf(':');
if (pos != -1) {
Header header = new DefaultHeader(s.substring(0, pos).trim(), s.substring(pos + 1));
for (int j = 0; j < request.length; j++) {
request[j].addHeader(header);
}
}
}
}
if (config.isUseAcceptGZip()) {
for (int i = 0; i < request.length; i++) {
request[i].addHeader(new DefaultHeader("Accept-Encoding", "gzip"));
}
}
if (config.getSoapAction() != null && config.getSoapAction().length() > 0) {
for (int i = 0; i < request.length; i++) {
request[i].addHeader(new DefaultHeader("SOAPAction", config.getSoapAction()));
}
}
}
public String execute() throws Exception {
prepare();
ThreadPoolExecutor workerPool = new ThreadPoolExecutor(
config.getThreads(), config.getThreads(), 5, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r, "ClientPool");
}
});
workerPool.prestartAllCoreThreads();
BenchmarkWorker[] workers = new BenchmarkWorker[config.getThreads()];
for (int i = 0; i < workers.length; i++) {
workers[i] = new BenchmarkWorker(
params,
config.getVerbosity(),
request[i],
host,
config.getRequests(),
config.isKeepAlive(),
config.isDisableSSLVerification(),
config.getTrustStorePath(),
config.getTrustStorePassword(),
config.getIdentityStorePath(),
config.getIdentityStorePassword());
workerPool.execute(workers[i]);
}
while (workerPool.getCompletedTaskCount() < config.getThreads()) {
Thread.yield();
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
}
}
workerPool.shutdown();
return ResultProcessor.printResults(workers, host, config.getUrl().toString(), contentLength);
}
private HttpParams getHttpParams(
int socketTimeout, boolean useHttp1_0, boolean useExpectContinue) {
HttpParams params = new BasicHttpParams();
params.setParameter(HttpProtocolParams.PROTOCOL_VERSION,
useHttp1_0 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1)
.setParameter(HttpProtocolParams.USER_AGENT, "HttpCore-AB/1.1")
.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, useExpectContinue)
.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false)
.setIntParameter(HttpConnectionParams.SO_TIMEOUT, socketTimeout);
return params;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-ab/src/main/java/org/apache/http/benchmark/HttpBenchmark.java
|
Java
|
gpl3
| 8,878
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.security.KeyStore;
import javax.net.SocketFactory;
import javax.net.ssl.*;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
/**
* Worker thread for the {@link HttpBenchmark HttpBenchmark}.
*
*
* @since 4.0
*/
public class BenchmarkWorker implements Runnable {
private byte[] buffer = new byte[4096];
private final int verbosity;
private final HttpParams params;
private final HttpContext context;
private final BasicHttpProcessor httpProcessor;
private final HttpRequestExecutor httpexecutor;
private final ConnectionReuseStrategy connstrategy;
private final HttpRequest request;
private final HttpHost targetHost;
private final int count;
private final boolean keepalive;
private final boolean disableSSLVerification;
private final Stats stats = new Stats();
private final TrustManager[] trustAllCerts;
private final String trustStorePath;
private final String trustStorePassword;
private final String identityStorePath;
private final String identityStorePassword;
public BenchmarkWorker(
final HttpParams params,
int verbosity,
final HttpRequest request,
final HttpHost targetHost,
int count,
boolean keepalive,
boolean disableSSLVerification,
String trustStorePath,
String trustStorePassword,
String identityStorePath,
String identityStorePassword) {
super();
this.params = params;
this.context = new BasicHttpContext(null);
this.request = request;
this.targetHost = targetHost;
this.count = count;
this.keepalive = keepalive;
this.httpProcessor = new BasicHttpProcessor();
this.httpexecutor = new HttpRequestExecutor();
// Required request interceptors
this.httpProcessor.addInterceptor(new RequestContent());
this.httpProcessor.addInterceptor(new RequestTargetHost());
// Recommended request interceptors
this.httpProcessor.addInterceptor(new RequestConnControl());
this.httpProcessor.addInterceptor(new RequestUserAgent());
this.httpProcessor.addInterceptor(new RequestExpectContinue());
this.connstrategy = new DefaultConnectionReuseStrategy();
this.verbosity = verbosity;
this.disableSSLVerification = disableSSLVerification;
this.trustStorePath = trustStorePath;
this.trustStorePassword = trustStorePassword;
this.identityStorePath = identityStorePath;
this.identityStorePassword = identityStorePassword;
// Create a trust manager that does not validate certificate chains
trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
}
public void run() {
HttpResponse response = null;
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
String hostname = targetHost.getHostName();
int port = targetHost.getPort();
if (port == -1) {
port = 80;
}
// Populate the execution context
this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost);
this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request);
stats.start();
request.setParams(new DefaultedHttpParams(new BasicHttpParams(), this.params));
for (int i = 0; i < count; i++) {
try {
resetHeader(request);
if (!conn.isOpen()) {
Socket socket = null;
if ("https".equals(targetHost.getSchemeName())) {
if (disableSSLVerification) {
SSLContext sc = SSLContext.getInstance("SSL");
if (identityStorePath != null) {
KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(identityStorePath);
try {
identityStore.load(instream, identityStorePassword.toCharArray());
} finally {
try { instream.close(); } catch (IOException ignore) {}
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmf.init(identityStore, identityStorePassword.toCharArray());
sc.init(kmf.getKeyManagers(), trustAllCerts, null);
} else {
sc.init(null, trustAllCerts, null);
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
socket = sc.getSocketFactory().createSocket(hostname, port);
} else {
if (trustStorePath != null) {
System.setProperty("javax.net.ssl.trustStore", trustStorePath);
}
if (trustStorePassword != null) {
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
}
SocketFactory socketFactory = SSLSocketFactory.getDefault();
socket = socketFactory.createSocket(hostname, port);
}
} else {
socket = new Socket(hostname, port);
}
conn.bind(socket, params);
}
try {
// Prepare request
this.httpexecutor.preProcess(this.request, this.httpProcessor, this.context);
// Execute request and get a response
response = this.httpexecutor.execute(this.request, conn, this.context);
// Finalize response
this.httpexecutor.postProcess(response, this.httpProcessor, this.context);
} catch (HttpException e) {
stats.incWriteErrors();
if (this.verbosity >= 2) {
System.err.println("Failed HTTP request : " + e.getMessage());
}
continue;
}
verboseOutput(response);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
stats.incSuccessCount();
} else {
stats.incFailureCount();
continue;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
String charset = EntityUtils.getContentCharSet(entity);
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
long contentlen = 0;
InputStream instream = entity.getContent();
int l = 0;
while ((l = instream.read(this.buffer)) != -1) {
stats.incTotalBytesRecv(l);
contentlen += l;
if (this.verbosity >= 4) {
String s = new String(this.buffer, 0, l, charset);
System.out.print(s);
}
}
instream.close();
stats.setContentLength(contentlen);
}
if (this.verbosity >= 4) {
System.out.println();
System.out.println();
}
if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) {
conn.close();
} else {
stats.incKeepAliveCount();
}
} catch (IOException ex) {
ex.printStackTrace();
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
} catch (Exception ex) {
ex.printStackTrace();
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("Generic error: " + ex.getMessage());
}
}
}
stats.finish();
if (response != null) {
Header header = response.getFirstHeader("Server");
if (header != null) {
stats.setServerName(header.getValue());
}
}
try {
conn.close();
} catch (IOException ex) {
ex.printStackTrace();
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
}
}
private void verboseOutput(HttpResponse response) {
if (this.verbosity >= 3) {
System.out.println(">> " + request.getRequestLine().toString());
Header[] headers = request.getAllHeaders();
for (int h = 0; h < headers.length; h++) {
System.out.println(">> " + headers[h].toString());
}
System.out.println();
}
if (this.verbosity >= 2) {
System.out.println(response.getStatusLine().getStatusCode());
}
if (this.verbosity >= 3) {
System.out.println("<< " + response.getStatusLine().toString());
Header[] headers = response.getAllHeaders();
for (int h = 0; h < headers.length; h++) {
System.out.println("<< " + headers[h].toString());
}
System.out.println();
}
}
private static void resetHeader(final HttpRequest request) {
for (HeaderIterator it = request.headerIterator(); it.hasNext();) {
Header header = it.nextHeader();
if (!(header instanceof DefaultHeader)) {
it.remove();
}
}
}
public Stats getStats() {
return stats;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-ab/src/main/java/org/apache/http/benchmark/BenchmarkWorker.java
|
Java
|
gpl3
| 13,436
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark;
import java.io.File;
import java.net.URL;
public class Config {
private URL url;
private int requests;
private int threads;
private boolean keepAlive;
private int verbosity;
private boolean headInsteadOfGet;
private boolean useHttp1_0;
private String contentType;
private String[] headers;
private int socketTimeout;
private String method = "GET";
private boolean useChunking;
private boolean useExpectContinue;
private boolean useAcceptGZip;
private File payloadFile = null;
private String payloadText = null;
private String soapAction = null;
private boolean disableSSLVerification = true;
private String trustStorePath = null;
private String identityStorePath = null;
private String trustStorePassword = null;
private String identityStorePassword = null;
public Config() {
super();
this.url = null;
this.requests = 1;
this.threads = 1;
this.keepAlive = false;
this.verbosity = 0;
this.headInsteadOfGet = false;
this.useHttp1_0 = false;
this.payloadFile = null;
this.payloadText = null;
this.contentType = null;
this.headers = null;
this.socketTimeout = 60000;
}
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
public int getRequests() {
return requests;
}
public void setRequests(int requests) {
this.requests = requests;
}
public int getThreads() {
return threads;
}
public void setThreads(int threads) {
this.threads = threads;
}
public boolean isKeepAlive() {
return keepAlive;
}
public void setKeepAlive(boolean keepAlive) {
this.keepAlive = keepAlive;
}
public int getVerbosity() {
return verbosity;
}
public void setVerbosity(int verbosity) {
this.verbosity = verbosity;
}
public boolean isHeadInsteadOfGet() {
return headInsteadOfGet;
}
public void setHeadInsteadOfGet(boolean headInsteadOfGet) {
this.headInsteadOfGet = headInsteadOfGet;
this.method = "HEAD";
}
public boolean isUseHttp1_0() {
return useHttp1_0;
}
public void setUseHttp1_0(boolean useHttp1_0) {
this.useHttp1_0 = useHttp1_0;
}
public File getPayloadFile() {
return payloadFile;
}
public void setPayloadFile(File payloadFile) {
this.payloadFile = payloadFile;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String[] getHeaders() {
return headers;
}
public void setHeaders(String[] headers) {
this.headers = headers;
}
public int getSocketTimeout() {
return socketTimeout;
}
public void setSocketTimeout(int socketTimeout) {
this.socketTimeout = socketTimeout;
}
public void setMethod(String method) {
this.method = method;
}
public void setUseChunking(boolean useChunking) {
this.useChunking = useChunking;
}
public void setUseExpectContinue(boolean useExpectContinue) {
this.useExpectContinue = useExpectContinue;
}
public void setUseAcceptGZip(boolean useAcceptGZip) {
this.useAcceptGZip = useAcceptGZip;
}
public String getMethod() {
return method;
}
public boolean isUseChunking() {
return useChunking;
}
public boolean isUseExpectContinue() {
return useExpectContinue;
}
public boolean isUseAcceptGZip() {
return useAcceptGZip;
}
public String getPayloadText() {
return payloadText;
}
public String getSoapAction() {
return soapAction;
}
public boolean isDisableSSLVerification() {
return disableSSLVerification;
}
public String getTrustStorePath() {
return trustStorePath;
}
public String getIdentityStorePath() {
return identityStorePath;
}
public String getTrustStorePassword() {
return trustStorePassword;
}
public String getIdentityStorePassword() {
return identityStorePassword;
}
public void setPayloadText(String payloadText) {
this.payloadText = payloadText;
}
public void setSoapAction(String soapAction) {
this.soapAction = soapAction;
}
public void setDisableSSLVerification(boolean disableSSLVerification) {
this.disableSSLVerification = disableSSLVerification;
}
public void setTrustStorePath(String trustStorePath) {
this.trustStorePath = trustStorePath;
}
public void setIdentityStorePath(String identityStorePath) {
this.identityStorePath = identityStorePath;
}
public void setTrustStorePassword(String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
public void setIdentityStorePassword(String identityStorePassword) {
this.identityStorePassword = identityStorePassword;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-ab/src/main/java/org/apache/http/benchmark/Config.java
|
Java
|
gpl3
| 6,414
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.benchmark;
import org.apache.http.message.BasicHeader;
public class DefaultHeader extends BasicHeader {
public DefaultHeader(final String name, final String value) {
super(name, value);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-ab/src/main/java/org/apache/http/benchmark/DefaultHeader.java
|
Java
|
gpl3
| 1,419
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.sip;
import org.apache.http.HttpException;
/**
* Signals that an SIP exception has occurred.
* This is for protocol errors specific to SIP,
* as opposed to protocol errors shared with HTTP.
*
*
*/
public class SipException extends HttpException {
private static final long serialVersionUID = 337592534308025800L;
/**
* Creates a new SipException with a <tt>null</tt> detail message.
*/
public SipException() {
super();
}
/**
* Creates a new SipException with the specified detail message.
*
* @param message the exception detail message
*/
public SipException(final String message) {
super(message);
}
/**
* Creates a new SipException with the specified detail message and cause.
*
* @param message the exception detail message
* @param cause the <tt>Throwable</tt> that caused this exception, or
* <tt>null</tt> if the cause is unavailable, unknown, or
* not a <tt>Throwable</tt>
*/
public SipException(final String message, final Throwable cause) {
super(message, cause);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/sip/SipException.java
|
Java
|
gpl3
| 2,371
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.sip;
import java.io.Serializable;
import org.apache.http.ProtocolVersion;
/**
* Represents an SIP version, as specified in RFC 3261.
*
*
*/
public final class SipVersion extends ProtocolVersion
implements Serializable {
private static final long serialVersionUID = 6112302080954348220L;
/** The protocol name. */
public static final String SIP = "SIP";
/** SIP protocol version 2.0 */
public static final SipVersion SIP_2_0 = new SipVersion(2, 0);
/**
* Create a SIP protocol version designator.
*
* @param major the major version number of the SIP protocol
* @param minor the minor version number of the SIP protocol
*
* @throws IllegalArgumentException
* if either major or minor version number is negative
*/
public SipVersion(int major, int minor) {
super(SIP, major, minor);
}
/**
* Obtains a specific SIP version.
*
* @param major the major version
* @param minor the minor version
*
* @return an instance of {@link SipVersion} with the argument version
*/
@Override
public ProtocolVersion forVersion(int major, int minor) {
if ((major == this.major) && (minor == this.minor)) {
return this;
}
if ((major == 2) && (minor == 0)) {
return SIP_2_0;
}
// argument checking is done in the constructor
return new SipVersion(major, minor);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/sip/SipVersion.java
|
Java
|
gpl3
| 2,707
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.sip;
import org.apache.http.FormattedHeader;
import org.apache.http.HeaderElement;
import org.apache.http.ParseException;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.message.ParserCursor;
import org.apache.http.message.BasicHeaderValueParser;
/**
* Represents a SIP (or HTTP) header field parsed 'on demand'.
* The name of the header will be parsed and mapped immediately,
* the value only when accessed
*
*
*/
public class BufferedCompactHeader
implements CompactHeader, FormattedHeader, Cloneable {
/** The full header name. */
private final String fullName;
/** The compact header name, if there is one. */
private final String compactName;
/**
* The buffer containing the entire header line.
*/
private final CharArrayBuffer buffer;
/**
* The beginning of the header value in the buffer
*/
private final int valuePos;
/**
* Creates a new header from a buffer.
* The name of the header will be parsed and mapped immediately,
* the value only if it is accessed.
*
* @param buffer the buffer containing the header to represent
* @param mapper the header name mapper, or <code>null</code> for the
* {@link BasicCompactHeaderMapper#DEFAULT default}
*
* @throws ParseException in case of a parse error
*/
public BufferedCompactHeader(final CharArrayBuffer buffer,
CompactHeaderMapper mapper)
throws ParseException {
super();
if (buffer == null) {
throw new IllegalArgumentException
("Char array buffer may not be null");
}
final int colon = buffer.indexOf(':');
if (colon == -1) {
throw new ParseException
("Missing colon after header name.\n" + buffer.toString());
}
final String name = buffer.substringTrimmed(0, colon);
if (name.length() == 0) {
throw new ParseException
("Missing header name.\n" + buffer.toString());
}
if (mapper == null)
mapper = BasicCompactHeaderMapper.DEFAULT;
final String altname = mapper.getAlternateName(name);
String fname = name;
String cname = altname;
if ((altname != null) && (name.length() < altname.length())) {
// the header uses the compact name
fname = altname;
cname = name;
}
this.fullName = fname;
this.compactName = cname;
this.buffer = buffer;
this.valuePos = colon + 1;
}
// non-javadoc, see interface Header
public String getName() {
return this.fullName;
}
// non-javadoc, see interface CompactHeader
public String getCompactName() {
return this.compactName;
}
// non-javadoc, see interface Header
public String getValue() {
return this.buffer.substringTrimmed(this.valuePos,
this.buffer.length());
}
// non-javadoc, see interface Header
public HeaderElement[] getElements() throws ParseException {
ParserCursor cursor = new ParserCursor(0, this.buffer.length());
cursor.updatePos(this.valuePos);
return BasicHeaderValueParser.DEFAULT
.parseElements(this.buffer, cursor);
}
// non-javadoc, see interface BufferedHeader
public int getValuePos() {
return this.valuePos;
}
// non-javadoc, see interface BufferedHeader
public CharArrayBuffer getBuffer() {
return this.buffer;
}
@Override
public String toString() {
return this.buffer.toString();
}
@Override
public Object clone() throws CloneNotSupportedException {
// buffer is considered immutable
// no need to make a copy of it
return super.clone();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/sip/BufferedCompactHeader.java
|
Java
|
gpl3
| 5,152
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.sip;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
/**
* Basic implementation of a {@link CompactHeaderMapper}.
* Header names are assumed to be case insensitive.
*
*
*/
public class BasicCompactHeaderMapper implements CompactHeaderMapper {
/**
* The map from compact names to full names.
* Keys are converted to lower case, values may be mixed case.
*/
protected Map<String,String> mapCompactToFull;
/**
* The map from full names to compact names.
* Keys are converted to lower case, values may be mixed case.
*/
protected Map<String,String> mapFullToCompact;
/**
* The default mapper.
* This mapper is initialized with the compact header names defined at
* <a href="http://www.iana.org/assignments/sip-parameters">
* http://www.iana.org/assignments/sip-parameters
* </a>
* on 2008-01-02.
*/
// see below for static initialization
public final static CompactHeaderMapper DEFAULT;
/**
* Creates a new header mapper with an empty mapping.
*/
public BasicCompactHeaderMapper() {
createMaps();
}
/**
* Initializes the two maps.
* The default implementation here creates an empty hash map for
* each attribute that is <code>null</code>.
* Derived implementations may choose to instantiate other
* map implementations, or to populate the maps by default.
* In the latter case, it is the responsibility of the dervied class
* to guarantee consistent mappings in both directions.
*/
protected void createMaps() {
if (mapCompactToFull == null) {
mapCompactToFull = new HashMap<String,String>();
}
if (mapFullToCompact == null) {
mapFullToCompact = new HashMap<String,String>();
}
}
/**
* Adds a header name mapping.
*
* @param compact the compact name of the header
* @param full the full name of the header
*/
public void addMapping(final String compact, final String full) {
if (compact == null) {
throw new IllegalArgumentException
("The compact name must not be null.");
}
if (full == null) {
throw new IllegalArgumentException
("The full name must not be null.");
}
if (compact.length() >= full.length()) {
throw new IllegalArgumentException
("The compact name must be shorter than the full name. " +
compact + " -> " + full);
}
mapCompactToFull.put(compact.toLowerCase(), full);
mapFullToCompact.put(full.toLowerCase(), compact);
}
/**
* Switches this mapper to read-only mode.
* Subsequent invocations of {@link #addMapping addMapping}
* will trigger an exception.
* <br/>
* The implementation here should be called only once.
* It replaces the internal maps with unmodifiable ones.
*/
protected void makeReadOnly() {
mapCompactToFull = Collections.unmodifiableMap(mapCompactToFull);
mapFullToCompact = Collections.unmodifiableMap(mapFullToCompact);
}
// non-javadoc, see interface CompactHeaderMapper
public String getCompactName(final String fullname) {
if (fullname == null) {
throw new IllegalArgumentException
("The full name must not be null.");
}
return mapFullToCompact.get(fullname.toLowerCase());
}
// non-javadoc, see interface CompactHeaderMapper
public String getFullName(final String compactname) {
if (compactname == null) {
throw new IllegalArgumentException
("The compact name must not be null.");
}
return mapCompactToFull.get(compactname.toLowerCase());
}
// non-javadoc, see interface CompactHeaderMapper
public String getAlternateName(final String name) {
if (name == null) {
throw new IllegalArgumentException
("The name must not be null.");
}
final String namelc = name.toLowerCase();
String result = null;
// to minimize lookups, use a heuristic to determine the direction
boolean iscompact = name.length() < 2;
if (iscompact) {
result = mapCompactToFull.get(namelc);
}
if (result == null) {
result = mapFullToCompact.get(namelc);
}
if ((result == null) && !iscompact) {
result = mapCompactToFull.get(namelc);
}
return result;
}
// initializes the default mapper and switches it to read-only mode
static {
BasicCompactHeaderMapper chm = new BasicCompactHeaderMapper();
chm.addMapping("a", "Accept-Contact");
chm.addMapping("u", "Allow-Events");
chm.addMapping("i", "Call-ID");
chm.addMapping("m", "Contact");
chm.addMapping("e", "Content-Encoding");
chm.addMapping("l", "Content-Length");
chm.addMapping("c", "Content-Type");
chm.addMapping("o", "Event");
chm.addMapping("f", "From");
chm.addMapping("y", "Identity");
chm.addMapping("n", "Identity-Info");
chm.addMapping("r", "Refer-To");
chm.addMapping("b", "Referred-By");
chm.addMapping("j", "Reject-Contact");
chm.addMapping("d", "Request-Disposition");
chm.addMapping("x", "Session-Expires");
chm.addMapping("s", "Subject");
chm.addMapping("k", "Supported");
chm.addMapping("t", "To");
chm.addMapping("v", "Via");
chm.makeReadOnly();
DEFAULT = chm;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/sip/BasicCompactHeaderMapper.java
|
Java
|
gpl3
| 6,926
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.sip;
import org.apache.http.Header;
/**
* Represents an SIP (or HTTP) header field with an optional compact name.
* RFC 3261 (SIP/2.0), section 7.3.3 specifies that some header field
* names have an abbreviated form which is equivalent to the full name.
* All compact header names defined for SIP are registered at
* <a href="http://www.iana.org/assignments/sip-parameters">
* http://www.iana.org/assignments/sip-parameters
* </a>.
* <br/>
* While all compact names defined so far are single-character names,
* RFC 3261 does not mandate that. This interface therefore allows for
* strings as the compact name.
*
*
*/
public interface CompactHeader extends Header {
/**
* Obtains the name of this header in compact form, if there is one.
*
* @return the compact name of this header, or
* <code>null</code> if there is none
*/
String getCompactName()
;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/sip/CompactHeader.java
|
Java
|
gpl3
| 2,141
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.sip;
import org.apache.http.message.BasicHeader;
/**
* Represents a SIP (or HTTP) header field with optional compact name.
*
*
*/
public class BasicCompactHeader extends BasicHeader
implements CompactHeader {
private static final long serialVersionUID = -8275767773930430518L;
/** The compact name, if there is one. */
private final String compact;
/**
* Constructor with names and value.
*
* @param fullname the full header name
* @param compactname the compact header name, or <code>null</code>
* @param value the header value
*/
public BasicCompactHeader(final String fullname,
final String compactname,
final String value) {
super(fullname, value);
if ((compactname != null) &&
(compactname.length() >= fullname.length())) {
throw new IllegalArgumentException
("Compact name must be shorter than full name. " +
compactname + " -> " + fullname);
}
this.compact = compactname;
}
// non-javadoc, see interface CompactHeader
public String getCompactName() {
return this.compact;
}
/**
* Creates a compact header with automatic lookup.
*
* @param name the header name, either full or compact
* @param value the header value
* @param mapper the header name mapper, or <code>null</code> for the
* {@link BasicCompactHeaderMapper#DEFAULT default}
*/
public static
BasicCompactHeader newHeader(final String name, final String value,
CompactHeaderMapper mapper) {
if (name == null) {
throw new IllegalArgumentException
("The name must not be null.");
}
// value will be checked by constructor later
if (mapper == null)
mapper = BasicCompactHeaderMapper.DEFAULT;
final String altname = mapper.getAlternateName(name);
String fname = name;
String cname = altname;
if ((altname != null) && (name.length() < altname.length())) {
// we were called with the compact name
fname = altname;
cname = name;
}
return new BasicCompactHeader(fname, cname, value);
}
// we might want a toString method that includes the short name, if defined
// default cloning implementation is fine
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/sip/BasicCompactHeader.java
|
Java
|
gpl3
| 3,747
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.sip;
import org.apache.http.Header;
import org.apache.http.ParseException;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.message.BasicLineParser;
/**
* Basic parser for lines in the head section of an SIP message.
*
*
*/
public class BasicSipLineParser extends BasicLineParser {
/** The header name mapper to use, never <code>null</code>. */
protected final CompactHeaderMapper mapper;
/**
* A default instance of this class, for use as default or fallback.
*/
public final static
BasicSipLineParser DEFAULT = new BasicSipLineParser(null);
/**
* Creates a new line parser for SIP protocol.
*
* @param mapper the header name mapper, or <code>null</code> for the
* {@link BasicCompactHeaderMapper#DEFAULT default}
*/
public BasicSipLineParser(CompactHeaderMapper mapper) {
super(SipVersion.SIP_2_0);
this.mapper = (mapper != null) ?
mapper : BasicCompactHeaderMapper.DEFAULT;
}
// non-javadoc, see interface LineParser
@Override
public Header parseHeader(CharArrayBuffer buffer)
throws ParseException {
// the actual parser code is in the constructor of BufferedHeader
return new BufferedCompactHeader(buffer, mapper);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/sip/BasicSipLineParser.java
|
Java
|
gpl3
| 2,536
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.sip;
import java.util.Locale;
import java.util.Map;
import java.util.HashMap;
import org.apache.http.ReasonPhraseCatalog;
/**
* English reason phrases for SIP status codes.
* All status codes defined in {@link SipStatus} are supported.
* See <a href="http://www.iana.org/assignments/sip-parameters">
* http://www.iana.org/assignments/sip-parameters
* </a>
* for a full list of registered SIP status codes and the defining RFCs.
*
*
*/
public class EnglishSipReasonPhraseCatalog
implements ReasonPhraseCatalog {
// static map with english reason phrases defined below
/**
* The default instance of this catalog.
* This catalog is thread safe, so there typically
* is no need to create other instances.
*/
public final static EnglishSipReasonPhraseCatalog INSTANCE =
new EnglishSipReasonPhraseCatalog();
/**
* Restricted default constructor, for derived classes.
* If you need an instance of this class, use {@link #INSTANCE INSTANCE}.
*/
protected EnglishSipReasonPhraseCatalog() {
// no body
}
/**
* Obtains the reason phrase for a status code.
*
* @param status the status code, in the range 100-699
* @param loc ignored
*
* @return the reason phrase, or <code>null</code>
*/
public String getReason(int status, Locale loc) {
if ((status < 100) || (status >= 700)) {
throw new IllegalArgumentException
("Unknown category for status code " + status + ".");
}
// Unlike HTTP status codes, those for SIP are not compact
// in each category. We therefore use a map for lookup.
return REASON_PHRASES.get(Integer.valueOf(status));
}
/**
* Reason phrases lookup table.
* Since this attribute is private and never exposed,
* we don't need to turn it into an unmodifiable map.
*/
// see below for static initialization
private static final
Map<Integer,String> REASON_PHRASES = new HashMap<Integer,String>();
/**
* Stores the given reason phrase, by status code.
* Helper method to initialize the static lookup map.
*
* @param status the status code for which to define the phrase
* @param reason the reason phrase for this status code
*/
private static void setReason(int status, String reason) {
REASON_PHRASES.put(Integer.valueOf(status), reason);
}
// ----------------------------------------------------- Static Initializer
/** Set up status code to "reason phrase" map. */
static {
// --- 1xx Informational ---
setReason(SipStatus.SC_CONTINUE,
"Trying");
setReason(SipStatus.SC_RINGING,
"Ringing");
setReason(SipStatus.SC_CALL_IS_BEING_FORWARDED,
"Call Is Being Forwarded");
setReason(SipStatus.SC_QUEUED,
"Queued");
setReason(SipStatus.SC_SESSION_PROGRESS,
"Session Progress");
// --- 2xx Successful ---
setReason(SipStatus.SC_OK,
"OK");
setReason(SipStatus.SC_ACCEPTED,
"Accepted");
// --- 3xx Redirection ---
setReason(SipStatus.SC_MULTIPLE_CHOICES,
"Multiple Choices");
setReason(SipStatus.SC_MOVED_PERMANENTLY,
"Moved Permanently");
setReason(SipStatus.SC_MOVED_TEMPORARILY,
"Moved Temporarily");
setReason(SipStatus.SC_USE_PROXY,
"Use Proxy");
setReason(SipStatus.SC_ALTERNATIVE_SERVICE,
"Alternative Service");
// --- 4xx Request Failure ---
setReason(SipStatus.SC_BAD_REQUEST,
"Bad Request");
setReason(SipStatus.SC_UNAUTHORIZED,
"Unauthorized");
setReason(SipStatus.SC_PAYMENT_REQUIRED,
"Payment Required");
setReason(SipStatus.SC_FORBIDDEN,
"Forbidden");
setReason(SipStatus.SC_NOT_FOUND,
"Not Found");
setReason(SipStatus.SC_METHOD_NOT_ALLOWED,
"Method Not Allowed");
setReason(SipStatus.SC_NOT_ACCEPTABLE,
"Not Acceptable");
setReason(SipStatus.SC_PROXY_AUTHENTICATION_REQUIRED,
"Proxy Authentication Required");
setReason(SipStatus.SC_REQUEST_TIMEOUT,
"Request Timeout");
setReason(SipStatus.SC_GONE,
"Gone");
setReason(SipStatus.SC_CONDITIONAL_REQUEST_FAILED,
"Conditional Request Failed");
setReason(SipStatus.SC_REQUEST_ENTITY_TOO_LARGE,
"Request Entity Too Large");
setReason(SipStatus.SC_REQUEST_URI_TOO_LONG,
"Request-URI Too Long");
setReason(SipStatus.SC_UNSUPPORTED_MEDIA_TYPE,
"Unsupported Media Type");
setReason(SipStatus.SC_UNSUPPORTED_URI_SCHEME,
"Unsupported URI Scheme");
setReason(SipStatus.SC_UNKNOWN_RESOURCE_PRIORITY,
"Unknown Resource-Priority");
setReason(SipStatus.SC_BAD_EXTENSION,
"Bad Extension");
setReason(SipStatus.SC_EXTENSION_REQUIRED,
"Extension Required");
setReason(SipStatus.SC_SESSION_INTERVAL_TOO_SMALL,
"Session Interval Too Small");
setReason(SipStatus.SC_INTERVAL_TOO_BRIEF,
"Interval Too Brief");
setReason(SipStatus.SC_USE_IDENTITY_HEADER,
"Use Identity Header");
setReason(SipStatus.SC_PROVIDE_REFERRER_IDENTITY,
"Provide Referrer Identity");
setReason(SipStatus.SC_ANONYMITY_DISALLOWED,
"Anonymity Disallowed");
setReason(SipStatus.SC_BAD_IDENTITY_INFO,
"Bad Identity-Info");
setReason(SipStatus.SC_UNSUPPORTED_CERTIFICATE,
"Unsupported Certificate");
setReason(SipStatus.SC_INVALID_IDENTITY_HEADER,
"Invalid Identity Header");
setReason(SipStatus.SC_TEMPORARILY_UNAVAILABLE,
"Temporarily Unavailable");
setReason(SipStatus.SC_CALL_TRANSACTION_DOES_NOT_EXIST,
"Call/Transaction Does Not Exist");
setReason(SipStatus.SC_LOOP_DETECTED,
"Loop Detected");
setReason(SipStatus.SC_TOO_MANY_HOPS,
"Too Many Hops");
setReason(SipStatus.SC_ADDRESS_INCOMPLETE,
"Address Incomplete");
setReason(SipStatus.SC_AMBIGUOUS,
"Ambiguous");
setReason(SipStatus.SC_BUSY_HERE,
"Busy Here");
setReason(SipStatus.SC_REQUEST_TERMINATED,
"Request Terminated");
setReason(SipStatus.SC_NOT_ACCEPTABLE_HERE,
"Not Acceptable Here");
setReason(SipStatus.SC_BAD_EVENT,
"Bad Event");
setReason(SipStatus.SC_REQUEST_PENDING,
"Request Pending");
setReason(SipStatus.SC_UNDECIPHERABLE,
"Undecipherable");
setReason(SipStatus.SC_SECURITY_AGREEMENT_REQUIRED,
"Security Agreement Required");
// --- 5xx Server Failure ---
setReason(SipStatus.SC_SERVER_INTERNAL_ERROR,
"Server Internal Error");
setReason(SipStatus.SC_NOT_IMPLEMENTED,
"Not Implemented");
setReason(SipStatus.SC_BAD_GATEWAY,
"Bad Gateway");
setReason(SipStatus.SC_SERVICE_UNAVAILABLE,
"Service Unavailable");
setReason(SipStatus.SC_SERVER_TIMEOUT,
"Server Time-out");
setReason(SipStatus.SC_VERSION_NOT_SUPPORTED,
"Version Not Supported");
setReason(SipStatus.SC_MESSAGE_TOO_LARGE,
"Message Too Large");
setReason(SipStatus.SC_PRECONDITION_FAILURE,
"Precondition Failure");
// --- 6xx Global Failures ---
setReason(SipStatus.SC_BUSY_EVERYWHERE,
"Busy Everywhere");
setReason(SipStatus.SC_DECLINE,
"Decline");
setReason(SipStatus.SC_DOES_NOT_EXIST_ANYWHERE,
"Does Not Exist Anywhere");
setReason(SipStatus.SC_NOT_ACCEPTABLE_ANYWHERE,
"Not Acceptable");
} // static initializer
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/sip/EnglishSipReasonPhraseCatalog.java
|
Java
|
gpl3
| 9,722
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.sip;
/**
* A mapper between full and compact header names.
* RFC 3261 (SIP/2.0), section 7.3.3 specifies that some header field
* names have an abbreviated form which is equivalent to the full name.
* All compact header names defined for SIP are registered at
* <a href="http://www.iana.org/assignments/sip-parameters">
* http://www.iana.org/assignments/sip-parameters
* </a>.
* <br/>
* While all compact names defined so far are single-character names,
* RFC 3261 does not mandate that. This interface therefore allows for
* strings as the compact name.
*
*
*/
public interface CompactHeaderMapper {
/**
* Obtains the compact name for the given full name.
*
* @param fullname the header name for which to look up the compact form
*
* @return the compact form of the argument header name, or
* <code>null</code> if there is none
*/
String getCompactName(String fullname)
;
/**
* Obtains the full name for the given compact name.
*
* @param compactname the compact name for which to look up the full name
*
* @return the full name of the argument compact header name, or
* <code>null</code> if there is none
*/
String getFullName(String compactname)
;
/**
* Obtains the alternate name for the given header name.
* This performs a lookup in both directions, if necessary.
* <br/>
* If the returned name is shorter than the argument name,
* the argument was a full header name and the result is
* the compact name.
* If the returned name is longer than the argument name,
* the argument was a compact header name and the result
* is the full name.
* If the returned name has the same length as the argument name,
* somebody didn't understand the concept of a <i>compact form</i>
* when defining the mapping. You should expect malfunctioning
* applications in this case.
*
* @param name the header name to map, either a full or compact name
*
* @return the alternate header name, or
* <code>null</code> if there is none
*/
String getAlternateName(String name)
;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/sip/CompactHeaderMapper.java
|
Java
|
gpl3
| 3,449
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.sip;
/**
* Constants enumerating the SIP status codes.
* All status codes registered at
* <a href="http://www.iana.org/assignments/sip-parameters">
* http://www.iana.org/assignments/sip-parameters
* </a>
* on 2007-12-30 are listed.
* The defining RFCs include RFC 3261 (SIP/2.0),
* RFC 3265 (SIP-Specific Event Notification),
* RFC 4412 (Communications Resource Priority for SIP),
* RFC 4474 (Enhancements for Authenticated Identity Management in SIP),
* and others.
*
*
*/
public interface SipStatus {
// --- 1xx Informational ---
/** <tt>100 Trying</tt>. RFC 3261, section 21.1.1. */
public static final int SC_CONTINUE = 100;
/** <tt>180 Ringing</tt>. RFC 3261, section 21.1.2. */
public static final int SC_RINGING = 180;
/** <tt>181 Call Is Being Forwarded</tt>. RFC 3261, section 21.1.3. */
public static final int SC_CALL_IS_BEING_FORWARDED = 181;
/** <tt>182 Queued</tt>. RFC 3261, section 21.1.4. */
public static final int SC_QUEUED = 182;
/** <tt>183 Session Progress</tt>. RFC 3261, section 21.1.5. */
public static final int SC_SESSION_PROGRESS = 183;
// --- 2xx Successful ---
/** <tt>200 OK</tt>. RFC 3261, section 21.2.1. */
public static final int SC_OK = 200;
/** <tt>202 Accepted</tt>. RFC 3265, section 6.4. */
public static final int SC_ACCEPTED = 202;
// --- 3xx Redirection ---
/** <tt>300 Multiple Choices</tt>. RFC 3261, section 21.3.1. */
public static final int SC_MULTIPLE_CHOICES = 300;
/** <tt>301 Moved Permanently</tt>. RFC 3261, section 21.3.2. */
public static final int SC_MOVED_PERMANENTLY = 301;
/** <tt>302 Moved Temporarily</tt>. RFC 3261, section 21.3.3. */
public static final int SC_MOVED_TEMPORARILY = 302;
/** <tt>305 Use Proxy</tt>. RFC 3261, section 21.3.4. */
public static final int SC_USE_PROXY = 305;
/** <tt>380 Alternative Service</tt>. RFC 3261, section 21.3.5. */
public static final int SC_ALTERNATIVE_SERVICE = 380;
// --- 4xx Request Failure ---
/** <tt>400 Bad Request</tt>. RFC 3261, section 21.4.1. */
public static final int SC_BAD_REQUEST = 400;
/** <tt>401 Unauthorized</tt>. RFC 3261, section 21.4.2. */
public static final int SC_UNAUTHORIZED = 401;
/** <tt>402 Payment Required</tt>. RFC 3261, section 21.4.3. */
public static final int SC_PAYMENT_REQUIRED = 402;
/** <tt>403 Forbidden</tt>. RFC 3261, section 21.4.4. */
public static final int SC_FORBIDDEN = 403;
/** <tt>404 Not Found</tt>. RFC 3261, section 21.4.5. */
public static final int SC_NOT_FOUND = 404;
/** <tt>405 Method Not Allowed</tt>. RFC 3261, section 21.4.6. */
public static final int SC_METHOD_NOT_ALLOWED = 405;
/** <tt>406 Not Acceptable</tt>. RFC 3261, section 21.4.7. */
public static final int SC_NOT_ACCEPTABLE = 406;
/**
* <tt>407 Proxy Authentication Required</tt>.
* RFC 3261, section 21.4.8.
*/
public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
/** <tt>408 Request Timeout</tt>. RFC 3261, section 21.4.9. */
public static final int SC_REQUEST_TIMEOUT = 408;
/** <tt>410 Gone</tt>. RFC 3261, section 21.4.10. */
public static final int SC_GONE = 410;
/** <tt>412 Conditional Request Failed</tt>. RFC 3903, section 11.2.1. */
public static final int SC_CONDITIONAL_REQUEST_FAILED = 412;
/** <tt>413 Request Entity Too Large</tt>. RFC 3261, section 21.4.11. */
public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413;
/** <tt>414 Request-URI Too Long</tt>. RFC 3261, section 21.4.12. */
public static final int SC_REQUEST_URI_TOO_LONG = 414;
/** <tt>415 Unsupported Media Type</tt>. RFC 3261, section 21.4.13. */
public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
/** <tt>416 Unsupported URI Scheme</tt>. RFC 3261, section 21.4.14. */
public static final int SC_UNSUPPORTED_URI_SCHEME = 416;
/** <tt>417 Unknown Resource-Priority</tt>. RFC 4412, section 12.4. */
public static final int SC_UNKNOWN_RESOURCE_PRIORITY = 417;
/** <tt>420 Bad Extension</tt>. RFC 3261, section 21.4.15. */
public static final int SC_BAD_EXTENSION = 420;
/** <tt>421 Extension Required</tt>. RFC 3261, section 21.4.16. */
public static final int SC_EXTENSION_REQUIRED = 421;
/** <tt>422 Session Interval Too Small</tt>. RFC 4028, chapter 6. */
public static final int SC_SESSION_INTERVAL_TOO_SMALL = 422;
/** <tt>423 Interval Too Brief</tt>. RFC 3261, section 21.4.17. */
public static final int SC_INTERVAL_TOO_BRIEF = 423;
/** <tt>428 Use Identity Header</tt>. RFC 4474, section 14.2. */
public static final int SC_USE_IDENTITY_HEADER = 428;
/** <tt>429 Provide Referrer Identity</tt>. RFC 3892, chapter 5. */
public static final int SC_PROVIDE_REFERRER_IDENTITY = 429;
/** <tt>433 Anonymity Disallowed</tt>. RFC 5079, chapter 5. */
public static final int SC_ANONYMITY_DISALLOWED = 433;
/** <tt>436 Bad Identity-Info</tt>. RFC 4474, section 14.3. */
public static final int SC_BAD_IDENTITY_INFO = 436;
/** <tt>437 Unsupported Certificate</tt>. RFC 4474, section 14.4. */
public static final int SC_UNSUPPORTED_CERTIFICATE = 437;
/** <tt>438 Invalid Identity Header</tt>. RFC 4474, section 14.5. */
public static final int SC_INVALID_IDENTITY_HEADER = 438;
/** <tt>480 Temporarily Unavailable</tt>. RFC 3261, section 21.4.18. */
public static final int SC_TEMPORARILY_UNAVAILABLE = 480;
/**
* <tt>481 Call/Transaction Does Not Exist</tt>.
* RFC 3261, section 21.4.19.
*/
public static final int SC_CALL_TRANSACTION_DOES_NOT_EXIST = 481;
/** <tt>482 Loop Detected</tt>. RFC 3261, section 21.4.20. */
public static final int SC_LOOP_DETECTED = 482;
/** <tt>483 Too Many Hops</tt>. RFC 3261, section 21.4.21. */
public static final int SC_TOO_MANY_HOPS = 483;
/** <tt>484 Address Incomplete</tt>. RFC 3261, section 21.4.22. */
public static final int SC_ADDRESS_INCOMPLETE = 484;
/** <tt>485 Ambiguous</tt>. RFC 3261, section 21.4.23. */
public static final int SC_AMBIGUOUS = 485;
/** <tt>486 Busy Here</tt>. RFC 3261, section 21.4.24. */
public static final int SC_BUSY_HERE = 486;
/** <tt>487 Request Terminated</tt>. RFC 3261, section 21.4.25. */
public static final int SC_REQUEST_TERMINATED = 487;
/** <tt>488 Not Acceptable Here</tt>. RFC 3261, section 21.4.26. */
public static final int SC_NOT_ACCEPTABLE_HERE = 488;
/** <tt>489 Bad Event</tt>. RFC 3265, section 6.4. */
public static final int SC_BAD_EVENT = 489;
/** <tt>491 Request Pending</tt>. RFC 3261, section 21.4.27. */
public static final int SC_REQUEST_PENDING = 491;
/** <tt>493 Undecipherable</tt>. RFC 3261, section 21.4.28. */
public static final int SC_UNDECIPHERABLE = 493;
/** <tt>494 Security Agreement Required</tt>. RFC 3329, section 6.4. */
public static final int SC_SECURITY_AGREEMENT_REQUIRED = 494;
// --- 5xx Server Failure ---
/** <tt>500 Server Internal Error</tt>. RFC 3261, section 21.5.1. */
public static final int SC_SERVER_INTERNAL_ERROR = 500;
/** <tt>501 Not Implemented</tt>. RFC 3261, section 21.5.2. */
public static final int SC_NOT_IMPLEMENTED = 501;
/** <tt>502 Bad Gateway</tt>. RFC 3261, section 21.5.3. */
public static final int SC_BAD_GATEWAY = 502;
/** <tt>503 Service Unavailable</tt>. RFC 3261, section 21.5.4. */
public static final int SC_SERVICE_UNAVAILABLE = 503;
/** <tt>504 Server Time-out</tt>. RFC 3261, section 21.5.5. */
public static final int SC_SERVER_TIMEOUT = 504;
/** <tt>505 Version Not Supported</tt>. RFC 3261, section 21.5.6. */
public static final int SC_VERSION_NOT_SUPPORTED = 505;
/** <tt>513 Message Too Large</tt>. RFC 3261, section 21.5.7. */
public static final int SC_MESSAGE_TOO_LARGE = 513;
/** <tt>580 Precondition Failure</tt>. RFC 3312, chapter 8. */
public static final int SC_PRECONDITION_FAILURE = 580;
// --- 6xx Global Failures ---
/** <tt>600 Busy Everywhere</tt>. RFC 3261, section 21.6.1. */
public static final int SC_BUSY_EVERYWHERE = 600;
/** <tt>603 Decline</tt>. RFC 3261, section 21.6.2. */
public static final int SC_DECLINE = 603;
/** <tt>604 Does Not Exist Anywhere</tt>. RFC 3261, section 21.6.3. */
public static final int SC_DOES_NOT_EXIST_ANYWHERE = 604;
/**
* <tt>606 Not Acceptable</tt>. RFC 3261, section 21.6.4.
* Status codes 606 and 406 both indicate "Not Acceptable",
* but we can only define one constant with that name in this interface.
* 406 is specific to an endpoint, while 606 is global and
* indicates that the callee will not find the request acceptable
* on any endpoint.
*/
public static final int SC_NOT_ACCEPTABLE_ANYWHERE = 606;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/sip/SipStatus.java
|
Java
|
gpl3
| 10,162
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.compress;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.protocol.HttpContext;
/**
* Client-side interceptor to indicate support for Gzip content compression.
*
*
* @since 4.0
*/
public class RequestAcceptEncoding implements HttpRequestInterceptor {
private static final String ACCEPT_ENCODING = "Accept-Encoding";
private static final String GZIP_CODEC = "gzip";
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (!request.containsHeader(ACCEPT_ENCODING)) {
request.addHeader(ACCEPT_ENCODING, GZIP_CODEC);
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/compress/RequestAcceptEncoding.java
|
Java
|
gpl3
| 1,985
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.compress;
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.ExecutionContext;
/**
* Server-side interceptor to handle Gzip-encoded responses.
*
*
* @since 4.0
*/
public class ResponseGzipCompress implements HttpResponseInterceptor {
private static final String ACCEPT_ENCODING = "Accept-Encoding";
private static final String GZIP_CODEC = "gzip";
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
HttpEntity entity = response.getEntity();
if (entity != null) {
HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
Header aeheader = request.getFirstHeader(ACCEPT_ENCODING);
if (aeheader != null) {
HeaderElement[] codecs = aeheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase(GZIP_CODEC)) {
response.setEntity(new GzipCompressingEntity(entity));
return;
}
}
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/compress/ResponseGzipCompress.java
|
Java
|
gpl3
| 2,819
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.compress;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
/**
* Wrapping entity that decompresses {@link #getContent content}.
*
*
* @since 4.0
*/
public class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent()
throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
// length of ungzipped content not known in advance
return -1;
}
} // class GzipDecompressingEntity
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/compress/GzipDecompressingEntity.java
|
Java
|
gpl3
| 2,125
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.compress;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
/**
* Wrapping entity that compresses content when {@link #writeTo writing}.
*
*
* @since 4.0
*/
public class GzipCompressingEntity extends HttpEntityWrapper {
private static final String GZIP_CODEC = "gzip";
public GzipCompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public Header getContentEncoding() {
return new BasicHeader(HTTP.CONTENT_ENCODING, GZIP_CODEC);
}
@Override
public long getContentLength() {
return -1;
}
@Override
public boolean isChunked() {
// force content chunking
return true;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
GZIPOutputStream gzip = new GZIPOutputStream(outstream);
InputStream in = wrappedEntity.getContent();
byte[] tmp = new byte[2048];
int l;
while ((l = in.read(tmp)) != -1) {
gzip.write(tmp, 0, l);
}
gzip.close();
}
} // class GzipCompressingEntity
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/compress/GzipCompressingEntity.java
|
Java
|
gpl3
| 2,709
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.compress;
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.protocol.HttpContext;
/**
* Client-side interceptor to handle Gzip-compressed responses.
*
*
* @since 4.0
*/
public class ResponseGzipUncompress implements HttpResponseInterceptor {
private static final String GZIP_CODEC = "gzip";
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
HttpEntity entity = response.getEntity();
if (entity != null) {
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase(GZIP_CODEC)) {
response.setEntity(new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/compress/ResponseGzipUncompress.java
|
Java
|
gpl3
| 2,573
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.logging;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.impl.nio.DefaultNHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.params.HttpParams;
public class LoggingNHttpClientConnection extends DefaultNHttpClientConnection {
private final Log log;
private final Log headerlog;
public LoggingNHttpClientConnection(
final IOSession session,
final HttpResponseFactory responseFactory,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(session, responseFactory, allocator, params);
this.log = LogFactory.getLog(getClass());
this.headerlog = LogFactory.getLog("org.apache.http.headers");
}
@Override
public void close() throws IOException {
this.log.debug("Close connection");
super.close();
}
@Override
public void shutdown() throws IOException {
this.log.debug("Shutdown connection");
super.shutdown();
}
@Override
public void submitRequest(final HttpRequest request) throws IOException, HttpException {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + this + ": " + request.getRequestLine().toString());
}
super.submitRequest(request);
}
@Override
public void consumeInput(final NHttpClientHandler handler) {
this.log.debug("Consume input");
super.consumeInput(handler);
}
@Override
public void produceOutput(final NHttpClientHandler handler) {
this.log.debug("Produce output");
super.produceOutput(handler);
}
@Override
protected NHttpMessageWriter<HttpRequest> createRequestWriter(
final SessionOutputBuffer buffer,
final HttpParams params) {
return new LoggingNHttpMessageWriter(
super.createRequestWriter(buffer, params));
}
@Override
protected NHttpMessageParser<HttpResponse> createResponseParser(
final SessionInputBuffer buffer,
final HttpResponseFactory responseFactory,
final HttpParams params) {
return new LoggingNHttpMessageParser(
super.createResponseParser(buffer, responseFactory, params));
}
class LoggingNHttpMessageWriter implements NHttpMessageWriter<HttpRequest> {
private final NHttpMessageWriter<HttpRequest> writer;
public LoggingNHttpMessageWriter(final NHttpMessageWriter<HttpRequest> writer) {
super();
this.writer = writer;
}
public void reset() {
this.writer.reset();
}
public void write(final HttpRequest message) throws IOException, HttpException {
if (message != null && headerlog.isDebugEnabled()) {
headerlog.debug(">> " + message.getRequestLine().toString());
Header[] headers = message.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
headerlog.debug(">> " + headers[i].toString());
}
}
this.writer.write(message);
}
}
class LoggingNHttpMessageParser implements NHttpMessageParser<HttpResponse> {
private final NHttpMessageParser<HttpResponse> parser;
public LoggingNHttpMessageParser(final NHttpMessageParser<HttpResponse> parser) {
super();
this.parser = parser;
}
public void reset() {
this.parser.reset();
}
public int fillBuffer(final ReadableByteChannel channel) throws IOException {
return this.parser.fillBuffer(channel);
}
public HttpResponse parse() throws IOException, HttpException {
HttpResponse message = this.parser.parse();
if (message != null && headerlog.isDebugEnabled()) {
headerlog.debug("<< " + message.getStatusLine().toString());
Header[] headers = message.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
headerlog.debug("<< " + headers[i].toString());
}
}
return message;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/logging/LoggingNHttpClientConnection.java
|
Java
|
gpl3
| 6,052
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.logging;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.HttpResponse;
import org.apache.http.impl.nio.DefaultNHttpServerConnection;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.params.HttpParams;
public class LoggingNHttpServerConnection extends DefaultNHttpServerConnection {
private final Log log;
private final Log headerlog;
public LoggingNHttpServerConnection(
final IOSession session,
final HttpRequestFactory requestFactory,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(session, requestFactory, allocator, params);
this.log = LogFactory.getLog(getClass());
this.headerlog = LogFactory.getLog("org.apache.http.headers");
}
@Override
public void close() throws IOException {
this.log.debug("Close connection");
super.close();
}
@Override
public void shutdown() throws IOException {
this.log.debug("Shutdown connection");
super.shutdown();
}
@Override
public void submitResponse(final HttpResponse response) throws IOException, HttpException {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + this + ": " + response.getStatusLine().toString());
}
super.submitResponse(response);
}
@Override
public void consumeInput(final NHttpServiceHandler handler) {
this.log.debug("Consume input");
super.consumeInput(handler);
}
@Override
public void produceOutput(final NHttpServiceHandler handler) {
this.log.debug("Produce output");
super.produceOutput(handler);
}
@Override
protected NHttpMessageWriter<HttpResponse> createResponseWriter(
final SessionOutputBuffer buffer,
final HttpParams params) {
return new LoggingNHttpMessageWriter(
super.createResponseWriter(buffer, params));
}
@Override
protected NHttpMessageParser<HttpRequest> createRequestParser(
final SessionInputBuffer buffer,
final HttpRequestFactory requestFactory,
final HttpParams params) {
return new LoggingNHttpMessageParser(
super.createRequestParser(buffer, requestFactory, params));
}
class LoggingNHttpMessageWriter implements NHttpMessageWriter<HttpResponse> {
private final NHttpMessageWriter<HttpResponse> writer;
public LoggingNHttpMessageWriter(final NHttpMessageWriter<HttpResponse> writer) {
super();
this.writer = writer;
}
public void reset() {
this.writer.reset();
}
public void write(final HttpResponse message) throws IOException, HttpException {
if (message != null && headerlog.isDebugEnabled()) {
headerlog.debug("<< " + message.getStatusLine().toString());
Header[] headers = message.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
headerlog.debug("<< " + headers[i].toString());
}
}
this.writer.write(message);
}
}
class LoggingNHttpMessageParser implements NHttpMessageParser<HttpRequest> {
private final NHttpMessageParser<HttpRequest> parser;
public LoggingNHttpMessageParser(final NHttpMessageParser<HttpRequest> parser) {
super();
this.parser = parser;
}
public void reset() {
this.parser.reset();
}
public int fillBuffer(final ReadableByteChannel channel) throws IOException {
return this.parser.fillBuffer(channel);
}
public HttpRequest parse() throws IOException, HttpException {
HttpRequest message = this.parser.parse();
if (message != null && headerlog.isDebugEnabled()) {
headerlog.debug(">> " + message.getRequestLine().toString());
Header[] headers = message.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
headerlog.debug(">> " + headers[i].toString());
}
}
return message;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/logging/LoggingNHttpServerConnection.java
|
Java
|
gpl3
| 6,052
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.logging;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.NHttpServiceHandler;
/**
* Decorator class intended to transparently extend an {@link NHttpServiceHandler}
* with basic event logging capabilities using Commons Logging.
*
*/
public class LoggingNHttpServiceHandler implements NHttpServiceHandler {
private final Log log;
private final Log headerlog;
private final NHttpServiceHandler handler;
public LoggingNHttpServiceHandler(final NHttpServiceHandler handler) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP service handler may not be null");
}
this.handler = handler;
this.log = LogFactory.getLog(handler.getClass());
this.headerlog = LogFactory.getLog("org.apache.http.headers");
}
public void connected(final NHttpServerConnection conn) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Connected");
}
this.handler.connected(conn);
}
public void closed(final NHttpServerConnection conn) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Closed");
}
this.handler.closed(conn);
}
public void exception(final NHttpServerConnection conn, final IOException ex) {
this.log.error("HTTP connection " + conn + ": " + ex.getMessage(), ex);
this.handler.exception(conn, ex);
}
public void exception(final NHttpServerConnection conn, final HttpException ex) {
this.log.error("HTTP connection " + conn + ": " + ex.getMessage(), ex);
this.handler.exception(conn, ex);
}
public void requestReceived(final NHttpServerConnection conn) {
HttpRequest request = conn.getHttpRequest();
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": " + request.getRequestLine());
}
this.handler.requestReceived(conn);
if (this.headerlog.isDebugEnabled()) {
this.headerlog.debug(">> " + request.getRequestLine().toString());
Header[] headers = request.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
this.headerlog.debug(">> " + headers[i].toString());
}
}
}
public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Output ready");
}
this.handler.outputReady(conn, encoder);
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Content encoder " + encoder);
}
}
public void responseReady(final NHttpServerConnection conn) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Response ready");
}
this.handler.responseReady(conn);
}
public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Input ready");
}
this.handler.inputReady(conn, decoder);
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Content decoder " + decoder);
}
}
public void timeout(final NHttpServerConnection conn) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Timeout");
}
this.handler.timeout(conn);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/logging/LoggingNHttpServiceHandler.java
|
Java
|
gpl3
| 5,170
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.logging;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpException;
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;
/**
* Decorator class intended to transparently extend an {@link NHttpClientHandler}
* with basic event logging capabilities using Commons Logging.
*
*/
public class LoggingNHttpClientHandler implements NHttpClientHandler {
private final Log log;
private final Log headerlog;
private final NHttpClientHandler handler;
public LoggingNHttpClientHandler(final NHttpClientHandler handler) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP client handler may not be null");
}
this.handler = handler;
this.log = LogFactory.getLog(handler.getClass());
this.headerlog = LogFactory.getLog("org.apache.http.headers");
}
public void connected(final NHttpClientConnection conn, final Object attachment) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Connected (" + attachment + ")");
}
this.handler.connected(conn, attachment);
}
public void closed(final NHttpClientConnection conn) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Closed");
}
this.handler.closed(conn);
}
public void exception(final NHttpClientConnection conn, final IOException ex) {
this.log.error("HTTP connection " + conn + ": " + ex.getMessage(), ex);
this.handler.exception(conn, ex);
}
public void exception(final NHttpClientConnection conn, final HttpException ex) {
this.log.error("HTTP connection " + conn + ": " + ex.getMessage(), ex);
this.handler.exception(conn, ex);
}
public void requestReady(final NHttpClientConnection conn) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Request ready");
}
this.handler.requestReady(conn);
}
public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Output ready");
}
this.handler.outputReady(conn, encoder);
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Content encoder " + encoder);
}
}
public void responseReceived(final NHttpClientConnection conn) {
HttpResponse response = conn.getHttpResponse();
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": " + response.getStatusLine());
}
this.handler.responseReceived(conn);
if (this.headerlog.isDebugEnabled()) {
this.headerlog.debug("<< " + response.getStatusLine().toString());
Header[] headers = response.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
this.headerlog.debug("<< " + headers[i].toString());
}
}
}
public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Input ready");
}
this.handler.inputReady(conn, decoder);
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Content decoder " + decoder);
}
}
public void timeout(final NHttpClientConnection conn) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP connection " + conn + ": Timeout");
}
this.handler.timeout(conn);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/logging/LoggingNHttpClientHandler.java
|
Java
|
gpl3
| 5,224
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.logging;
import org.apache.http.impl.nio.DefaultClientIOEventDispatch;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.NHttpClientIOTarget;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.params.HttpParams;
public class LoggingClientIOEventDispatch extends DefaultClientIOEventDispatch {
public LoggingClientIOEventDispatch(
final NHttpClientHandler handler,
final HttpParams params) {
super(new LoggingNHttpClientHandler(handler), params);
}
@Override
protected NHttpClientIOTarget createConnection(final IOSession session) {
return new LoggingNHttpClientConnection(
new LoggingIOSession(session, "client"),
createHttpResponseFactory(),
this.allocator,
this.params);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/logging/LoggingClientIOEventDispatch.java
|
Java
|
gpl3
| 2,049
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.logging;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.SelectionKey;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionBufferStatus;
/**
* Decorator class intended to transparently extend an {@link IOSession}
* with basic event logging capabilities using Commons Logging.
*
*/
public class LoggingIOSession implements IOSession {
private static AtomicLong COUNT = new AtomicLong(0);
private final Log log;
private final Wire wirelog;
private final IOSession session;
private final ByteChannel channel;
private final String id;
public LoggingIOSession(final IOSession session, final String id) {
super();
if (session == null) {
throw new IllegalArgumentException("I/O session may not be null");
}
this.session = session;
this.channel = new LoggingByteChannel();
this.id = id + "-" + COUNT.incrementAndGet();
this.log = LogFactory.getLog(session.getClass());
this.wirelog = new Wire(LogFactory.getLog("org.apache.http.wire"));
}
public ByteChannel channel() {
return this.channel;
}
public SocketAddress getLocalAddress() {
return this.session.getLocalAddress();
}
public SocketAddress getRemoteAddress() {
return this.session.getRemoteAddress();
}
public int getEventMask() {
return this.session.getEventMask();
}
private static String formatOps(int ops) {
StringBuffer buffer = new StringBuffer(6);
buffer.append('[');
if ((ops & SelectionKey.OP_READ) > 0) {
buffer.append('r');
}
if ((ops & SelectionKey.OP_WRITE) > 0) {
buffer.append('w');
}
if ((ops & SelectionKey.OP_ACCEPT) > 0) {
buffer.append('a');
}
if ((ops & SelectionKey.OP_CONNECT) > 0) {
buffer.append('c');
}
buffer.append(']');
return buffer.toString();
}
public void setEventMask(int ops) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O session " + this.id + " " + this.session + ": Set event mask "
+ formatOps(ops));
}
this.session.setEventMask(ops);
}
public void setEvent(int op) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O session " + this.id + " " + this.session + ": Set event "
+ formatOps(op));
}
this.session.setEvent(op);
}
public void clearEvent(int op) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O session " + this.id + " " + this.session + ": Clear event "
+ formatOps(op));
}
this.session.clearEvent(op);
}
public void close() {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O session " + this.id + " " + this.session + ": Close");
}
this.session.close();
}
public int getStatus() {
return this.session.getStatus();
}
public boolean isClosed() {
return this.session.isClosed();
}
public void shutdown() {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O session " + this.id + " " + this.session + ": Shutdown");
}
this.session.shutdown();
}
public int getSocketTimeout() {
return this.session.getSocketTimeout();
}
public void setSocketTimeout(int timeout) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O session " + this.id + " " + this.session + ": Set timeout "
+ timeout);
}
this.session.setSocketTimeout(timeout);
}
public void setBufferStatus(final SessionBufferStatus status) {
this.session.setBufferStatus(status);
}
public boolean hasBufferedInput() {
return this.session.hasBufferedInput();
}
public boolean hasBufferedOutput() {
return this.session.hasBufferedOutput();
}
public Object getAttribute(final String name) {
return this.session.getAttribute(name);
}
public void setAttribute(final String name, final Object obj) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O session " + this.id + " " + this.session + ": Set attribute "
+ name);
}
this.session.setAttribute(name, obj);
}
public Object removeAttribute(final String name) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O session " + this.id + " " + this.session + ": Remove attribute "
+ name);
}
return this.session.removeAttribute(name);
}
class LoggingByteChannel implements ByteChannel {
public int read(final ByteBuffer dst) throws IOException {
int bytesRead = session.channel().read(dst);
if (log.isDebugEnabled()) {
log.debug("I/O session " + id + " " + session + ": " + bytesRead + " bytes read");
}
if (bytesRead > 0 && wirelog.isEnabled()) {
ByteBuffer b = dst.duplicate();
int p = b.position();
b.limit(p);
b.position(p - bytesRead);
wirelog.input(b);
}
return bytesRead;
}
public int write(final ByteBuffer src) throws IOException {
int byteWritten = session.channel().write(src);
if (log.isDebugEnabled()) {
log.debug("I/O session " + id + " " + session + ": " + byteWritten + " bytes written");
}
if (byteWritten > 0 && wirelog.isEnabled()) {
ByteBuffer b = src.duplicate();
int p = b.position();
b.limit(p);
b.position(p - byteWritten);
wirelog.output(b);
}
return byteWritten;
}
public void close() throws IOException {
if (log.isDebugEnabled()) {
log.debug("I/O session " + id + " " + session + ": Channel close");
}
session.channel().close();
}
public boolean isOpen() {
return session.channel().isOpen();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/logging/LoggingIOSession.java
|
Java
|
gpl3
| 7,749
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.logging;
import java.nio.ByteBuffer;
import org.apache.commons.logging.Log;
class Wire {
private final Log log;
public Wire(final Log log) {
super();
this.log = log;
}
private void wire(final String header, final byte[] b, int pos, int off) {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < off; i++) {
int ch = b[pos + i];
if (ch == 13) {
buffer.append("[\\r]");
} else if (ch == 10) {
buffer.append("[\\n]\"");
buffer.insert(0, "\"");
buffer.insert(0, header);
this.log.debug(buffer.toString());
buffer.setLength(0);
} else if ((ch < 32) || (ch > 127)) {
buffer.append("[0x");
buffer.append(Integer.toHexString(ch));
buffer.append("]");
} else {
buffer.append((char) ch);
}
}
if (buffer.length() > 0) {
buffer.append('\"');
buffer.insert(0, '\"');
buffer.insert(0, header);
this.log.debug(buffer.toString());
}
}
public boolean isEnabled() {
return this.log.isDebugEnabled();
}
public void output(final byte[] b, int pos, int off) {
wire("<< ", b, pos, off);
}
public void input(final byte[] b, int pos, int off) {
wire(">> ", b, pos, off);
}
public void output(byte[] b) {
output(b, 0, b.length);
}
public void input(byte[] b) {
input(b, 0, b.length);
}
public void output(int b) {
output(new byte[] {(byte) b});
}
public void input(int b) {
input(new byte[] {(byte) b});
}
public void output(final ByteBuffer b) {
if (b.hasArray()) {
output(b.array(), b.arrayOffset() + b.position(), b.remaining());
} else {
byte[] tmp = new byte[b.remaining()];
b.get(tmp);
output(tmp);
}
}
public void input(final ByteBuffer b) {
if (b.hasArray()) {
input(b.array(), b.arrayOffset() + b.position(), b.remaining());
} else {
byte[] tmp = new byte[b.remaining()];
b.get(tmp);
input(tmp);
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/logging/Wire.java
|
Java
|
gpl3
| 3,579
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.logging;
import org.apache.http.impl.nio.DefaultServerIOEventDispatch;
import org.apache.http.nio.NHttpServerIOTarget;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.params.HttpParams;
public class LoggingServerIOEventDispatch extends DefaultServerIOEventDispatch {
public LoggingServerIOEventDispatch(
final NHttpServiceHandler handler,
final HttpParams params) {
super(new LoggingNHttpServiceHandler(handler), params);
}
@Override
protected NHttpServerIOTarget createConnection(final IOSession session) {
return new LoggingNHttpServerConnection(
new LoggingIOSession(session, "server"),
createHttpRequestFactory(),
this.allocator,
this.params);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/logging/LoggingServerIOEventDispatch.java
|
Java
|
gpl3
| 2,051
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.io.InputStream;
import java.io.InterruptedIOException;
/**
* Test class similar to {@link java.io.ByteArrayInputStream} that throws if encounters
* value zero '\000' in the source byte array.
*/
public class TimeoutByteArrayInputStream extends InputStream {
private final byte[] buf;
private int pos;
protected int count;
public TimeoutByteArrayInputStream(byte[] buf, int off, int len) {
super();
this.buf = buf;
this.pos = off;
this.count = Math.min(off + len, buf.length);
}
public TimeoutByteArrayInputStream(byte[] buf) {
this(buf, 0, buf.length);
}
public int read() throws IOException {
if (this.pos < this.count) {
return -1;
}
int v = this.buf[this.pos++] & 0xff;
if (v != 0) {
return v;
} else {
throw new InterruptedIOException("Timeout");
}
}
public int read(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (this.pos >= this.count) {
return -1;
}
if (this.pos + len > this.count) {
len = this.count - this.pos;
}
if (len <= 0) {
return 0;
}
if ((this.buf[this.pos] & 0xff) == 0) {
this.pos++;
throw new InterruptedIOException("Timeout");
}
for (int i = 0; i < len; i++) {
int v = this.buf[this.pos] & 0xff;
if (v == 0) {
return i;
} else {
b[off + i] = (byte) v;
this.pos++;
}
}
return len;
}
public long skip(long n) {
if (this.pos + n > this.count) {
n = this.count - this.pos;
}
if (n < 0) {
return 0;
}
this.pos += n;
return n;
}
public int available() {
return this.count - this.pos;
}
public boolean markSupported() {
return false;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/TimeoutByteArrayInputStream.java
|
Java
|
gpl3
| 3,566
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.ByteArrayOutputStream;
import java.io.OutputStream;
import org.apache.ogt.http.impl.io.AbstractSessionOutputBuffer;
import org.apache.ogt.http.params.BasicHttpParams;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link org.apache.ogt.http.io.SessionOutputBuffer} mockup implementation.
*
*/
public class SessionOutputBufferMockup extends AbstractSessionOutputBuffer {
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
public static final int BUFFER_SIZE = 16;
public SessionOutputBufferMockup(
final OutputStream outstream,
int buffersize,
final HttpParams params) {
super();
init(outstream, buffersize, params);
}
public SessionOutputBufferMockup(
final OutputStream outstream,
int buffersize) {
this(outstream, buffersize, new BasicHttpParams());
}
public SessionOutputBufferMockup(
final ByteArrayOutputStream buffer,
final HttpParams params) {
this(buffer, BUFFER_SIZE, params);
this.buffer = buffer;
}
public SessionOutputBufferMockup(
final ByteArrayOutputStream buffer) {
this(buffer, BUFFER_SIZE, new BasicHttpParams());
this.buffer = buffer;
}
public SessionOutputBufferMockup(final HttpParams params) {
this(new ByteArrayOutputStream(), params);
}
public SessionOutputBufferMockup() {
this(new ByteArrayOutputStream(), new BasicHttpParams());
}
public byte[] getData() {
if (this.buffer != null) {
return this.buffer.toByteArray();
} else {
return new byte[] {};
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/SessionOutputBufferMockup.java
|
Java
|
gpl3
| 2,935
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.DefaultedHttpParams;
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.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.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
public class HttpClient {
private final HttpParams params;
private final HttpProcessor httpproc;
private final HttpRequestExecutor httpexecutor;
private final ConnectionReuseStrategy connStrategy;
private final HttpContext context;
public HttpClient() {
super();
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1)
.setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1");
this.httpproc = new ImmutableHttpProcessor(
new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()
});
this.httpexecutor = new HttpRequestExecutor();
this.connStrategy = new DefaultConnectionReuseStrategy();
this.context = new BasicHttpContext();
}
public HttpParams getParams() {
return this.params;
}
public HttpResponse execute(
final HttpRequest request,
final HttpHost targetHost,
final HttpClientConnection conn) throws HttpException, IOException {
this.context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
request.setParams(new DefaultedHttpParams(request.getParams(), this.params));
this.httpexecutor.preProcess(request, this.httpproc, this.context);
HttpResponse response = this.httpexecutor.execute(request, conn, this.context);
response.setParams(new DefaultedHttpParams(response.getParams(), this.params));
this.httpexecutor.postProcess(response, this.httpproc, this.context);
return response;
}
public boolean keepAlive(final HttpResponse response) {
return this.connStrategy.keepAlive(response, this.context);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/HttpClient.java
|
Java
|
gpl3
| 4,836
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.io.InputStream;
import java.io.OutputStream;
import org.apache.ogt.http.entity.AbstractHttpEntity;
/**
* {@link AbstractHttpEntity} mockup implementation.
*
*/
public class HttpEntityMockup extends AbstractHttpEntity {
private boolean stream;
public InputStream getContent() throws IOException, IllegalStateException {
return null;
}
public long getContentLength() {
return 0;
}
public boolean isRepeatable() {
return false;
}
public void setStreaming(final boolean b) {
this.stream = b;
}
public boolean isStreaming() {
return this.stream;
}
public void writeTo(OutputStream outstream) throws IOException {
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/HttpEntityMockup.java
|
Java
|
gpl3
| 1,979
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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 void setSocketTimeout(int timeout) {
}
public int getSocketTimeout() {
return -1;
}
public boolean isOpen() {
return this.open;
}
public boolean isStale() {
return false;
}
public HttpConnectionMetrics getMetrics() {
return null;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/HttpConnectionMockup.java
|
Java
|
gpl3
| 2,041
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpException;
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.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;
public class HttpServer {
private final HttpParams params;
private final HttpProcessor httpproc;
private final ConnectionReuseStrategy connStrategy;
private final HttpResponseFactory responseFactory;
private final HttpRequestHandlerRegistry reqistry;
private final ServerSocket serversocket;
private HttpExpectationVerifier expectationVerifier;
private Thread listener;
private volatile boolean shutdown;
public HttpServer() throws IOException {
super();
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "TEST-SERVER/1.1");
this.httpproc = new ImmutableHttpProcessor(
new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
this.connStrategy = new DefaultConnectionReuseStrategy();
this.responseFactory = new DefaultHttpResponseFactory();
this.reqistry = new HttpRequestHandlerRegistry();
this.serversocket = new ServerSocket(0);
}
public void registerHandler(
final String pattern,
final HttpRequestHandler handler) {
this.reqistry.register(pattern, handler);
}
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.expectationVerifier = expectationVerifier;
}
private HttpServerConnection acceptConnection() throws IOException {
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(socket, this.params);
return conn;
}
public int getPort() {
return this.serversocket.getLocalPort();
}
public InetAddress getInetAddress() {
return this.serversocket.getInetAddress();
}
public void start() {
if (this.listener != null) {
throw new IllegalStateException("Listener already running");
}
this.listener = new Thread(new Runnable() {
public void run() {
while (!shutdown && !Thread.interrupted()) {
try {
// Set up HTTP connection
HttpServerConnection conn = acceptConnection();
// Set up the HTTP service
HttpService httpService = new HttpService(
httpproc,
connStrategy,
responseFactory,
reqistry,
expectationVerifier,
params);
// Start worker thread
Thread t = new WorkerThread(httpService, conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
break;
}
}
}
});
this.listener.start();
}
public void shutdown() {
if (this.shutdown) {
return;
}
this.shutdown = true;
try {
this.serversocket.close();
} catch (IOException ignore) {}
this.listener.interrupt();
try {
this.listener.join(1000);
} catch (InterruptedException ignore) {}
}
static class WorkerThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
public WorkerThread(
final HttpService httpservice,
final HttpServerConnection conn) {
super();
this.httpservice = httpservice;
this.conn = conn;
}
public void run() {
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (ConnectionClosedException ex) {
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {}
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/HttpServer.java
|
Java
|
gpl3
| 7,786
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/SessionInputBufferMockup.java
|
Java
|
gpl3
| 3,868
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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 org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.message.AbstractHttpMessage;
import org.apache.ogt.http.params.HttpProtocolParams;
/**
* {@link org.apache.ogt.http.HttpMessage} mockup implementation.
*
*/
public class HttpMessageMockup extends AbstractHttpMessage {
public HttpMessageMockup() {
super();
}
public ProtocolVersion getProtocolVersion() {
return HttpProtocolParams.getVersion(this.getParams());
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/HttpMessageMockup.java
|
Java
|
gpl3
| 1,697
|
@import url("../../../css/hc-maven.css");
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/site/resources/css/site.css
|
CSS
|
gpl3
| 41
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
import java.net.Socket;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.message.BasicHttpRequest;
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.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
import org.apache.ogt.http.util.EntityUtils;
/**
* Elemental example for executing a GET request.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*
*
*
*/
public class ElementalHttpGet {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
// Required protocol interceptors
new RequestContent(),
new RequestTargetHost(),
// Recommended protocol interceptors
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost("localhost", 8080);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
try {
String[] targets = {
"/",
"/servlets-examples/servlet/RequestInfoExample",
"/somewhere%20in%20pampa"};
for (int i = 0; i < targets.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/examples/org/apache/http/examples/ElementalHttpGet.java
|
Java
|
gpl3
| 5,530
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
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.DefaultHttpClientConnection;
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.ExecutionContext;
import org.apache.ogt.http.protocol.HTTP;
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.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.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
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;
/**
* Rudimentary HTTP/1.1 reverse proxy.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP reverse proxy.
*
*
*/
public class ElementalReverseProxy {
private static final String HTTP_IN_CONN = "http.proxy.in-conn";
private static final String HTTP_OUT_CONN = "http.proxy.out-conn";
private static final String HTTP_CONN_KEEPALIVE = "http.proxy.conn-keepalive";
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specified target hostname and port");
System.exit(1);
}
String hostname = args[0];
int port = 80;
if (args.length > 1) {
port = Integer.parseInt(args[1]);
}
HttpHost target = new HttpHost(hostname, port);
Thread t = new RequestListenerThread(8888, target);
t.setDaemon(false);
t.start();
}
static class ProxyHandler implements HttpRequestHandler {
private final HttpHost target;
private final HttpProcessor httpproc;
private final HttpRequestExecutor httpexecutor;
private final ConnectionReuseStrategy connStrategy;
public ProxyHandler(
final HttpHost target,
final HttpProcessor httpproc,
final HttpRequestExecutor httpexecutor) {
super();
this.target = target;
this.httpproc = httpproc;
this.httpexecutor = httpexecutor;
this.connStrategy = new DefaultConnectionReuseStrategy();
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpClientConnection conn = (HttpClientConnection) context.getAttribute(
HTTP_OUT_CONN);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.target);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
// Remove hop-by-hop headers
request.removeHeaders(HTTP.CONTENT_LEN);
request.removeHeaders(HTTP.TRANSFER_ENCODING);
request.removeHeaders(HTTP.CONN_DIRECTIVE);
request.removeHeaders("Keep-Alive");
request.removeHeaders("Proxy-Authenticate");
request.removeHeaders("TE");
request.removeHeaders("Trailers");
request.removeHeaders("Upgrade");
this.httpexecutor.preProcess(request, this.httpproc, context);
HttpResponse targetResponse = this.httpexecutor.execute(request, conn, context);
this.httpexecutor.postProcess(response, this.httpproc, context);
// Remove hop-by-hop headers
targetResponse.removeHeaders(HTTP.CONTENT_LEN);
targetResponse.removeHeaders(HTTP.TRANSFER_ENCODING);
targetResponse.removeHeaders(HTTP.CONN_DIRECTIVE);
targetResponse.removeHeaders("Keep-Alive");
targetResponse.removeHeaders("TE");
targetResponse.removeHeaders("Trailers");
targetResponse.removeHeaders("Upgrade");
response.setStatusLine(targetResponse.getStatusLine());
response.setHeaders(targetResponse.getAllHeaders());
response.setEntity(targetResponse.getEntity());
System.out.println("<< Response: " + response.getStatusLine());
boolean keepalive = this.connStrategy.keepAlive(response, context);
context.setAttribute(HTTP_CONN_KEEPALIVE, new Boolean(keepalive));
}
}
static class RequestListenerThread extends Thread {
private final HttpHost target;
private final ServerSocket serversocket;
private final HttpParams params;
private final HttpService httpService;
public RequestListenerThread(int port, final HttpHost target) throws IOException {
this.target = target;
this.serversocket = new ServerSocket(port);
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up HTTP protocol processor for incoming connections
HttpProcessor inhttpproc = new ImmutableHttpProcessor(
new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()
});
// Set up HTTP protocol processor for outgoing connections
HttpProcessor outhttpproc = new ImmutableHttpProcessor(
new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
// Set up outgoing request executor
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
// Set up incoming request handler
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new ProxyHandler(
this.target,
outhttpproc,
httpexecutor));
// Set up the HTTP service
this.httpService = new HttpService(
inhttpproc,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory(),
reqistry,
this.params);
}
public void run() {
System.out.println("Listening on port " + this.serversocket.getLocalPort());
while (!Thread.interrupted()) {
try {
// Set up incoming HTTP connection
Socket insocket = this.serversocket.accept();
DefaultHttpServerConnection inconn = new DefaultHttpServerConnection();
System.out.println("Incoming connection from " + insocket.getInetAddress());
inconn.bind(insocket, this.params);
// Set up outgoing HTTP connection
Socket outsocket = new Socket(this.target.getHostName(), this.target.getPort());
DefaultHttpClientConnection outconn = new DefaultHttpClientConnection();
outconn.bind(outsocket, this.params);
System.out.println("Outgoing connection to " + outsocket.getInetAddress());
// Start worker thread
Thread t = new ProxyThread(this.httpService, inconn, outconn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
System.err.println("I/O error initialising connection thread: "
+ e.getMessage());
break;
}
}
}
}
static class ProxyThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection inconn;
private final HttpClientConnection outconn;
public ProxyThread(
final HttpService httpservice,
final HttpServerConnection inconn,
final HttpClientConnection outconn) {
super();
this.httpservice = httpservice;
this.inconn = inconn;
this.outconn = outconn;
}
public void run() {
System.out.println("New connection thread");
HttpContext context = new BasicHttpContext(null);
// Bind connection objects to the execution context
context.setAttribute(HTTP_IN_CONN, this.inconn);
context.setAttribute(HTTP_OUT_CONN, this.outconn);
try {
while (!Thread.interrupted()) {
if (!this.inconn.isOpen()) {
this.outconn.close();
break;
}
this.httpservice.handleRequest(this.inconn, context);
Boolean keepalive = (Boolean) context.getAttribute(HTTP_CONN_KEEPALIVE);
if (!Boolean.TRUE.equals(keepalive)) {
this.outconn.close();
this.inconn.close();
break;
}
}
} catch (ConnectionClosedException ex) {
System.err.println("Client closed connection");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.inconn.shutdown();
} catch (IOException ignore) {}
try {
this.outconn.shutdown();
} catch (IOException ignore) {}
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/examples/org/apache/http/examples/ElementalReverseProxy.java
|
Java
|
gpl3
| 13,513
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
import org.apache.ogt.http.util.VersionInfo;
/**
* Prints version information for debugging purposes.
* This can be used to verify that the correct versions of the
* HttpComponent JARs are picked up from the classpath.
*
*
*/
public class PrintVersionInfo {
/** A default list of module packages. */
private final static String[] MODULE_LIST = {
"org.apache.ogt.http", // HttpCore
"org.apache.ogt.http.nio", // HttpCore NIO
"org.apache.ogt.http.client", // HttpClient
};
/**
* Prints version information.
*
* @param args command line arguments. Leave empty to print version
* information for the default packages. Otherwise, pass
* a list of packages for which to get version info.
*/
public static void main(String args[]) {
String[] pckgs = (args.length > 0) ? args : MODULE_LIST;
VersionInfo[] via = VersionInfo.loadVersionInfo(pckgs, null);
System.out.println("version info for thread context classloader:");
for (int i=0; i<via.length; i++)
System.out.println(via[i]);
System.out.println();
// if the version information for the classloader of this class
// is different from that for the thread context classloader,
// there may be a problem with multiple versions in the classpath
via = VersionInfo.loadVersionInfo
(pckgs, PrintVersionInfo.class.getClassLoader());
System.out.println("version info for static classloader:");
for (int i=0; i<via.length; i++)
System.out.println(via[i]);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/examples/org/apache/http/examples/PrintVersionInfo.java
|
Java
|
gpl3
| 2,907
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.Locale;
import org.apache.ogt.http.ConnectionClosedException;
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.HttpResponseInterceptor;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.MethodNotSupportedException;
import org.apache.ogt.http.entity.ContentProducer;
import org.apache.ogt.http.entity.EntityTemplate;
import org.apache.ogt.http.entity.FileEntity;
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.HttpParams;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
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;
import org.apache.ogt.http.util.EntityUtils;
/**
* Basic, yet fully functional and spec compliant, HTTP/1.1 file server.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP file server.
*
*
*/
public class ElementalHttpServer {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
Thread t = new RequestListenerThread(8080, args[0]);
t.setDaemon(false);
t.start();
}
static class HttpFileHandler implements HttpRequestHandler {
private final String docRoot;
public HttpFileHandler(final String docRoot) {
super();
this.docRoot = docRoot;
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + " method not supported");
}
String target = request.getRequestLine().getUri();
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
byte[] entityContent = EntityUtils.toByteArray(entity);
System.out.println("Incoming entity content (bytes): " + entityContent.length);
}
final File file = new File(this.docRoot, URLDecoder.decode(target));
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("File ");
writer.write(file.getPath());
writer.write(" not found");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("File " + file.getPath() + " not found");
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("Access denied");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("Cannot read file " + file.getPath());
} else {
response.setStatusCode(HttpStatus.SC_OK);
FileEntity body = new FileEntity(file, "text/html");
response.setEntity(body);
System.out.println("Serving file " + file.getPath());
}
}
}
static class RequestListenerThread extends Thread {
private final ServerSocket serversocket;
private final HttpParams params;
private final HttpService httpService;
public RequestListenerThread(int port, final String docroot) throws IOException {
this.serversocket = new ServerSocket(port);
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
// Set up request handlers
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new HttpFileHandler(docroot));
// Set up the HTTP service
this.httpService = new HttpService(
httpproc,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory(),
reqistry,
this.params);
}
public void run() {
System.out.println("Listening on port " + this.serversocket.getLocalPort());
while (!Thread.interrupted()) {
try {
// Set up HTTP connection
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
System.out.println("Incoming connection from " + socket.getInetAddress());
conn.bind(socket, this.params);
// Start worker thread
Thread t = new WorkerThread(this.httpService, conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
System.err.println("I/O error initialising connection thread: "
+ e.getMessage());
break;
}
}
}
}
static class WorkerThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
public WorkerThread(
final HttpService httpservice,
final HttpServerConnection conn) {
super();
this.httpservice = httpservice;
this.conn = conn;
}
public void run() {
System.out.println("New connection thread");
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (ConnectionClosedException ex) {
System.err.println("Client closed connection");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {}
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/examples/org/apache/http/examples/ElementalHttpServer.java
|
Java
|
gpl3
| 11,231
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
import java.io.ByteArrayInputStream;
import java.net.Socket;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.entity.ByteArrayEntity;
import org.apache.ogt.http.entity.InputStreamEntity;
import org.apache.ogt.http.entity.StringEntity;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.message.BasicHttpEntityEnclosingRequest;
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.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
import org.apache.ogt.http.util.EntityUtils;
/**
* Elemental example for executing a POST request.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*
*
*
*/
public class ElementalHttpPost {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
// Required protocol interceptors
new RequestContent(),
new RequestTargetHost(),
// Recommended protocol interceptors
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost("localhost", 8080);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
try {
HttpEntity[] requestBodies = {
new StringEntity(
"This is the first test request", "UTF-8"),
new ByteArrayEntity(
"This is the second test request".getBytes("UTF-8")),
new InputStreamEntity(
new ByteArrayInputStream(
"This is the third test request (will be chunked)"
.getBytes("UTF-8")), -1)
};
for (int i = 0; i < requestBodies.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
"/servlets-examples/servlet/RequestInfoExample");
request.setEntity(requestBodies[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/examples/org/apache/http/examples/ElementalHttpPost.java
|
Java
|
gpl3
| 6,296
|