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.nio.protocol;
import java.io.IOException;
import java.util.Queue;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.nio.entity.BufferingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
abstract class RequestExecutionHandler
implements NHttpRequestExecutionHandler, HttpRequestExecutionHandler {
public void initalizeContext(final HttpContext context, final Object attachment) {
context.setAttribute("queue", attachment);
}
protected abstract HttpRequest generateRequest(Job testjob);
public HttpRequest submitRequest(final HttpContext context) {
@SuppressWarnings("unchecked")
Queue<Job> queue = (Queue<Job>) context.getAttribute("queue");
if (queue == null) {
throw new IllegalStateException("Queue is null");
}
Job testjob = queue.poll();
context.setAttribute("job", testjob);
if (testjob != null) {
return generateRequest(testjob);
} else {
return null;
}
}
public ConsumingNHttpEntity responseEntity(
final HttpResponse response,
final HttpContext context) throws IOException {
return new BufferingNHttpEntity(response.getEntity(),
new HeapByteBufferAllocator());
}
public void handleResponse(final HttpResponse response, final HttpContext context) {
Job testjob = (Job) context.removeAttribute("job");
if (testjob == null) {
throw new IllegalStateException("TestJob is null");
}
int statusCode = response.getStatusLine().getStatusCode();
String content = null;
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
content = EntityUtils.toString(entity);
} catch (IOException ex) {
content = "I/O exception: " + ex.getMessage();
}
}
testjob.setResult(statusCode, content);
}
public void finalizeContext(final HttpContext context) {
Job testjob = (Job) context.removeAttribute("job");
if (testjob != null) {
testjob.fail("Request failed");
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/nio/protocol/RequestExecutionHandler.java | Java | gpl3 | 3,634 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.nio.entity.BufferingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
final class RequestHandler extends SimpleNHttpRequestHandler implements HttpRequestHandler {
private final boolean chunking;
RequestHandler() {
this(false);
}
RequestHandler(boolean chunking) {
super();
this.chunking = chunking;
}
public ConsumingNHttpEntity entityRequest(
final HttpEntityEnclosingRequest request,
final HttpContext context) {
return new BufferingNHttpEntity(
request.getEntity(),
new HeapByteBufferAllocator());
}
@Override
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String content = null;
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
if (entity != null) {
content = EntityUtils.toString(entity);
} else {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
content = "Request entity not avaialble";
}
} else {
String s = request.getRequestLine().getUri();
int idx = s.indexOf('x');
if (idx == -1) {
throw new HttpException("Unexpected request-URI format");
}
String pattern = s.substring(0, idx);
int count = Integer.parseInt(s.substring(idx + 1, s.length()));
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < count; i++) {
buffer.append(pattern);
}
content = buffer.toString();
}
NStringEntity entity = new NStringEntity(content, "US-ASCII");
entity.setChunked(this.chunking);
response.setEntity(entity);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/nio/protocol/RequestHandler.java | Java | gpl3 | 3,738 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.util.Random;
public class Job {
private static final Random RND = new Random();
private static final String TEST_CHARS = "0123456789ABCDEF";
private final int count;
private final String pattern;
private volatile boolean completed;
private volatile int statusCode;
private volatile String result;
private volatile String failureMessage;
private volatile Exception ex;
public Job(int maxCount) {
super();
this.count = RND.nextInt(maxCount - 1) + 1;
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < 5; i++) {
char rndchar = TEST_CHARS.charAt(RND.nextInt(TEST_CHARS.length() - 1));
buffer.append(rndchar);
}
this.pattern = buffer.toString();
}
public Job() {
this(1000);
}
public Job(final String pattern, int count) {
super();
this.count = count;
this.pattern = pattern;
}
public int getCount() {
return this.count;
}
public String getPattern() {
return this.pattern;
}
public String getExpected() {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < this.count; i++) {
buffer.append(this.pattern);
}
return buffer.toString();
}
public int getStatusCode() {
return this.statusCode;
}
public String getResult() {
return this.result;
}
public boolean isSuccessful() {
return this.result != null;
}
public String getFailureMessage() {
return this.failureMessage;
}
public Exception getException() {
return this.ex;
}
public boolean isCompleted() {
return this.completed;
}
public synchronized void setResult(int statusCode, final String result) {
if (this.completed) {
return;
}
this.completed = true;
this.statusCode = statusCode;
this.result = result;
notifyAll();
}
public synchronized void fail(final String message, final Exception ex) {
if (this.completed) {
return;
}
this.completed = true;
this.result = null;
this.failureMessage = message;
this.ex = ex;
notifyAll();
}
public void fail(final String message) {
fail(message, null);
}
public synchronized void waitFor() throws InterruptedException {
while (!this.completed) {
wait();
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/nio/protocol/Job.java | Java | gpl3 | 3,767 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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;
public class OoopsieRuntimeException extends RuntimeException {
private static final long serialVersionUID = 662807254163212266L;
public OoopsieRuntimeException() {
super("Ooopsie!!!");
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/OoopsieRuntimeException.java | Java | gpl3 | 1,424 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.http.mockup.HttpSSLClient;
import org.apache.http.mockup.HttpSSLServer;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
/**
* Base class for all HttpCore NIO tests
*/
public class HttpCoreNIOSSLTestBase extends TestCase {
public HttpCoreNIOSSLTestBase(String testName) {
super(testName);
}
protected HttpSSLServer server;
protected HttpSSLClient client;
@Override
protected void setUp() throws Exception {
HttpParams serverParams = new SyncBasicHttpParams();
serverParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000)
.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.server = new HttpSSLServer(serverParams);
this.server.setExceptionHandler(new SimpleIOReactorExceptionHandler());
HttpParams clientParams = new SyncBasicHttpParams();
clientParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000)
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 120000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1");
this.client = new HttpSSLClient(clientParams);
this.client.setExceptionHandler(new SimpleIOReactorExceptionHandler());
}
@Override
protected void tearDown() {
try {
this.client.shutdown();
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
try {
this.server.shutdown();
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/HttpCoreNIOSSLTestBase.java | Java | gpl3 | 3,511 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.mockup;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.protocol.EventListener;
public class SimpleEventListener implements EventListener {
public SimpleEventListener() {
super();
}
public void connectionOpen(final NHttpConnection conn) {
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out");
}
public void connectionClosed(final NHttpConnection conn) {
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
ex.printStackTrace(System.out);
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
ex.printStackTrace(System.out);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/SimpleEventListener.java | Java | gpl3 | 2,036 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.ExceptionEvent;
import org.apache.http.impl.nio.ssl.SSLClientIOEventDispatch;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.params.HttpParams;
public class HttpSSLClient {
private final SSLContext sslcontext;
private final DefaultConnectingIOReactor ioReactor;
private final HttpParams params;
private volatile IOReactorThread thread;
public HttpSSLClient(final HttpParams params) throws Exception {
super();
this.params = params;
this.sslcontext = createSSLContext();
this.ioReactor = new DefaultConnectingIOReactor(2, this.params);
}
private TrustManagerFactory createTrustManagerFactory() throws NoSuchAlgorithmException {
String algo = TrustManagerFactory.getDefaultAlgorithm();
try {
return TrustManagerFactory.getInstance(algo);
} catch (NoSuchAlgorithmException ex) {
return TrustManagerFactory.getInstance("SunX509");
}
}
protected SSLContext createSSLContext() throws Exception {
ClassLoader cl = getClass().getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(url.openStream(), "nopassword".toCharArray());
TrustManagerFactory tmfactory = createTrustManagerFactory();
tmfactory.init(keystore);
TrustManager[] trustmanagers = tmfactory.getTrustManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, trustmanagers, null);
return sslcontext;
}
public HttpParams getParams() {
return this.params;
}
public IOReactorStatus getStatus() {
return this.ioReactor.getStatus();
}
public List<ExceptionEvent> getAuditLog() {
return this.ioReactor.getAuditLog();
}
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.ioReactor.setExceptionHandler(exceptionHandler);
}
protected IOEventDispatch createIOEventDispatch(
final NHttpClientHandler clientHandler,
final SSLContext sslcontext,
final HttpParams params) {
return new SSLClientIOEventDispatch(clientHandler, sslcontext, params);
}
private void execute(final NHttpClientHandler clientHandler) throws IOException {
IOEventDispatch ioEventDispatch = createIOEventDispatch(
clientHandler,
this.sslcontext,
this.params);
this.ioReactor.execute(ioEventDispatch);
}
public SessionRequest openConnection(final InetSocketAddress address, final Object attachment) {
return this.ioReactor.connect(address, null, attachment, null);
}
public void start(final NHttpClientHandler clientHandler) {
this.thread = new IOReactorThread(clientHandler);
this.thread.start();
}
public void join(long timeout) throws InterruptedException {
if (this.thread != null) {
this.thread.join(timeout);
}
}
public Exception getException() {
if (this.thread != null) {
return this.thread.getException();
} else {
return null;
}
}
public void shutdown() throws IOException {
this.ioReactor.shutdown();
try {
if (this.thread != null) {
this.thread.join(500);
}
} catch (InterruptedException ignore) {
}
}
private class IOReactorThread extends Thread {
private final NHttpClientHandler clientHandler;
private volatile Exception ex;
public IOReactorThread(final NHttpClientHandler clientHandler) {
super();
this.clientHandler = clientHandler;
}
@Override
public void run() {
try {
execute(this.clientHandler);
} catch (Exception ex) {
this.ex = ex;
}
}
public Exception getException() {
return this.ex;
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/HttpSSLClient.java | Java | gpl3 | 5,949 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
import org.apache.http.impl.nio.DefaultServerIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.impl.nio.reactor.ExceptionEvent;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.ListenerEndpoint;
import org.apache.http.params.HttpParams;
/**
* Trivial test server based on HttpCore NIO
*
*/
public class HttpServerNio {
private final DefaultListeningIOReactor ioReactor;
private final HttpParams params;
private volatile IOReactorThread thread;
private ListenerEndpoint endpoint;
public HttpServerNio(final HttpParams params) throws IOException {
super();
this.ioReactor = new DefaultListeningIOReactor(2, params);
this.params = params;
}
public HttpParams getParams() {
return this.params;
}
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.ioReactor.setExceptionHandler(exceptionHandler);
}
protected IOEventDispatch createIOEventDispatch(
final NHttpServiceHandler serviceHandler, final HttpParams params) {
return new DefaultServerIOEventDispatch(serviceHandler, params);
}
private void execute(final NHttpServiceHandler serviceHandler) throws IOException {
IOEventDispatch ioEventDispatch = createIOEventDispatch(
serviceHandler,
this.params);
this.ioReactor.execute(ioEventDispatch);
}
public ListenerEndpoint getListenerEndpoint() {
return this.endpoint;
}
public void setEndpoint(ListenerEndpoint endpoint) {
this.endpoint = endpoint;
}
public void start(final NHttpServiceHandler serviceHandler) {
this.endpoint = this.ioReactor.listen(new InetSocketAddress(0));
this.thread = new IOReactorThread(serviceHandler);
this.thread.start();
}
public IOReactorStatus getStatus() {
return this.ioReactor.getStatus();
}
public List<ExceptionEvent> getAuditLog() {
return this.ioReactor.getAuditLog();
}
public void join(long timeout) throws InterruptedException {
if (this.thread != null) {
this.thread.join(timeout);
}
}
public Exception getException() {
if (this.thread != null) {
return this.thread.getException();
} else {
return null;
}
}
public void shutdown() throws IOException {
this.ioReactor.shutdown();
try {
join(500);
} catch (InterruptedException ignore) {
}
}
private class IOReactorThread extends Thread {
private final NHttpServiceHandler serviceHandler;
private volatile Exception ex;
public IOReactorThread(final NHttpServiceHandler serviceHandler) {
super();
this.serviceHandler = serviceHandler;
}
@Override
public void run() {
try {
execute(this.serviceHandler);
} catch (Exception ex) {
this.ex = ex;
}
}
public Exception getException() {
return this.ex;
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/HttpServerNio.java | Java | gpl3 | 4,702 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
import org.apache.http.impl.nio.DefaultClientIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.ExceptionEvent;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.params.HttpParams;
public class HttpClientNio {
private final DefaultConnectingIOReactor ioReactor;
private final HttpParams params;
private volatile IOReactorThread thread;
public HttpClientNio(final HttpParams params) throws IOException {
super();
this.ioReactor = new DefaultConnectingIOReactor(2, params);
this.params = params;
}
public HttpParams getParams() {
return this.params;
}
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.ioReactor.setExceptionHandler(exceptionHandler);
}
protected IOEventDispatch createIOEventDispatch(
final NHttpClientHandler clientHandler, final HttpParams params) {
return new DefaultClientIOEventDispatch(clientHandler, params);
}
private void execute(final NHttpClientHandler clientHandler) throws IOException {
IOEventDispatch ioEventDispatch = createIOEventDispatch(
clientHandler,
this.params);
this.ioReactor.execute(ioEventDispatch);
}
public SessionRequest openConnection(final InetSocketAddress address, final Object attachment) {
return this.ioReactor.connect(address, null, attachment, null);
}
public void start(final NHttpClientHandler clientHandler) {
this.thread = new IOReactorThread(clientHandler);
this.thread.start();
}
public IOReactorStatus getStatus() {
return this.ioReactor.getStatus();
}
public List<ExceptionEvent> getAuditLog() {
return this.ioReactor.getAuditLog();
}
public void join(long timeout) throws InterruptedException {
if (this.thread != null) {
this.thread.join(timeout);
}
}
public Exception getException() {
if (this.thread != null) {
return this.thread.getException();
} else {
return null;
}
}
public void shutdown() throws IOException {
this.ioReactor.shutdown();
try {
join(500);
} catch (InterruptedException ignore) {
}
}
private class IOReactorThread extends Thread {
private final NHttpClientHandler clientHandler;
private volatile Exception ex;
public IOReactorThread(final NHttpClientHandler clientHandler) {
super();
this.clientHandler = clientHandler;
}
@Override
public void run() {
try {
execute(this.clientHandler);
} catch (Exception ex) {
this.ex = ex;
}
}
public Exception getException() {
return this.ex;
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/HttpClientNio.java | Java | gpl3 | 4,511 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.impl.nio.reactor.ExceptionEvent;
import org.apache.http.impl.nio.ssl.SSLServerIOEventDispatch;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.ListenerEndpoint;
import org.apache.http.params.HttpParams;
/**
* Trivial test server based on HttpCore NIO SSL
*
*/
public class HttpSSLServer {
private final SSLContext sslcontext;
private final DefaultListeningIOReactor ioReactor;
private final HttpParams params;
private volatile IOReactorThread thread;
private ListenerEndpoint endpoint;
public HttpSSLServer(final HttpParams params) throws Exception {
super();
this.params = params;
this.sslcontext = createSSLContext();
this.ioReactor = new DefaultListeningIOReactor(2, this.params);
}
private KeyManagerFactory createKeyManagerFactory() throws NoSuchAlgorithmException {
String algo = KeyManagerFactory.getDefaultAlgorithm();
try {
return KeyManagerFactory.getInstance(algo);
} catch (NoSuchAlgorithmException ex) {
return KeyManagerFactory.getInstance("SunX509");
}
}
protected SSLContext createSSLContext() throws Exception {
ClassLoader cl = getClass().getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(url.openStream(), "nopassword".toCharArray());
KeyManagerFactory kmfactory = createKeyManagerFactory();
kmfactory.init(keystore, "nopassword".toCharArray());
KeyManager[] keymanagers = kmfactory.getKeyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(keymanagers, null, null);
return sslcontext;
}
public HttpParams getParams() {
return this.params;
}
public IOReactorStatus getStatus() {
return this.ioReactor.getStatus();
}
public List<ExceptionEvent> getAuditLog() {
return this.ioReactor.getAuditLog();
}
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.ioReactor.setExceptionHandler(exceptionHandler);
}
protected IOEventDispatch createIOEventDispatch(
final NHttpServiceHandler serviceHandler,
final SSLContext sslcontext,
final HttpParams params) {
return new SSLServerIOEventDispatch(serviceHandler, sslcontext, params);
}
private void execute(final NHttpServiceHandler serviceHandler) throws IOException {
IOEventDispatch ioEventDispatch = createIOEventDispatch(
serviceHandler,
this.sslcontext,
this.params);
this.ioReactor.execute(ioEventDispatch);
}
public ListenerEndpoint getListenerEndpoint() {
return this.endpoint;
}
public void start(final NHttpServiceHandler serviceHandler) {
this.endpoint = this.ioReactor.listen(new InetSocketAddress(0));
this.thread = new IOReactorThread(serviceHandler);
this.thread.start();
}
public void join(long timeout) throws InterruptedException {
if (this.thread != null) {
this.thread.join(timeout);
}
}
public Exception getException() {
if (this.thread != null) {
return this.thread.getException();
} else {
return null;
}
}
public void shutdown() throws IOException {
this.ioReactor.shutdown();
try {
if (this.thread != null) {
this.thread.join(500);
}
} catch (InterruptedException ignore) {
}
}
private class IOReactorThread extends Thread {
private final NHttpServiceHandler serviceHandler;
private volatile Exception ex;
public IOReactorThread(final NHttpServiceHandler serviceHandler) {
super();
this.serviceHandler = serviceHandler;
}
@Override
public void run() {
try {
execute(this.serviceHandler);
} catch (Exception ex) {
this.ex = ex;
}
}
public Exception getException() {
return this.ex;
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/HttpSSLServer.java | Java | gpl3 | 6,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.mockup;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.impl.nio.codecs.AbstractContentEncoder;
import org.apache.http.nio.reactor.SessionOutputBuffer;
public class MockupEncoder extends AbstractContentEncoder {
// TODO? remove this field and the complete() and isCompleted() methods
private boolean completed;
public MockupEncoder(
final WritableByteChannel channel,
final SessionOutputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super(channel, buffer, metrics);
}
@Override
public boolean isCompleted() {
return this.completed;
}
@Override
public void complete() throws IOException {
this.completed = true;
}
public int write(final ByteBuffer src) throws IOException {
if (src == null) {
return 0;
}
if (this.completed) {
throw new IllegalStateException("Decoding process already completed");
}
return this.channel.write(src);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/MockupEncoder.java | Java | gpl3 | 2,370 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.mockup;
import org.apache.http.nio.protocol.NHttpRequestHandler;
import org.apache.http.nio.protocol.NHttpRequestHandlerResolver;
public class SimpleNHttpRequestHandlerResolver implements NHttpRequestHandlerResolver {
private final NHttpRequestHandler handler;
public SimpleNHttpRequestHandlerResolver(final NHttpRequestHandler handler) {
this.handler = handler;
}
public NHttpRequestHandler lookup(final String requestURI) {
return this.handler;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/SimpleNHttpRequestHandlerResolver.java | Java | gpl3 | 1,701 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.mockup;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.util.EncodingUtils;
public class ReadableByteChannelMockup implements ReadableByteChannel {
private final String[] chunks;
private final String charset;
private int chunkCount = 0;
private ByteBuffer currentChunk;
private boolean closed = false;
public ReadableByteChannelMockup(final String[] chunks, final String charset) {
super();
this.chunks = chunks;
this.charset = charset;
}
private void prepareChunk() {
if (this.currentChunk == null || !this.currentChunk.hasRemaining()) {
if (this.chunkCount < this.chunks.length) {
String s = this.chunks[this.chunkCount];
this.chunkCount++;
this.currentChunk = ByteBuffer.wrap(EncodingUtils.getBytes(s, this.charset));
} else {
this.closed = true;
}
}
}
public int read(final ByteBuffer dst) throws IOException {
prepareChunk();
if (this.closed) {
return -1;
}
int i = 0;
while (dst.hasRemaining() && this.currentChunk.hasRemaining()) {
dst.put(this.currentChunk.get());
i++;
}
return i;
}
public void close() throws IOException {
this.closed = true;
}
public boolean isOpen() {
return !this.closed;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/ReadableByteChannelMockup.java | Java | gpl3 | 2,713 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.mockup;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.nio.ContentDecoder;
public class MockupDecoder implements ContentDecoder {
private final ReadableByteChannel channel;
private boolean completed;
public MockupDecoder(final ReadableByteChannel channel) {
super();
this.channel = channel;
}
public int read(final ByteBuffer dst) throws IOException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.completed) {
return -1;
}
int bytesRead = this.channel.read(dst);
if (bytesRead == -1) {
this.completed = true;
}
return bytesRead;
}
public boolean isCompleted() {
return this.completed;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/MockupDecoder.java | Java | gpl3 | 2,092 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.mockup;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerResolver;
public class SimpleHttpRequestHandlerResolver implements HttpRequestHandlerResolver {
private final HttpRequestHandler handler;
public SimpleHttpRequestHandlerResolver(final HttpRequestHandler handler) {
super();
this.handler = handler;
}
public HttpRequestHandler lookup(final String requestURI) {
return this.handler;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/SimpleHttpRequestHandlerResolver.java | Java | gpl3 | 1,702 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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;
import java.io.IOException;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
class SimpleIOReactorExceptionHandler implements IOReactorExceptionHandler {
public boolean handle(final RuntimeException ex) {
if (!(ex instanceof OoopsieRuntimeException)) {
ex.printStackTrace(System.out);
}
return false;
}
public boolean handle(final IOException ex) {
ex.printStackTrace(System.out);
return false;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/SimpleIOReactorExceptionHandler.java | Java | gpl3 | 1,695 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.http.mockup.HttpClientNio;
import org.apache.http.mockup.HttpServerNio;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
/**
* Base class for all HttpCore NIO tests
*
*/
public class HttpCoreNIOTestBase extends TestCase {
public HttpCoreNIOTestBase(String testName) {
super(testName);
}
protected HttpServerNio server;
protected HttpClientNio client;
@Override
protected void setUp() throws Exception {
HttpParams serverParams = new SyncBasicHttpParams();
serverParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "TEST-SERVER/1.1");
this.server = new HttpServerNio(serverParams);
this.server.setExceptionHandler(new SimpleIOReactorExceptionHandler());
HttpParams clientParams = new SyncBasicHttpParams();
clientParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000)
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1");
this.client = new HttpClientNio(clientParams);
this.client.setExceptionHandler(new SimpleIOReactorExceptionHandler());
}
@Override
protected void tearDown() {
try {
this.client.shutdown();
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
try {
this.server.shutdown();
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/HttpCoreNIOTestBase.java | Java | gpl3 | 3,505 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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()
;
}
| zzhhhhh-android-gps | 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.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();
}
}
| zzhhhhh-android-gps | 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 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
}
| zzhhhhh-android-gps | 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.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);
}
}
| zzhhhhh-android-gps | 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;
/**
* 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)
;
}
| zzhhhhh-android-gps | 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;
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;
}
}
| zzhhhhh-android-gps | 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;
/**
* 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;
}
| zzhhhhh-android-gps | 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.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);
}
}
| zzhhhhh-android-gps | 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.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);
}
}
| zzhhhhh-android-gps | 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 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
}
| zzhhhhh-android-gps | 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.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);
}
}
| zzhhhhh-android-gps | 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.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;
}
}
} | zzhhhhh-android-gps | 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 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);
}
} | zzhhhhh-android-gps | 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 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);
}
} | zzhhhhh-android-gps | 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 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;
}
}
} | zzhhhhh-android-gps | 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 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);
}
}
| zzhhhhh-android-gps | 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.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();
}
}
} | zzhhhhh-android-gps | 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);
}
}
}
| zzhhhhh-android-gps | 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.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
| zzhhhhh-android-gps | 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 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
| zzhhhhh-android-gps | 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 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;
}
}
}
}
}
}
| zzhhhhh-android-gps | 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 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;
}
}
}
}
}
}
| zzhhhhh-android-gps | 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.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);
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-contrib/src/main/java/org/apache/http/contrib/compress/RequestAcceptEncoding.java | Java | gpl3 | 1,985 |
@import url("../../css/hc-maven.css");
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/src/site/resources/css/site.css | CSS | gpl3 | 39 |
<?xml version="1.0" encoding="utf-8"?>
<!--
====================================================================
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
====================================================================
This software consists of voluntary contributions made by many
individuals on behalf of the Apache Software Foundation. For more
information on the Apache Software Foundation, please see
<http://www.apache.org />.
====================================================================
Based on XSL FO (PDF) stylesheet for the Spring reference
documentation.
Thanks are due to Christian Bauer of the Hibernate project
team for writing the original stylesheet upon which this one
is based.
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
version="1.0">
<xsl:import href="urn:docbkx:stylesheet"/>
<!-- Prevent blank pages in output -->
<xsl:template name="book.titlepage.before.verso">
</xsl:template>
<xsl:template name="book.titlepage.verso">
</xsl:template>
<xsl:template name="book.titlepage.separator">
</xsl:template>
<!--###################################################
Header
################################################### -->
<!-- More space in the center header for long text -->
<xsl:attribute-set name="header.content.properties">
<xsl:attribute name="font-family">
<xsl:value-of select="$body.font.family"/>
</xsl:attribute>
<xsl:attribute name="margin-left">-5em</xsl:attribute>
<xsl:attribute name="margin-right">-5em</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
Custom Footer
################################################### -->
<xsl:template name="footer.content">
<xsl:param name="pageclass" select="''"/>
<xsl:param name="sequence" select="''"/>
<xsl:param name="position" select="''"/>
<xsl:param name="gentext-key" select="''"/>
<xsl:variable name="Version">
<xsl:if test="//releaseinfo">
<xsl:text>HttpCore (</xsl:text>
<xsl:value-of select="//releaseinfo"/>
<xsl:text>)</xsl:text>
</xsl:if>
</xsl:variable>
<xsl:choose>
<xsl:when test="$sequence='blank'">
<xsl:if test="$position = 'center'">
<xsl:value-of select="$Version"/>
</xsl:if>
</xsl:when>
<!-- for double sided printing, print page numbers on alternating sides (of the page) -->
<xsl:when test="$double.sided != 0">
<xsl:choose>
<xsl:when test="$sequence = 'even' and $position='left'">
<fo:page-number/>
</xsl:when>
<xsl:when test="$sequence = 'odd' and $position='right'">
<fo:page-number/>
</xsl:when>
<xsl:when test="$position='center'">
<xsl:value-of select="$Version"/>
</xsl:when>
</xsl:choose>
</xsl:when>
<!-- for single sided printing, print all page numbers on the right (of the page) -->
<xsl:when test="$double.sided = 0">
<xsl:choose>
<xsl:when test="$position='center'">
<xsl:value-of select="$Version"/>
</xsl:when>
<xsl:when test="$position='right'">
<fo:page-number/>
</xsl:when>
</xsl:choose>
</xsl:when>
</xsl:choose>
</xsl:template>
<!--###################################################
Table Of Contents
################################################### -->
<!-- Generate the TOCs for named components only -->
<xsl:param name="generate.toc">
book toc
</xsl:param>
<!-- Show only Sections up to level 3 in the TOCs -->
<xsl:param name="toc.section.depth">2</xsl:param>
<!-- Dot and Whitespace as separator in TOC between Label and Title-->
<xsl:param name="autotoc.label.separator" select="'. '"/>
<!-- Show titles in bookmarks pane -->
<xsl:param name="fop1.extensions">1</xsl:param>
<!--###################################################
Paper & Page Size
################################################### -->
<!-- Paper type, no headers on blank pages, no double sided printing -->
<xsl:param name="paper.type" select="'A4'"/>
<xsl:param name="double.sided">0</xsl:param>
<xsl:param name="headers.on.blank.pages">0</xsl:param>
<xsl:param name="footers.on.blank.pages">0</xsl:param>
<!-- Space between paper border and content (chaotic stuff, don't touch) -->
<xsl:param name="page.margin.top">5mm</xsl:param>
<xsl:param name="region.before.extent">10mm</xsl:param>
<xsl:param name="body.margin.top">10mm</xsl:param>
<xsl:param name="body.margin.bottom">15mm</xsl:param>
<xsl:param name="region.after.extent">10mm</xsl:param>
<xsl:param name="page.margin.bottom">0mm</xsl:param>
<xsl:param name="page.margin.outer">18mm</xsl:param>
<xsl:param name="page.margin.inner">18mm</xsl:param>
<!-- No intendation of Titles -->
<xsl:param name="title.margin.left">0pc</xsl:param>
<!--###################################################
Fonts & Styles
################################################### -->
<!-- Left aligned text and no hyphenation -->
<xsl:param name="alignment">justify</xsl:param>
<xsl:param name="hyphenate">false</xsl:param>
<!-- Default Font size -->
<xsl:param name="body.font.master">11</xsl:param>
<xsl:param name="body.font.small">8</xsl:param>
<!-- Line height in body text -->
<xsl:param name="line-height">1.4</xsl:param>
<!-- Monospaced fonts are smaller than regular text -->
<xsl:attribute-set name="monospace.properties">
<xsl:attribute name="font-family">
<xsl:value-of select="$monospace.font.family"/>
</xsl:attribute>
<xsl:attribute name="font-size">0.8em</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
Tables
################################################### -->
<!-- The table width should be adapted to the paper size -->
<xsl:param name="default.table.width">17.4cm</xsl:param>
<!-- Some padding inside tables -->
<xsl:attribute-set name="table.cell.padding">
<xsl:attribute name="padding-left">4pt</xsl:attribute>
<xsl:attribute name="padding-right">4pt</xsl:attribute>
<xsl:attribute name="padding-top">4pt</xsl:attribute>
<xsl:attribute name="padding-bottom">4pt</xsl:attribute>
</xsl:attribute-set>
<!-- Only hairlines as frame and cell borders in tables -->
<xsl:param name="table.frame.border.thickness">0.1pt</xsl:param>
<xsl:param name="table.cell.border.thickness">0.1pt</xsl:param>
<!--###################################################
Labels
################################################### -->
<!-- Label Chapters and Sections (numbering) -->
<xsl:param name="chapter.autolabel">1</xsl:param>
<xsl:param name="section.autolabel" select="1"/>
<xsl:param name="section.label.includes.component.label" select="1"/>
<!--###################################################
Titles
################################################### -->
<!-- Chapter title size -->
<xsl:attribute-set name="chapter.titlepage.recto.style">
<xsl:attribute name="text-align">left</xsl:attribute>
<xsl:attribute name="font-weight">bold</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.8"/>
<xsl:text>pt</xsl:text>
</xsl:attribute>
</xsl:attribute-set>
<!-- Why is the font-size for chapters hardcoded in the XSL FO templates?
Let's remove it, so this sucker can use our attribute-set only... -->
<xsl:template match="title" mode="chapter.titlepage.recto.auto.mode">
<fo:block xmlns:fo="http://www.w3.org/1999/XSL/Format"
xsl:use-attribute-sets="chapter.titlepage.recto.style">
<xsl:call-template name="component.title">
<xsl:with-param name="node" select="ancestor-or-self::chapter[1]"/>
</xsl:call-template>
</fo:block>
</xsl:template>
<!-- Sections 1, 2 and 3 titles have a small bump factor and padding -->
<xsl:attribute-set name="section.title.level1.properties">
<xsl:attribute name="space-before.optimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.8em</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.5"/>
<xsl:text>pt</xsl:text>
</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute-set name="section.title.level2.properties">
<xsl:attribute name="space-before.optimum">0.6em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.6em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.6em</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.25"/>
<xsl:text>pt</xsl:text>
</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute-set name="section.title.level3.properties">
<xsl:attribute name="space-before.optimum">0.4em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.4em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.4em</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.0"/>
<xsl:text>pt</xsl:text>
</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<!-- Titles of formal objects (tables, examples, ...) -->
<xsl:attribute-set name="formal.title.properties" use-attribute-sets="normal.para.spacing">
<xsl:attribute name="font-weight">bold</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master"/>
<xsl:text>pt</xsl:text>
</xsl:attribute>
<xsl:attribute name="hyphenate">false</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.4em</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.6em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.8em</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
Programlistings
################################################### -->
<!-- Verbatim text formatting (programlistings) -->
<xsl:attribute-set name="monospace.verbatim.properties">
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.small * 1.0"/>
<xsl:text>pt</xsl:text>
</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute-set name="verbatim.properties">
<xsl:attribute name="space-before.minimum">1em</xsl:attribute>
<xsl:attribute name="space-before.optimum">1em</xsl:attribute>
<xsl:attribute name="space-before.maximum">1em</xsl:attribute>
<xsl:attribute name="border-color">#444444</xsl:attribute>
<xsl:attribute name="border-style">solid</xsl:attribute>
<xsl:attribute name="border-width">0.1pt</xsl:attribute>
<xsl:attribute name="padding-top">0.5em</xsl:attribute>
<xsl:attribute name="padding-left">0.5em</xsl:attribute>
<xsl:attribute name="padding-right">0.5em</xsl:attribute>
<xsl:attribute name="padding-bottom">0.5em</xsl:attribute>
<xsl:attribute name="margin-left">0.5em</xsl:attribute>
<xsl:attribute name="margin-right">0.5em</xsl:attribute>
</xsl:attribute-set>
<!-- Shade (background) programlistings -->
<xsl:param name="shade.verbatim">1</xsl:param>
<xsl:attribute-set name="shade.verbatim.style">
<xsl:attribute name="background-color">#F0F0F0</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
Callouts
################################################### -->
<!-- Use images for callouts instead of (1) (2) (3) -->
<xsl:param name="callout.graphics">0</xsl:param>
<xsl:param name="callout.unicode">1</xsl:param>
<!-- Place callout marks at this column in annotated areas -->
<xsl:param name="callout.defaultcolumn">90</xsl:param>
<!--###################################################
Admonitions
################################################### -->
<!-- Use nice graphics for admonitions -->
<xsl:param name="admon.graphics">'1'</xsl:param>
<!-- <xsl:param name="admon.graphics.path">&admon_gfx_path;</xsl:param> -->
<!--###################################################
Misc
################################################### -->
<!-- Placement of titles -->
<xsl:param name="formal.title.placement">
figure after
example before
equation before
table before
procedure before
</xsl:param>
<!-- Format Variable Lists as Blocks (prevents horizontal overflow) -->
<xsl:param name="variablelist.as.blocks">1</xsl:param>
<!-- The horrible list spacing problems -->
<xsl:attribute-set name="list.block.spacing">
<xsl:attribute name="space-before.optimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.8em</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
colored and hyphenated links
################################################### -->
<xsl:template match="ulink">
<fo:basic-link external-destination="{@url}"
xsl:use-attribute-sets="xref.properties"
text-decoration="underline"
color="blue">
<xsl:choose>
<xsl:when test="count(child::node())=0">
<xsl:value-of select="@url"/>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates/>
</xsl:otherwise>
</xsl:choose>
</fo:basic-link>
</xsl:template>
</xsl:stylesheet>
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/src/docbkx/resources/xsl/fopdf.xsl | XSLT | gpl3 | 16,604 |
<?xml version="1.0" encoding="utf-8"?>
<!--
====================================================================
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
====================================================================
This software consists of voluntary contributions made by many
individuals on behalf of the Apache Software Foundation. For more
information on the Apache Software Foundation, please see
<http://www.apache.org />.
====================================================================
Based on the XSL HTML configuration file for the Spring
Reference Documentation.
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
version="1.0">
<xsl:import href="urn:docbkx:stylesheet"/>
<!--###################################################
HTML Settings
################################################### -->
<xsl:param name="html.stylesheet">html.css</xsl:param>
<!-- These extensions are required for table printing and other stuff -->
<xsl:param name="use.extensions">1</xsl:param>
<xsl:param name="tablecolumns.extension">0</xsl:param>
<xsl:param name="callout.extensions">1</xsl:param>
<xsl:param name="graphicsize.extension">0</xsl:param>
<!--###################################################
Table Of Contents
################################################### -->
<!-- Generate the TOCs for named components only -->
<xsl:param name="generate.toc">
book toc
</xsl:param>
<!-- Show only Sections up to level 3 in the TOCs -->
<xsl:param name="toc.section.depth">3</xsl:param>
<!--###################################################
Labels
################################################### -->
<!-- Label Chapters and Sections (numbering) -->
<xsl:param name="chapter.autolabel">1</xsl:param>
<xsl:param name="section.autolabel" select="1"/>
<xsl:param name="section.label.includes.component.label" select="1"/>
<!--###################################################
Callouts
################################################### -->
<!-- Use images for callouts instead of (1) (2) (3) -->
<xsl:param name="callout.graphics">0</xsl:param>
<!-- Place callout marks at this column in annotated areas -->
<xsl:param name="callout.defaultcolumn">90</xsl:param>
<!--###################################################
Admonitions
################################################### -->
<!-- Use nice graphics for admonitions -->
<xsl:param name="admon.graphics">0</xsl:param>
<!--###################################################
Misc
################################################### -->
<!-- Placement of titles -->
<xsl:param name="formal.title.placement">
figure after
example before
equation before
table before
procedure before
</xsl:param>
<xsl:template match="author" mode="titlepage.mode">
<xsl:if test="name(preceding-sibling::*[1]) = 'author'">
<xsl:text>, </xsl:text>
</xsl:if>
<span class="{name(.)}">
<xsl:call-template name="person.name"/>
<xsl:apply-templates mode="titlepage.mode" select="./contrib"/>
<xsl:apply-templates mode="titlepage.mode" select="./affiliation"/>
</span>
</xsl:template>
<xsl:template match="authorgroup" mode="titlepage.mode">
<div class="{name(.)}">
<h2>Authors</h2>
<p/>
<xsl:apply-templates mode="titlepage.mode"/>
</div>
</xsl:template>
</xsl:stylesheet>
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/src/docbkx/resources/xsl/html.xsl | XSLT | gpl3 | 4,600 |
<?xml version="1.0" encoding="utf-8"?>
<!--
====================================================================
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
====================================================================
This software consists of voluntary contributions made by many
individuals on behalf of the Apache Software Foundation. For more
information on the Apache Software Foundation, please see
<http://www.apache.org />.
====================================================================
Based on the XSL HTML configuration file for the Spring
Reference Documentation.
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
version="1.0">
<xsl:import href="urn:docbkx:stylesheet"/>
<!--###################################################
HTML Settings
################################################### -->
<xsl:param name="chunk.section.depth">'5'</xsl:param>
<xsl:param name="use.id.as.filename">'1'</xsl:param>
<!-- These extensions are required for table printing and other stuff -->
<xsl:param name="use.extensions">1</xsl:param>
<xsl:param name="tablecolumns.extension">0</xsl:param>
<xsl:param name="callout.extensions">1</xsl:param>
<xsl:param name="graphicsize.extension">0</xsl:param>
<!--###################################################
Table Of Contents
################################################### -->
<!-- Generate the TOCs for named components only -->
<xsl:param name="generate.toc">
book toc
</xsl:param>
<!-- Show only Sections up to level 3 in the TOCs -->
<xsl:param name="toc.section.depth">3</xsl:param>
<!--###################################################
Labels
################################################### -->
<!-- Label Chapters and Sections (numbering) -->
<xsl:param name="chapter.autolabel">1</xsl:param>
<xsl:param name="section.autolabel" select="1"/>
<xsl:param name="section.label.includes.component.label" select="1"/>
<!--###################################################
Callouts
################################################### -->
<!-- Place callout marks at this column in annotated areas -->
<xsl:param name="callout.graphics">1</xsl:param>
<xsl:param name="callout.defaultcolumn">90</xsl:param>
<!--###################################################
Misc
################################################### -->
<!-- Placement of titles -->
<xsl:param name="formal.title.placement">
figure after
example before
equation before
table before
procedure before
</xsl:param>
<xsl:template match="author" mode="titlepage.mode">
<xsl:if test="name(preceding-sibling::*[1]) = 'author'">
<xsl:text>, </xsl:text>
</xsl:if>
<span class="{name(.)}">
<xsl:call-template name="person.name"/>
<xsl:apply-templates mode="titlepage.mode" select="./contrib"/>
<xsl:apply-templates mode="titlepage.mode" select="./affiliation"/>
</span>
</xsl:template>
<xsl:template match="authorgroup" mode="titlepage.mode">
<div class="{name(.)}">
<h2>Authors</h2>
<p/>
<xsl:apply-templates mode="titlepage.mode"/>
</div>
</xsl:template>
<!--###################################################
Headers and Footers
################################################### -->
<xsl:template name="user.header.navigation">
<div class="banner">
<a class="bannerLeft" href="http://www.apache.org/"
title="Apache Software Foundation">
<img style="border:none;" src="images/asf_logo_wide.gif"/>
</a>
<a class="bannerRight" href="http://hc.apache.org/httpcomponents-core-ga/"
title="Apache HttpComponents Core">
<img style="border:none;" src="images/hc_logo.png"/>
</a>
<div class="clear"/>
</div>
</xsl:template>
</xsl:stylesheet>
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/src/docbkx/resources/xsl/html_chunk.xsl | XSLT | gpl3 | 5,079 |
/*
====================================================================
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
====================================================================
This software consists of voluntary contributions made by many
individuals on behalf of the Apache Software Foundation. For more
information on the Apache Software Foundation, please see
<http://www.apache.org/>.
====================================================================
Based on the CSS file for the Spring Reference Documentation.
*/
body {
text-align: justify;
margin-right: 2em;
margin-left: 2em;
}
a:active {
color: #003399;
}
a:visited {
color: #888888;
}
p {
font-family: Verdana, Arial, sans-serif;
}
dt {
font-family: Verdana, Arial, sans-serif;
font-size: 12px;
}
p, dl, dt, dd, blockquote {
color: #000000;
margin-bottom: 3px;
margin-top: 3px;
padding-top: 0px;
}
ol, ul, p {
margin-top: 6px;
margin-bottom: 6px;
}
p, blockquote {
font-size: 90%;
}
p.releaseinfo {
font-size: 100%;
font-weight: bold;
font-family: Verdana, Arial, helvetica, sans-serif;
padding-top: 10px;
}
p.pubdate {
font-size: 120%;
font-weight: bold;
font-family: Verdana, Arial, helvetica, sans-serif;
}
td {
font-size: 80%;
}
td, th, span {
color: #000000;
}
blockquote {
margin-right: 0px;
}
h1, h2, h3, h4, h6, H6 {
color: #000000;
font-weight: 500;
margin-top: 0px;
padding-top: 14px;
font-family: Verdana, Arial, helvetica, sans-serif;
margin-bottom: 0px;
}
h2.title {
font-weight: 800;
margin-bottom: 8px;
}
h2.subtitle {
font-weight: 800;
margin-bottom: 20px;
}
.firstname, .surname {
font-size: 12px;
font-family: Verdana, Arial, helvetica, sans-serif;
}
table {
border-collapse: collapse;
border-spacing: 0;
border: 1px black;
empty-cells: hide;
margin: 10px 0px 30px 50px;
width: 90%;
}
div.table {
margin: 30px 0px 30px 0px;
border: 1px dashed gray;
padding: 10px;
}
div .table-contents table {
border: 1px solid black;
}
div.table > p.title {
padding-left: 10px;
}
td {
padding: 4pt;
font-family: Verdana, Arial, helvetica, sans-serif;
}
div.warning TD {
text-align: justify;
}
h1 {
font-size: 150%;
}
h2 {
font-size: 110%;
}
h3 {
font-size: 100%;
font-weight: bold;
}
h4 {
font-size: 90%;
font-weight: bold;
}
h5 {
font-size: 90%;
font-style: italic;
}
h6 {
font-size: 100%;
font-style: italic;
}
tt {
font-size: 110%;
font-family: "Courier New", Courier, monospace;
color: #000000;
}
.navheader, .navfooter {
border: none;
}
pre {
font-size: 110%;
padding: 5px;
border-style: solid;
border-width: 1px;
border-color: #CCCCCC;
background-color: #f3f5e9;
}
ul, ol, li {
list-style: disc;
}
hr {
width: 100%;
height: 1px;
background-color: #CCCCCC;
border-width: 0px;
padding: 0px;
}
.variablelist {
padding-top: 10px;
padding-bottom: 10px;
margin: 0;
}
.term {
font-weight: bold;
}
.mediaobject {
padding-top: 30px;
padding-bottom: 30px;
}
.legalnotice {
font-family: Verdana, Arial, helvetica, sans-serif;
font-size: 12px;
font-style: italic;
}
.sidebar {
float: right;
margin: 10px 0px 10px 30px;
padding: 10px 20px 20px 20px;
width: 33%;
border: 1px solid black;
background-color: #F4F4F4;
font-size: 14px;
}
.property {
font-family: "Courier New", Courier, monospace;
}
a code {
font-family: Verdana, Arial, monospace;
font-size: 12px;
}
td code {
font-size: 110%;
}
div.note * td,
div.tip * td,
div.warning * td,
div.calloutlist * td {
text-align: justify;
font-size: 100%;
}
.programlisting .interfacename,
.programlisting .literal,
.programlisting .classname {
font-size: 95%;
}
.title .interfacename,
.title .literal,
.title .classname {
font-size: 130%;
}
.programlisting * .lineannotation,
.programlisting * .lineannotation * {
color: blue;
}
.bannerLeft, .bannerRight {
font-size: xx-large;
font-weight: bold;
}
.bannerLeft img, .bannerRight img {
margin: 0px;
}
.bannerLeft img {
float:left;
text-shadow: #7CFC00;
}
.bannerRight img {
float:right;
text-shadow: #7CFC00;
}
.banner {
padding: 0px;
}
.banner img {
border: none;
}
.clear {
clear:both;
visibility: hidden;
} | zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/src/docbkx/resources/css/hc-tutorial.css | CSS | gpl3 | 5,273 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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();
}
}
}
| zzhhhhh-android-gps | 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.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();
}
});
}
}
| zzhhhhh-android-gps | 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();
}
});
}
}
| zzhhhhh-android-gps | 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();
}
} | zzhhhhh-android-gps | 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.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);
}
} | zzhhhhh-android-gps | 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 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);
}
} | zzhhhhh-android-gps | 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;
interface HttpWorkerCallback {
void started(HttpWorker worker);
void shutdown(HttpWorker worker);
} | zzhhhhh-android-gps | 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.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();
}
});
}
}
| zzhhhhh-android-gps | 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.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();
}
});
}
}
| zzhhhhh-android-gps | 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.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;
}
}
}
} | zzhhhhh-android-gps | 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 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());
}
}
}
} | zzhhhhh-android-gps | 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.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);
}
}
| zzhhhhh-android-gps | 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;
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;
}
}
} | zzhhhhh-android-gps | 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;
public interface HttpServer {
String getName();
String getVersion();
void start() throws Exception;
void shutdown();
}
| zzhhhhh-android-gps | 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;
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;
}
}
| zzhhhhh-android-gps | 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;
/**
* 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;
}
}
| zzhhhhh-android-gps | 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.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");
}
}
| zzhhhhh-android-gps | 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;
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;
}
}
| zzhhhhh-android-gps | 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 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);
}
}
| zzhhhhh-android-gps | 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 org.apache.http.message.BasicHeader;
public class DefaultHeader extends BasicHeader {
public DefaultHeader(final String name, final String value) {
super(name, value);
}
}
| zzhhhhh-android-gps | 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.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;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-ab/src/main/java/org/apache/http/benchmark/BenchmarkWorker.java | Java | gpl3 | 13,436 |
@import url("../../../css/hc-maven.css"); | zzhhhhh-android-gps | 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;
import java.net.InetAddress;
/**
* An HTTP connection over the Internet Protocol (IP).
*
* @since 4.0
*/
public interface HttpInetConnection extends HttpConnection {
InetAddress getLocalAddress();
int getLocalPort();
InetAddress getRemoteAddress();
int getRemotePort();
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpInetConnection.java | Java | gpl3 | 1,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;
/**
* Constants enumerating the HTTP status codes.
* All status codes defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and
* RFC2518 (WebDAV) are listed.
*
* @see StatusLine
*
* @since 4.0
*/
public interface HttpStatus {
// --- 1xx Informational ---
/** <tt>100 Continue</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_CONTINUE = 100;
/** <tt>101 Switching Protocols</tt> (HTTP/1.1 - RFC 2616)*/
public static final int SC_SWITCHING_PROTOCOLS = 101;
/** <tt>102 Processing</tt> (WebDAV - RFC 2518) */
public static final int SC_PROCESSING = 102;
// --- 2xx Success ---
/** <tt>200 OK</tt> (HTTP/1.0 - RFC 1945) */
public static final int SC_OK = 200;
/** <tt>201 Created</tt> (HTTP/1.0 - RFC 1945) */
public static final int SC_CREATED = 201;
/** <tt>202 Accepted</tt> (HTTP/1.0 - RFC 1945) */
public static final int SC_ACCEPTED = 202;
/** <tt>203 Non Authoritative Information</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;
/** <tt>204 No Content</tt> (HTTP/1.0 - RFC 1945) */
public static final int SC_NO_CONTENT = 204;
/** <tt>205 Reset Content</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_RESET_CONTENT = 205;
/** <tt>206 Partial Content</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_PARTIAL_CONTENT = 206;
/**
* <tt>207 Multi-Status</tt> (WebDAV - RFC 2518) or <tt>207 Partial Update
* OK</tt> (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?)
*/
public static final int SC_MULTI_STATUS = 207;
// --- 3xx Redirection ---
/** <tt>300 Mutliple Choices</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_MULTIPLE_CHOICES = 300;
/** <tt>301 Moved Permanently</tt> (HTTP/1.0 - RFC 1945) */
public static final int SC_MOVED_PERMANENTLY = 301;
/** <tt>302 Moved Temporarily</tt> (Sometimes <tt>Found</tt>) (HTTP/1.0 - RFC 1945) */
public static final int SC_MOVED_TEMPORARILY = 302;
/** <tt>303 See Other</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_SEE_OTHER = 303;
/** <tt>304 Not Modified</tt> (HTTP/1.0 - RFC 1945) */
public static final int SC_NOT_MODIFIED = 304;
/** <tt>305 Use Proxy</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_USE_PROXY = 305;
/** <tt>307 Temporary Redirect</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_TEMPORARY_REDIRECT = 307;
// --- 4xx Client Error ---
/** <tt>400 Bad Request</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_BAD_REQUEST = 400;
/** <tt>401 Unauthorized</tt> (HTTP/1.0 - RFC 1945) */
public static final int SC_UNAUTHORIZED = 401;
/** <tt>402 Payment Required</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_PAYMENT_REQUIRED = 402;
/** <tt>403 Forbidden</tt> (HTTP/1.0 - RFC 1945) */
public static final int SC_FORBIDDEN = 403;
/** <tt>404 Not Found</tt> (HTTP/1.0 - RFC 1945) */
public static final int SC_NOT_FOUND = 404;
/** <tt>405 Method Not Allowed</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_METHOD_NOT_ALLOWED = 405;
/** <tt>406 Not Acceptable</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_NOT_ACCEPTABLE = 406;
/** <tt>407 Proxy Authentication Required</tt> (HTTP/1.1 - RFC 2616)*/
public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
/** <tt>408 Request Timeout</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_REQUEST_TIMEOUT = 408;
/** <tt>409 Conflict</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_CONFLICT = 409;
/** <tt>410 Gone</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_GONE = 410;
/** <tt>411 Length Required</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_LENGTH_REQUIRED = 411;
/** <tt>412 Precondition Failed</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_PRECONDITION_FAILED = 412;
/** <tt>413 Request Entity Too Large</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_REQUEST_TOO_LONG = 413;
/** <tt>414 Request-URI Too Long</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_REQUEST_URI_TOO_LONG = 414;
/** <tt>415 Unsupported Media Type</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
/** <tt>416 Requested Range Not Satisfiable</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
/** <tt>417 Expectation Failed</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_EXPECTATION_FAILED = 417;
/**
* Static constant for a 418 error.
* <tt>418 Unprocessable Entity</tt> (WebDAV drafts?)
* or <tt>418 Reauthentication Required</tt> (HTTP/1.1 drafts?)
*/
// not used
// public static final int SC_UNPROCESSABLE_ENTITY = 418;
/**
* Static constant for a 419 error.
* <tt>419 Insufficient Space on Resource</tt>
* (WebDAV - draft-ietf-webdav-protocol-05?)
* or <tt>419 Proxy Reauthentication Required</tt>
* (HTTP/1.1 drafts?)
*/
public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419;
/**
* Static constant for a 420 error.
* <tt>420 Method Failure</tt>
* (WebDAV - draft-ietf-webdav-protocol-05?)
*/
public static final int SC_METHOD_FAILURE = 420;
/** <tt>422 Unprocessable Entity</tt> (WebDAV - RFC 2518) */
public static final int SC_UNPROCESSABLE_ENTITY = 422;
/** <tt>423 Locked</tt> (WebDAV - RFC 2518) */
public static final int SC_LOCKED = 423;
/** <tt>424 Failed Dependency</tt> (WebDAV - RFC 2518) */
public static final int SC_FAILED_DEPENDENCY = 424;
// --- 5xx Server Error ---
/** <tt>500 Server Error</tt> (HTTP/1.0 - RFC 1945) */
public static final int SC_INTERNAL_SERVER_ERROR = 500;
/** <tt>501 Not Implemented</tt> (HTTP/1.0 - RFC 1945) */
public static final int SC_NOT_IMPLEMENTED = 501;
/** <tt>502 Bad Gateway</tt> (HTTP/1.0 - RFC 1945) */
public static final int SC_BAD_GATEWAY = 502;
/** <tt>503 Service Unavailable</tt> (HTTP/1.0 - RFC 1945) */
public static final int SC_SERVICE_UNAVAILABLE = 503;
/** <tt>504 Gateway Timeout</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_GATEWAY_TIMEOUT = 504;
/** <tt>505 HTTP Version Not Supported</tt> (HTTP/1.1 - RFC 2616) */
public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
/** <tt>507 Insufficient Storage</tt> (WebDAV - RFC 2518) */
public static final int SC_INSUFFICIENT_STORAGE = 507;
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpStatus.java | Java | gpl3 | 7,818 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* A factory for {@link HttpRequest HttpRequest} objects.
*
* @since 4.0
*/
public interface HttpRequestFactory {
HttpRequest newHttpRequest(RequestLine requestline)
throws MethodNotSupportedException;
HttpRequest newHttpRequest(String method, String uri)
throws MethodNotSupportedException;
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpRequestFactory.java | Java | gpl3 | 1,547 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.params.HttpProtocolParams;
/**
* RequestUserAgent is responsible for adding <code>User-Agent</code> header.
* This interceptor is recommended for client side protocol processors.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#USER_AGENT}</li>
* </ul>
*
* @since 4.0
*/
public class RequestUserAgent implements HttpRequestInterceptor {
public RequestUserAgent() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (!request.containsHeader(HTTP.USER_AGENT)) {
String useragent = HttpProtocolParams.getUserAgent(request.getParams());
if (useragent != null) {
request.addHeader(HTTP.USER_AGENT, useragent);
}
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/RequestUserAgent.java | Java | gpl3 | 2,442 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
/**
* Defines an interface to verify whether an incoming HTTP request meets
* the target server's expectations.
*<p>
* The Expect request-header field is used to indicate that particular
* server behaviors are required by the client.
*</p>
*<pre>
* Expect = "Expect" ":" 1#expectation
*
* expectation = "100-continue" | expectation-extension
* expectation-extension = token [ "=" ( token | quoted-string )
* *expect-params ]
* expect-params = ";" token [ "=" ( token | quoted-string ) ]
*</pre>
*<p>
* A server that does not understand or is unable to comply with any of
* the expectation values in the Expect field of a request MUST respond
* with appropriate error status. The server MUST respond with a 417
* (Expectation Failed) status if any of the expectations cannot be met
* or, if there are other problems with the request, some other 4xx
* status.
*</p>
*
* @since 4.0
*/
public interface HttpExpectationVerifier {
/**
* Verifies whether the given request meets the server's expectations.
* <p>
* If the request fails to meet particular criteria, this method can
* trigger a terminal response back to the client by setting the status
* code of the response object to a value greater or equal to
* <code>200</code>. In this case the client will not have to transmit
* the request body. If the request meets expectations this method can
* terminate without modifying the response object. Per default the status
* code of the response object will be set to <code>100</code>.
*
* @param request the HTTP request.
* @param response the HTTP response.
* @param context the HTTP context.
* @throws HttpException in case of an HTTP protocol violation.
*/
void verify(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException;
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/HttpExpectationVerifier.java | Java | gpl3 | 3,279 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
/**
* Constants and static helpers related to the HTTP protocol.
*
* @since 4.0
*/
public final class HTTP {
public static final int CR = 13; // <US-ASCII CR, carriage return (13)>
public static final int LF = 10; // <US-ASCII LF, linefeed (10)>
public static final int SP = 32; // <US-ASCII SP, space (32)>
public static final int HT = 9; // <US-ASCII HT, horizontal-tab (9)>
/** HTTP header definitions */
public static final String TRANSFER_ENCODING = "Transfer-Encoding";
public static final String CONTENT_LEN = "Content-Length";
public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_ENCODING = "Content-Encoding";
public static final String EXPECT_DIRECTIVE = "Expect";
public static final String CONN_DIRECTIVE = "Connection";
public static final String TARGET_HOST = "Host";
public static final String USER_AGENT = "User-Agent";
public static final String DATE_HEADER = "Date";
public static final String SERVER_HEADER = "Server";
/** HTTP expectations */
public static final String EXPECT_CONTINUE = "100-continue";
/** HTTP connection control */
public static final String CONN_CLOSE = "Close";
public static final String CONN_KEEP_ALIVE = "Keep-Alive";
/** Transfer encoding definitions */
public static final String CHUNK_CODING = "chunked";
public static final String IDENTITY_CODING = "identity";
/** Common charset definitions */
public static final String UTF_8 = "UTF-8";
public static final String UTF_16 = "UTF-16";
public static final String US_ASCII = "US-ASCII";
public static final String ASCII = "ASCII";
public static final String ISO_8859_1 = "ISO-8859-1";
/** Default charsets */
public static final String DEFAULT_CONTENT_CHARSET = ISO_8859_1;
public static final String DEFAULT_PROTOCOL_CHARSET = US_ASCII;
/** Content type definitions */
public final static String OCTET_STREAM_TYPE = "application/octet-stream";
public final static String PLAIN_TEXT_TYPE = "text/plain";
public final static String CHARSET_PARAM = "; charset=";
/** Default content type */
public final static String DEFAULT_CONTENT_TYPE = OCTET_STREAM_TYPE;
public static boolean isWhitespace(char ch) {
return ch == SP || ch == HT || ch == CR || ch == LF;
}
private HTTP() {
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/HTTP.java | Java | gpl3 | 3,635 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
/**
* RequestDate interceptor is responsible for adding <code>Date</code> header
* to the outgoing requests This interceptor is optional for client side
* protocol processors.
*
* @since 4.0
*/
public class RequestDate implements HttpRequestInterceptor {
private static final HttpDateGenerator DATE_GENERATOR = new HttpDateGenerator();
public RequestDate() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException
("HTTP request may not be null.");
}
if ((request instanceof HttpEntityEnclosingRequest) &&
!request.containsHeader(HTTP.DATE_HEADER)) {
String httpdate = DATE_GENERATOR.getCurrentDate();
request.setHeader(HTTP.DATE_HEADER, httpdate);
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/RequestDate.java | Java | gpl3 | 2,367 |
<html>
<head>
<!--
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
-->
</head>
<body>
HTTP protocol execution framework. This package contains common protocol
aspects implemented as protocol interceptors as well as protocol handler
implementations based on classic (blocking) I/O model.
</body>
</html>
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/package.html | HTML | gpl3 | 1,440 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
/**
* HttpRequestHandler represents a routine for processing of a specific group
* of HTTP requests. Protocol handlers are designed to take care of protocol
* specific aspects, whereas individual request handlers are expected to take
* care of application specific HTTP processing. The main purpose of a request
* handler is to generate a response object with a content entity to be sent
* back to the client in response to the given request
*
* @since 4.0
*/
public interface HttpRequestHandler {
/**
* Handles the request and produces a response to be sent back to
* the client.
*
* @param request the HTTP request.
* @param response the HTTP response.
* @param context the HTTP execution context.
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
void handle(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException;
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/HttpRequestHandler.java | Java | gpl3 | 2,410 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
/**
* HttpRequestHandlerResolver can be used to resolve an instance of
* {@link HttpRequestHandler} matching a particular request URI. Usually the
* resolved request handler will be used to process the request with the
* specified request URI.
*
* @since 4.0
*/
public interface HttpRequestHandlerResolver {
/**
* Looks up a handler matching the given request URI.
*
* @param requestURI the request URI
* @return HTTP request handler or <code>null</code> if no match
* is found.
*/
HttpRequestHandler lookup(String requestURI);
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/HttpRequestHandlerResolver.java | Java | gpl3 | 1,801 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.ProtocolVersion;
/**
* RequestContent is the most important interceptor for outgoing requests.
* It is responsible for delimiting content length by adding
* <code>Content-Length</code> or <code>Transfer-Content</code> headers based
* on the properties of the enclosed entity and the protocol version.
* This interceptor is required for correct functioning of client side protocol
* processors.
*
* @since 4.0
*/
public class RequestContent implements HttpRequestInterceptor {
public RequestContent() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (request instanceof HttpEntityEnclosingRequest) {
if (request.containsHeader(HTTP.TRANSFER_ENCODING)) {
throw new ProtocolException("Transfer-encoding header already present");
}
if (request.containsHeader(HTTP.CONTENT_LEN)) {
throw new ProtocolException("Content-Length header already present");
}
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
if (entity == null) {
request.addHeader(HTTP.CONTENT_LEN, "0");
return;
}
// Must specify a transfer encoding or a content length
if (entity.isChunked() || entity.getContentLength() < 0) {
if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
throw new ProtocolException(
"Chunked transfer encoding not allowed for " + ver);
}
request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);
} else {
request.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength()));
}
// Specify a content type if known
if (entity.getContentType() != null && !request.containsHeader(
HTTP.CONTENT_TYPE )) {
request.addHeader(entity.getContentType());
}
// Specify a content encoding if known
if (entity.getContentEncoding() != null && !request.containsHeader(
HTTP.CONTENT_ENCODING)) {
request.addHeader(entity.getContentEncoding());
}
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/RequestContent.java | Java | gpl3 | 4,134 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import java.net.InetAddress;
import org.apache.ogt.http.HttpConnection;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpInetConnection;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.ProtocolVersion;
/**
* RequestTargetHost is responsible for adding <code>Host</code> header. This
* interceptor is required for client side protocol processors.
*
* @since 4.0
*/
public class RequestTargetHost implements HttpRequestInterceptor {
public RequestTargetHost() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase("CONNECT") && ver.lessEquals(HttpVersion.HTTP_1_0)) {
return;
}
if (!request.containsHeader(HTTP.TARGET_HOST)) {
HttpHost targethost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (targethost == null) {
HttpConnection conn = (HttpConnection) context
.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn instanceof HttpInetConnection) {
// Populate the context with a default HTTP host based on the
// inet address of the target host
InetAddress address = ((HttpInetConnection) conn).getRemoteAddress();
int port = ((HttpInetConnection) conn).getRemotePort();
if (address != null) {
targethost = new HttpHost(address.getHostName(), port);
}
}
if (targethost == null) {
if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
return;
} else {
throw new ProtocolException("Target host missing");
}
}
}
request.addHeader(HTTP.TARGET_HOST, targethost.toHostString());
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/RequestTargetHost.java | Java | gpl3 | 3,856 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import java.net.ProtocolException;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.params.CoreProtocolPNames;
/**
* HttpRequestExecutor is a client side HTTP protocol handler based on the
* blocking I/O model that implements the essential requirements of the HTTP
* protocol for the client side message processing, as described by RFC 2616.
* <br>
* HttpRequestExecutor relies on {@link HttpProcessor} to generate mandatory
* protocol headers for all outgoing messages and apply common, cross-cutting
* message transformations to all incoming and outgoing messages. Application
* specific processing can be implemented outside HttpRequestExecutor once the
* request has been executed and a response has been received.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}</li>
* </ul>
*
* @since 4.0
*/
public class HttpRequestExecutor {
/**
* Create a new request executor.
*/
public HttpRequestExecutor() {
super();
}
/**
* Decide whether a response comes with an entity.
* The implementation in this class is based on RFC 2616.
* <br/>
* Derived executors can override this method to handle
* methods and response codes not specified in RFC 2616.
*
* @param request the request, to obtain the executed method
* @param response the response, to obtain the status code
*/
protected boolean canResponseHaveBody(final HttpRequest request,
final HttpResponse response) {
if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
return false;
}
int status = response.getStatusLine().getStatusCode();
return status >= HttpStatus.SC_OK
&& status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_NOT_MODIFIED
&& status != HttpStatus.SC_RESET_CONTENT;
}
/**
* Sends the request and obtain a response.
*
* @param request the request to execute.
* @param conn the connection over which to execute the request.
*
* @return the response to the request.
*
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
public HttpResponse execute(
final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context)
throws IOException, HttpException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (conn == null) {
throw new IllegalArgumentException("Client connection may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
try {
HttpResponse response = doSendRequest(request, conn, context);
if (response == null) {
response = doReceiveResponse(request, conn, context);
}
return response;
} catch (IOException ex) {
closeConnection(conn);
throw ex;
} catch (HttpException ex) {
closeConnection(conn);
throw ex;
} catch (RuntimeException ex) {
closeConnection(conn);
throw ex;
}
}
private final static void closeConnection(final HttpClientConnection conn) {
try {
conn.close();
} catch (IOException ignore) {
}
}
/**
* Pre-process the given request using the given protocol processor and
* initiates the process of request execution.
*
* @param request the request to prepare
* @param processor the processor to use
* @param context the context for sending the request
*
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
public void preProcess(
final HttpRequest request,
final HttpProcessor processor,
final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (processor == null) {
throw new IllegalArgumentException("HTTP processor may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
processor.process(request, context);
}
/**
* Send the given request over the given connection.
* <p>
* This method also handles the expect-continue handshake if necessary.
* If it does not have to handle an expect-continue handshake, it will
* not use the connection for reading or anything else that depends on
* data coming in over the connection.
*
* @param request the request to send, already
* {@link #preProcess preprocessed}
* @param conn the connection over which to send the request,
* already established
* @param context the context for sending the request
*
* @return a terminal response received as part of an expect-continue
* handshake, or
* <code>null</code> if the expect-continue handshake is not used
*
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
protected HttpResponse doSendRequest(
final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context)
throws IOException, HttpException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (conn == null) {
throw new IllegalArgumentException("HTTP connection may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
HttpResponse response = null;
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_REQ_SENT, Boolean.FALSE);
conn.sendRequestHeader(request);
if (request instanceof HttpEntityEnclosingRequest) {
// Check for expect-continue handshake. We have to flush the
// headers and wait for an 100-continue response to handle it.
// If we get a different response, we must not send the entity.
boolean sendentity = true;
final ProtocolVersion ver =
request.getRequestLine().getProtocolVersion();
if (((HttpEntityEnclosingRequest) request).expectContinue() &&
!ver.lessEquals(HttpVersion.HTTP_1_0)) {
conn.flush();
// As suggested by RFC 2616 section 8.2.3, we don't wait for a
// 100-continue response forever. On timeout, send the entity.
int tms = request.getParams().getIntParameter(
CoreProtocolPNames.WAIT_FOR_CONTINUE, 2000);
if (conn.isResponseAvailable(tms)) {
response = conn.receiveResponseHeader();
if (canResponseHaveBody(request, response)) {
conn.receiveResponseEntity(response);
}
int status = response.getStatusLine().getStatusCode();
if (status < 200) {
if (status != HttpStatus.SC_CONTINUE) {
throw new ProtocolException(
"Unexpected response: " + response.getStatusLine());
}
// discard 100-continue
response = null;
} else {
sendentity = false;
}
}
}
if (sendentity) {
conn.sendRequestEntity((HttpEntityEnclosingRequest) request);
}
}
conn.flush();
context.setAttribute(ExecutionContext.HTTP_REQ_SENT, Boolean.TRUE);
return response;
}
/**
* Waits for and receives a response.
* This method will automatically ignore intermediate responses
* with status code 1xx.
*
* @param request the request for which to obtain the response
* @param conn the connection over which the request was sent
* @param context the context for receiving the response
*
* @return the terminal response, not yet post-processed
*
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
protected HttpResponse doReceiveResponse(
final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (conn == null) {
throw new IllegalArgumentException("HTTP connection may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
HttpResponse response = null;
int statuscode = 0;
while (response == null || statuscode < HttpStatus.SC_OK) {
response = conn.receiveResponseHeader();
if (canResponseHaveBody(request, response)) {
conn.receiveResponseEntity(response);
}
statuscode = response.getStatusLine().getStatusCode();
} // while intermediate response
return response;
}
/**
* Post-processes the given response using the given protocol processor and
* completes the process of request execution.
* <p>
* This method does <i>not</i> read the response entity, if any.
* The connection over which content of the response entity is being
* streamed from cannot be reused until {@link HttpEntity#consumeContent()}
* has been invoked.
*
* @param response the response object to post-process
* @param processor the processor to use
* @param context the context for post-processing the response
*
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
public void postProcess(
final HttpResponse response,
final HttpProcessor processor,
final HttpContext context)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
if (processor == null) {
throw new IllegalArgumentException("HTTP processor may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);
processor.process(response, context);
}
} // class HttpRequestExecutor
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/HttpRequestExecutor.java | Java | gpl3 | 13,382 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Generates a date in the format required by the HTTP protocol.
*
* @since 4.0
*/
public class HttpDateGenerator {
/** Date format pattern used to generate the header in RFC 1123 format. */
public static final
String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
/** The time zone to use in the date header. */
public static final TimeZone GMT = TimeZone.getTimeZone("GMT");
private final DateFormat dateformat;
private long dateAsLong = 0L;
private String dateAsText = null;
public HttpDateGenerator() {
super();
this.dateformat = new SimpleDateFormat(PATTERN_RFC1123, Locale.US);
this.dateformat.setTimeZone(GMT);
}
public synchronized String getCurrentDate() {
long now = System.currentTimeMillis();
if (now - this.dateAsLong > 1000) {
// Generate new date string
this.dateAsText = this.dateformat.format(new Date(now));
this.dateAsLong = now;
}
return this.dateAsText;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/HttpDateGenerator.java | Java | gpl3 | 2,407 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
/**
* Immutable {@link HttpProcessor}.
*
* @since 4.1
*/
//@ThreadSafe
public final class ImmutableHttpProcessor implements HttpProcessor {
private final HttpRequestInterceptor[] requestInterceptors;
private final HttpResponseInterceptor[] responseInterceptors;
public ImmutableHttpProcessor(
final HttpRequestInterceptor[] requestInterceptors,
final HttpResponseInterceptor[] responseInterceptors) {
super();
if (requestInterceptors != null) {
int count = requestInterceptors.length;
this.requestInterceptors = new HttpRequestInterceptor[count];
for (int i = 0; i < count; i++) {
this.requestInterceptors[i] = requestInterceptors[i];
}
} else {
this.requestInterceptors = new HttpRequestInterceptor[0];
}
if (responseInterceptors != null) {
int count = responseInterceptors.length;
this.responseInterceptors = new HttpResponseInterceptor[count];
for (int i = 0; i < count; i++) {
this.responseInterceptors[i] = responseInterceptors[i];
}
} else {
this.responseInterceptors = new HttpResponseInterceptor[0];
}
}
public ImmutableHttpProcessor(
final HttpRequestInterceptorList requestInterceptors,
final HttpResponseInterceptorList responseInterceptors) {
super();
if (requestInterceptors != null) {
int count = requestInterceptors.getRequestInterceptorCount();
this.requestInterceptors = new HttpRequestInterceptor[count];
for (int i = 0; i < count; i++) {
this.requestInterceptors[i] = requestInterceptors.getRequestInterceptor(i);
}
} else {
this.requestInterceptors = new HttpRequestInterceptor[0];
}
if (responseInterceptors != null) {
int count = responseInterceptors.getResponseInterceptorCount();
this.responseInterceptors = new HttpResponseInterceptor[count];
for (int i = 0; i < count; i++) {
this.responseInterceptors[i] = responseInterceptors.getResponseInterceptor(i);
}
} else {
this.responseInterceptors = new HttpResponseInterceptor[0];
}
}
public ImmutableHttpProcessor(final HttpRequestInterceptor[] requestInterceptors) {
this(requestInterceptors, null);
}
public ImmutableHttpProcessor(final HttpResponseInterceptor[] responseInterceptors) {
this(null, responseInterceptors);
}
public void process(
final HttpRequest request,
final HttpContext context) throws IOException, HttpException {
for (int i = 0; i < this.requestInterceptors.length; i++) {
this.requestInterceptors[i].process(request, context);
}
}
public void process(
final HttpResponse response,
final HttpContext context) throws IOException, HttpException {
for (int i = 0; i < this.responseInterceptors.length; i++) {
this.responseInterceptors[i].process(response, context);
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/ImmutableHttpProcessor.java | Java | gpl3 | 4,693 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.util.List;
import org.apache.ogt.http.HttpResponseInterceptor;
/**
* Provides access to an ordered list of response interceptors.
* Lists are expected to be built upfront and used read-only afterwards
* for {@link HttpProcessor processing}.
*
* @since 4.0
*/
public interface HttpResponseInterceptorList {
/**
* Appends a response interceptor to this list.
*
* @param interceptor the response interceptor to add
*/
void addResponseInterceptor(HttpResponseInterceptor interceptor);
/**
* Inserts a response interceptor at the specified index.
*
* @param interceptor the response interceptor to add
* @param index the index to insert the interceptor at
*/
void addResponseInterceptor(HttpResponseInterceptor interceptor, int index);
/**
* Obtains the current size of this list.
*
* @return the number of response interceptors in this list
*/
int getResponseInterceptorCount();
/**
* Obtains a response interceptor from this list.
*
* @param index the index of the interceptor to obtain,
* 0 for first
*
* @return the interceptor at the given index, or
* <code>null</code> if the index is out of range
*/
HttpResponseInterceptor getResponseInterceptor(int index);
/**
* Removes all response interceptors from this list.
*/
void clearResponseInterceptors();
/**
* Removes all response interceptor of the specified class
*
* @param clazz the class of the instances to be removed.
*/
void removeResponseInterceptorByClass(Class clazz);
/**
* Sets the response interceptors in this list.
* This list will be cleared and re-initialized to contain
* all response interceptors from the argument list.
* If the argument list includes elements that are not response
* interceptors, the behavior is implementation dependent.
*
* @param list the list of response interceptors
*/
void setInterceptors(List list);
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/HttpResponseInterceptorList.java | Java | gpl3 | 3,321 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.ProtocolVersion;
/**
* ResponseContent is the most important interceptor for outgoing responses.
* It is responsible for delimiting content length by adding
* <code>Content-Length</code> or <code>Transfer-Content</code> headers based
* on the properties of the enclosed entity and the protocol version.
* This interceptor is required for correct functioning of server side protocol
* processors.
*
* @since 4.0
*/
public class ResponseContent implements HttpResponseInterceptor {
public ResponseContent() {
super();
}
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (response.containsHeader(HTTP.TRANSFER_ENCODING)) {
throw new ProtocolException("Transfer-encoding header already present");
}
if (response.containsHeader(HTTP.CONTENT_LEN)) {
throw new ProtocolException("Content-Length header already present");
}
ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
HttpEntity entity = response.getEntity();
if (entity != null) {
long len = entity.getContentLength();
if (entity.isChunked() && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
response.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);
} else if (len >= 0) {
response.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength()));
}
// Specify a content type if known
if (entity.getContentType() != null && !response.containsHeader(
HTTP.CONTENT_TYPE )) {
response.addHeader(entity.getContentType());
}
// Specify a content encoding if known
if (entity.getContentEncoding() != null && !response.containsHeader(
HTTP.CONTENT_ENCODING)) {
response.addHeader(entity.getContentEncoding());
}
} else {
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_NOT_MODIFIED
&& status != HttpStatus.SC_RESET_CONTENT) {
response.addHeader(HTTP.CONTENT_LEN, "0");
}
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/ResponseContent.java | Java | gpl3 | 4,042 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponseInterceptor;
/**
* HTTP protocol processor is a collection of protocol interceptors that
* implements the 'Chain of Responsibility' pattern, where each individual
* protocol interceptor is expected to work on a particular aspect of the HTTP
* protocol the interceptor is responsible for.
* <p>
* Usually the order in which interceptors are executed should not matter as
* long as they do not depend on a particular state of the execution context.
* If protocol interceptors have interdependencies and therefore must be
* executed in a particular order, they should be added to the protocol
* processor in the same sequence as their expected execution order.
* <p>
* Protocol interceptors must be implemented as thread-safe. Similarly to
* servlets, protocol interceptors should not use instance variables unless
* access to those variables is synchronized.
*
* @since 4.0
*/
public interface HttpProcessor
extends HttpRequestInterceptor, HttpResponseInterceptor {
// no additional methods
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/HttpProcessor.java | Java | gpl3 | 2,332 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.util.HashMap;
/**
* HttpContext represents execution state of an HTTP process. It is a structure
* that can be used to map an attribute name to an attribute value. Internally
* HTTP context implementations are usually backed by a {@link HashMap}.
* <p>
* The primary purpose of the HTTP context is to facilitate information sharing
* among various logically related components. HTTP context can be used
* to store a processing state for one message or several consecutive messages.
* Multiple logically related messages can participate in a logical session
* if the same context is reused between consecutive messages.
*
* @since 4.0
*/
public interface HttpContext {
/** The prefix reserved for use by HTTP components. "http." */
public static final String RESERVED_PREFIX = "http.";
/**
* Obtains attribute with the given name.
*
* @param id the attribute name.
* @return attribute value, or <code>null</code> if not set.
*/
Object getAttribute(String id);
/**
* Sets value of the attribute with the given name.
*
* @param id the attribute name.
* @param obj the attribute value.
*/
void setAttribute(String id, Object obj);
/**
* Removes attribute with the given name from the context.
*
* @param id the attribute name.
* @return attribute value, or <code>null</code> if not set.
*/
Object removeAttribute(String id);
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/HttpContext.java | Java | gpl3 | 2,686 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
/**
* Thread-safe extension of the {@link BasicHttpContext}.
*
* @since 4.0
*/
public class SyncBasicHttpContext extends BasicHttpContext {
public SyncBasicHttpContext(final HttpContext parentContext) {
super(parentContext);
}
public synchronized Object getAttribute(final String id) {
return super.getAttribute(id);
}
public synchronized void setAttribute(final String id, final Object obj) {
super.setAttribute(id, obj);
}
public synchronized Object removeAttribute(final String id) {
return super.removeAttribute(id);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/SyncBasicHttpContext.java | Java | gpl3 | 1,822 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
/**
* Default implementation of {@link HttpProcessor}.
* <p>
* Please note access to the internal structures of this class is not
* synchronized and therefore this class may be thread-unsafe.
*
* @since 4.0
*/
//@NotThreadSafe // Lists are not synchronized
public final class BasicHttpProcessor implements
HttpProcessor, HttpRequestInterceptorList, HttpResponseInterceptorList, Cloneable {
// Don't allow direct access, as nulls are not allowed
protected final List requestInterceptors = new ArrayList();
protected final List responseInterceptors = new ArrayList();
public void addRequestInterceptor(final HttpRequestInterceptor itcp) {
if (itcp == null) {
return;
}
this.requestInterceptors.add(itcp);
}
public void addRequestInterceptor(
final HttpRequestInterceptor itcp, int index) {
if (itcp == null) {
return;
}
this.requestInterceptors.add(index, itcp);
}
public void addResponseInterceptor(
final HttpResponseInterceptor itcp, int index) {
if (itcp == null) {
return;
}
this.responseInterceptors.add(index, itcp);
}
public void removeRequestInterceptorByClass(final Class clazz) {
for (Iterator it = this.requestInterceptors.iterator();
it.hasNext(); ) {
Object request = it.next();
if (request.getClass().equals(clazz)) {
it.remove();
}
}
}
public void removeResponseInterceptorByClass(final Class clazz) {
for (Iterator it = this.responseInterceptors.iterator();
it.hasNext(); ) {
Object request = it.next();
if (request.getClass().equals(clazz)) {
it.remove();
}
}
}
public final void addInterceptor(final HttpRequestInterceptor interceptor) {
addRequestInterceptor(interceptor);
}
public final void addInterceptor(final HttpRequestInterceptor interceptor, int index) {
addRequestInterceptor(interceptor, index);
}
public int getRequestInterceptorCount() {
return this.requestInterceptors.size();
}
public HttpRequestInterceptor getRequestInterceptor(int index) {
if ((index < 0) || (index >= this.requestInterceptors.size()))
return null;
return (HttpRequestInterceptor) this.requestInterceptors.get(index);
}
public void clearRequestInterceptors() {
this.requestInterceptors.clear();
}
public void addResponseInterceptor(final HttpResponseInterceptor itcp) {
if (itcp == null) {
return;
}
this.responseInterceptors.add(itcp);
}
public final void addInterceptor(final HttpResponseInterceptor interceptor) {
addResponseInterceptor(interceptor);
}
public final void addInterceptor(final HttpResponseInterceptor interceptor, int index) {
addResponseInterceptor(interceptor, index);
}
public int getResponseInterceptorCount() {
return this.responseInterceptors.size();
}
public HttpResponseInterceptor getResponseInterceptor(int index) {
if ((index < 0) || (index >= this.responseInterceptors.size()))
return null;
return (HttpResponseInterceptor) this.responseInterceptors.get(index);
}
public void clearResponseInterceptors() {
this.responseInterceptors.clear();
}
/**
* Sets the interceptor lists.
* First, both interceptor lists maintained by this processor
* will be cleared.
* Subsequently,
* elements of the argument list that are request interceptors will be
* added to the request interceptor list.
* Elements that are response interceptors will be
* added to the response interceptor list.
* Elements that are both request and response interceptor will be
* added to both lists.
* Elements that are neither request nor response interceptor
* will be ignored.
*
* @param list the list of request and response interceptors
* from which to initialize
*/
public void setInterceptors(final List list) {
if (list == null) {
throw new IllegalArgumentException("List must not be null.");
}
this.requestInterceptors.clear();
this.responseInterceptors.clear();
for (int i = 0; i < list.size(); i++) {
Object obj = list.get(i);
if (obj instanceof HttpRequestInterceptor) {
addInterceptor((HttpRequestInterceptor)obj);
}
if (obj instanceof HttpResponseInterceptor) {
addInterceptor((HttpResponseInterceptor)obj);
}
}
}
/**
* Clears both interceptor lists maintained by this processor.
*/
public void clearInterceptors() {
clearRequestInterceptors();
clearResponseInterceptors();
}
public void process(
final HttpRequest request,
final HttpContext context)
throws IOException, HttpException {
for (int i = 0; i < this.requestInterceptors.size(); i++) {
HttpRequestInterceptor interceptor =
(HttpRequestInterceptor) this.requestInterceptors.get(i);
interceptor.process(request, context);
}
}
public void process(
final HttpResponse response,
final HttpContext context)
throws IOException, HttpException {
for (int i = 0; i < this.responseInterceptors.size(); i++) {
HttpResponseInterceptor interceptor =
(HttpResponseInterceptor) this.responseInterceptors.get(i);
interceptor.process(response, context);
}
}
/**
* Sets up the target to have the same list of interceptors
* as the current instance.
*
* @param target object to be initialised
*/
protected void copyInterceptors(final BasicHttpProcessor target) {
target.requestInterceptors.clear();
target.requestInterceptors.addAll(this.requestInterceptors);
target.responseInterceptors.clear();
target.responseInterceptors.addAll(this.responseInterceptors);
}
/**
* Creates a copy of this instance
*
* @return new instance of the BasicHttpProcessor
*/
public BasicHttpProcessor copy() {
BasicHttpProcessor clone = new BasicHttpProcessor();
copyInterceptors(clone);
return clone;
}
public Object clone() throws CloneNotSupportedException {
BasicHttpProcessor clone = (BasicHttpProcessor) super.clone();
copyInterceptors(clone);
return clone;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/BasicHttpProcessor.java | Java | gpl3 | 8,345 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.params.HttpProtocolParams;
/**
* RequestExpectContinue is responsible for enabling the 'expect-continue'
* handshake by adding <code>Expect</code> header. This interceptor is
* recommended for client side protocol processors.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#USE_EXPECT_CONTINUE}</li>
* </ul>
*
* @since 4.0
*/
public class RequestExpectContinue implements HttpRequestInterceptor {
public RequestExpectContinue() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
// Do not send the expect header if request body is known to be empty
if (entity != null && entity.getContentLength() != 0) {
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
if (HttpProtocolParams.useExpectContinue(request.getParams())
&& !ver.lessEquals(HttpVersion.HTTP_1_0)) {
request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
}
}
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/RequestExpectContinue.java | Java | gpl3 | 3,077 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
/**
* RequestConnControl is responsible for adding <code>Connection</code> header
* to the outgoing requests, which is essential for managing persistence of
* <code>HTTP/1.0</code> connections. This interceptor is recommended for
* client side protocol processors.
*
* @since 4.0
*/
public class RequestConnControl implements HttpRequestInterceptor {
public RequestConnControl() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase("CONNECT")) {
return;
}
if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) {
// Default policy is to keep connection alive
// whenever possible
request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/RequestConnControl.java | Java | gpl3 | 2,439 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.util.List;
import org.apache.ogt.http.HttpRequestInterceptor;
/**
* Provides access to an ordered list of request interceptors.
* Lists are expected to be built upfront and used read-only afterwards
* for {@link HttpProcessor processing}.
*
* @since 4.0
*/
public interface HttpRequestInterceptorList {
/**
* Appends a request interceptor to this list.
*
* @param interceptor the request interceptor to add
*/
void addRequestInterceptor(HttpRequestInterceptor interceptor);
/**
* Inserts a request interceptor at the specified index.
*
* @param interceptor the request interceptor to add
* @param index the index to insert the interceptor at
*/
void addRequestInterceptor(HttpRequestInterceptor interceptor, int index);
/**
* Obtains the current size of this list.
*
* @return the number of request interceptors in this list
*/
int getRequestInterceptorCount();
/**
* Obtains a request interceptor from this list.
*
* @param index the index of the interceptor to obtain,
* 0 for first
*
* @return the interceptor at the given index, or
* <code>null</code> if the index is out of range
*/
HttpRequestInterceptor getRequestInterceptor(int index);
/**
* Removes all request interceptors from this list.
*/
void clearRequestInterceptors();
/**
* Removes all request interceptor of the specified class
*
* @param clazz the class of the instances to be removed.
*/
void removeRequestInterceptorByClass(Class clazz);
/**
* Sets the request interceptors in this list.
* This list will be cleared and re-initialized to contain
* all request interceptors from the argument list.
* If the argument list includes elements that are not request
* interceptors, the behavior is implementation dependent.
*
* @param list the list of request interceptors
*/
void setInterceptors(List list);
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/HttpRequestInterceptorList.java | Java | gpl3 | 3,297 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.util.Map;
/**
* Maintains a map of HTTP request handlers keyed by a request URI pattern.
* <br>
* Patterns may have three formats:
* <ul>
* <li><code>*</code></li>
* <li><code>*<uri></code></li>
* <li><code><uri>*</code></li>
* </ul>
* <br>
* This class can be used to resolve an instance of
* {@link HttpRequestHandler} matching a particular request URI. Usually the
* resolved request handler will be used to process the request with the
* specified request URI.
*
* @since 4.0
*/
public class HttpRequestHandlerRegistry implements HttpRequestHandlerResolver {
private final UriPatternMatcher matcher;
public HttpRequestHandlerRegistry() {
matcher = new UriPatternMatcher();
}
/**
* Registers the given {@link HttpRequestHandler} as a handler for URIs
* matching the given pattern.
*
* @param pattern the pattern to register the handler for.
* @param handler the handler.
*/
public void register(final String pattern, final HttpRequestHandler handler) {
if (pattern == null) {
throw new IllegalArgumentException("URI request pattern may not be null");
}
if (handler == null) {
throw new IllegalArgumentException("Request handler may not be null");
}
matcher.register(pattern, handler);
}
/**
* Removes registered handler, if exists, for the given pattern.
*
* @param pattern the pattern to unregister the handler for.
*/
public void unregister(final String pattern) {
matcher.unregister(pattern);
}
/**
* Sets handlers from the given map.
* @param map the map containing handlers keyed by their URI patterns.
*/
public void setHandlers(final Map map) {
matcher.setObjects(map);
}
public HttpRequestHandler lookup(final String requestURI) {
return (HttpRequestHandler) matcher.lookup(requestURI);
}
/**
* @deprecated
*/
protected boolean matchUriRequestPattern(final String pattern, final String requestUri) {
return matcher.matchUriRequestPattern(pattern, requestUri);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/HttpRequestHandlerRegistry.java | Java | gpl3 | 3,401 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.params.CoreProtocolPNames;
/**
* ResponseServer is responsible for adding <code>Server</code> header. This
* interceptor is recommended for server side protocol processors.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#ORIGIN_SERVER}</li>
* </ul>
*
* @since 4.0
*/
public class ResponseServer implements HttpResponseInterceptor {
public ResponseServer() {
super();
}
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (!response.containsHeader(HTTP.SERVER_HEADER)) {
String s = (String) response.getParams().getParameter(
CoreProtocolPNames.ORIGIN_SERVER);
if (s != null) {
response.addHeader(HTTP.SERVER_HEADER, s);
}
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/ResponseServer.java | Java | gpl3 | 2,474 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
/**
* {@link HttpContext} attribute names for protocol execution.
*
* @since 4.0
*/
public interface ExecutionContext {
/**
* Attribute name of a {@link org.apache.ogt.http.HttpConnection} object that
* represents the actual HTTP connection.
*/
public static final String HTTP_CONNECTION = "http.connection";
/**
* Attribute name of a {@link org.apache.ogt.http.HttpRequest} object that
* represents the actual HTTP request.
*/
public static final String HTTP_REQUEST = "http.request";
/**
* Attribute name of a {@link org.apache.ogt.http.HttpResponse} object that
* represents the actual HTTP response.
*/
public static final String HTTP_RESPONSE = "http.response";
/**
* Attribute name of a {@link org.apache.ogt.http.HttpHost} object that
* represents the connection target.
*/
public static final String HTTP_TARGET_HOST = "http.target_host";
/**
* Attribute name of a {@link org.apache.ogt.http.HttpHost} object that
* represents the connection proxy.
*/
public static final String HTTP_PROXY_HOST = "http.proxy_host";
/**
* Attribute name of a {@link Boolean} object that represents the
* the flag indicating whether the actual request has been fully transmitted
* to the target host.
*/
public static final String HTTP_REQ_SENT = "http.request_sent";
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/ExecutionContext.java | Java | gpl3 | 2,650 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolVersion;
/**
* ResponseConnControl is responsible for adding <code>Connection</code> header
* to the outgoing responses, which is essential for managing persistence of
* <code>HTTP/1.0</code> connections. This interceptor is recommended for
* server side protocol processors.
*
* @since 4.0
*/
public class ResponseConnControl implements HttpResponseInterceptor {
public ResponseConnControl() {
super();
}
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
// Always drop connection after certain type of responses
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_BAD_REQUEST ||
status == HttpStatus.SC_REQUEST_TIMEOUT ||
status == HttpStatus.SC_LENGTH_REQUIRED ||
status == HttpStatus.SC_REQUEST_TOO_LONG ||
status == HttpStatus.SC_REQUEST_URI_TOO_LONG ||
status == HttpStatus.SC_SERVICE_UNAVAILABLE ||
status == HttpStatus.SC_NOT_IMPLEMENTED) {
response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
return;
}
// Always drop connection for HTTP/1.0 responses and below
// if the content body cannot be correctly delimited
HttpEntity entity = response.getEntity();
if (entity != null) {
ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
if (entity.getContentLength() < 0 &&
(!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0))) {
response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
return;
}
}
// Drop connection if requested by the client
HttpRequest request = (HttpRequest)
context.getAttribute(ExecutionContext.HTTP_REQUEST);
if (request != null) {
Header header = request.getFirstHeader(HTTP.CONN_DIRECTIVE);
if (header != null) {
response.setHeader(HTTP.CONN_DIRECTIVE, header.getValue());
}
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/ResponseConnControl.java | Java | gpl3 | 4,019 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpStatus;
/**
* ResponseDate is responsible for adding <code>Date<c/ode> header to the
* outgoing responses. This interceptor is recommended for server side protocol
* processors.
*
* @since 4.0
*/
public class ResponseDate implements HttpResponseInterceptor {
private static final HttpDateGenerator DATE_GENERATOR = new HttpDateGenerator();
public ResponseDate() {
super();
}
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException
("HTTP response may not be null.");
}
int status = response.getStatusLine().getStatusCode();
if ((status >= HttpStatus.SC_OK) &&
!response.containsHeader(HTTP.DATE_HEADER)) {
String httpdate = DATE_GENERATOR.getCurrentDate();
response.setHeader(HTTP.DATE_HEADER, httpdate);
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/ResponseDate.java | Java | gpl3 | 2,400 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
/**
* {@link HttpContext} implementation that delegates resolution of an attribute
* to the given default {@link HttpContext} instance if the attribute is not
* present in the local one. The state of the local context can be mutated,
* whereas the default context is treated as read-only.
*
* @since 4.0
*/
public final class DefaultedHttpContext implements HttpContext {
private final HttpContext local;
private final HttpContext defaults;
public DefaultedHttpContext(final HttpContext local, final HttpContext defaults) {
super();
if (local == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
this.local = local;
this.defaults = defaults;
}
public Object getAttribute(final String id) {
Object obj = this.local.getAttribute(id);
if (obj == null) {
return this.defaults.getAttribute(id);
} else {
return obj;
}
}
public Object removeAttribute(final String id) {
return this.local.removeAttribute(id);
}
public void setAttribute(final String id, final Object obj) {
this.local.setAttribute(id, obj);
}
public HttpContext getDefaults() {
return this.defaults;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/DefaultedHttpContext.java | Java | gpl3 | 2,510 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseFactory;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.MethodNotSupportedException;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.UnsupportedHttpVersionException;
import org.apache.ogt.http.entity.ByteArrayEntity;
import org.apache.ogt.http.params.DefaultedHttpParams;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.util.EncodingUtils;
import org.apache.ogt.http.util.EntityUtils;
/**
* HttpService is a server side HTTP protocol handler based in the blocking
* I/O model that implements the essential requirements of the HTTP protocol
* for the server side message processing as described by RFC 2616.
* <br>
* HttpService relies on {@link HttpProcessor} to generate mandatory protocol
* headers for all outgoing messages and apply common, cross-cutting message
* transformations to all incoming and outgoing messages, whereas individual
* {@link HttpRequestHandler}s are expected to take care of application specific
* content generation and processing.
* <br>
* HttpService relies on {@link HttpRequestHandler} to resolve matching request
* handler for a particular request URI of an incoming HTTP request.
* <br>
* HttpService can use optional {@link HttpExpectationVerifier} to ensure that
* incoming requests meet server's expectations.
*
* @since 4.0
*/
public class HttpService {
/**
* TODO: make all variables final in the next major version
*/
private volatile HttpParams params = null;
private volatile HttpProcessor processor = null;
private volatile HttpRequestHandlerResolver handlerResolver = null;
private volatile ConnectionReuseStrategy connStrategy = null;
private volatile HttpResponseFactory responseFactory = null;
private volatile HttpExpectationVerifier expectationVerifier = null;
/**
* Create a new HTTP service.
*
* @param processor the processor to use on requests and responses
* @param connStrategy the connection reuse strategy
* @param responseFactory the response factory
* @param handlerResolver the handler resolver. May be null.
* @param expectationVerifier the expectation verifier. May be null.
* @param params the HTTP parameters
*
* @since 4.1
*/
public HttpService(
final HttpProcessor processor,
final ConnectionReuseStrategy connStrategy,
final HttpResponseFactory responseFactory,
final HttpRequestHandlerResolver handlerResolver,
final HttpExpectationVerifier expectationVerifier,
final HttpParams params) {
super();
if (processor == null) {
throw new IllegalArgumentException("HTTP processor may not be null");
}
if (connStrategy == null) {
throw new IllegalArgumentException("Connection reuse strategy may not be null");
}
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.processor = processor;
this.connStrategy = connStrategy;
this.responseFactory = responseFactory;
this.handlerResolver = handlerResolver;
this.expectationVerifier = expectationVerifier;
this.params = params;
}
/**
* Create a new HTTP service.
*
* @param processor the processor to use on requests and responses
* @param connStrategy the connection reuse strategy
* @param responseFactory the response factory
* @param handlerResolver the handler resolver. May be null.
* @param params the HTTP parameters
*
* @since 4.1
*/
public HttpService(
final HttpProcessor processor,
final ConnectionReuseStrategy connStrategy,
final HttpResponseFactory responseFactory,
final HttpRequestHandlerResolver handlerResolver,
final HttpParams params) {
this(processor, connStrategy, responseFactory, handlerResolver, null, params);
}
/**
* Create a new HTTP service.
*
* @param proc the processor to use on requests and responses
* @param connStrategy the connection reuse strategy
* @param responseFactory the response factory
*
* @deprecated use {@link HttpService#HttpService(HttpProcessor,
* ConnectionReuseStrategy, HttpResponseFactory, HttpRequestHandlerResolver, HttpParams)}
*/
public HttpService(
final HttpProcessor proc,
final ConnectionReuseStrategy connStrategy,
final HttpResponseFactory responseFactory) {
super();
setHttpProcessor(proc);
setConnReuseStrategy(connStrategy);
setResponseFactory(responseFactory);
}
/**
* @deprecated set {@link HttpProcessor} using constructor
*/
public void setHttpProcessor(final HttpProcessor processor) {
if (processor == null) {
throw new IllegalArgumentException("HTTP processor may not be null");
}
this.processor = processor;
}
/**
* @deprecated set {@link ConnectionReuseStrategy} using constructor
*/
public void setConnReuseStrategy(final ConnectionReuseStrategy connStrategy) {
if (connStrategy == null) {
throw new IllegalArgumentException("Connection reuse strategy may not be null");
}
this.connStrategy = connStrategy;
}
/**
* @deprecated set {@link HttpResponseFactory} using constructor
*/
public void setResponseFactory(final HttpResponseFactory responseFactory) {
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseFactory = responseFactory;
}
/**
* @deprecated set {@link HttpResponseFactory} using constructor
*/
public void setParams(final HttpParams params) {
this.params = params;
}
/**
* @deprecated set {@link HttpRequestHandlerResolver} using constructor
*/
public void setHandlerResolver(final HttpRequestHandlerResolver handlerResolver) {
this.handlerResolver = handlerResolver;
}
/**
* @deprecated set {@link HttpExpectationVerifier} using constructor
*/
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.expectationVerifier = expectationVerifier;
}
public HttpParams getParams() {
return this.params;
}
/**
* Handles receives one HTTP request over the given connection within the
* given execution context and sends a response back to the client.
*
* @param conn the active connection to the client
* @param context the actual execution context.
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
public void handleRequest(
final HttpServerConnection conn,
final HttpContext context) throws IOException, HttpException {
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
HttpResponse response = null;
try {
HttpRequest request = conn.receiveRequestHeader();
request.setParams(
new DefaultedHttpParams(request.getParams(), this.params));
ProtocolVersion ver =
request.getRequestLine().getProtocolVersion();
if (!ver.lessEquals(HttpVersion.HTTP_1_1)) {
// Downgrade protocol version if greater than HTTP/1.1
ver = HttpVersion.HTTP_1_1;
}
if (request instanceof HttpEntityEnclosingRequest) {
if (((HttpEntityEnclosingRequest) request).expectContinue()) {
response = this.responseFactory.newHttpResponse(ver,
HttpStatus.SC_CONTINUE, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
if (this.expectationVerifier != null) {
try {
this.expectationVerifier.verify(request, response, context);
} catch (HttpException ex) {
response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0,
HttpStatus.SC_INTERNAL_SERVER_ERROR, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handleException(ex, response);
}
}
if (response.getStatusLine().getStatusCode() < 200) {
// Send 1xx response indicating the server expections
// have been met
conn.sendResponseHeader(response);
conn.flush();
response = null;
conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
}
} else {
conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
}
}
if (response == null) {
response = this.responseFactory.newHttpResponse(ver, HttpStatus.SC_OK, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);
this.processor.process(request, context);
doService(request, response, context);
}
// Make sure the request content is fully consumed
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
EntityUtils.consume(entity);
}
} catch (HttpException ex) {
response = this.responseFactory.newHttpResponse
(HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR,
context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handleException(ex, response);
}
this.processor.process(response, context);
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
conn.flush();
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
}
}
/**
* Handles the given exception and generates an HTTP response to be sent
* back to the client to inform about the exceptional condition encountered
* in the course of the request processing.
*
* @param ex the exception.
* @param response the HTTP response.
*/
protected void handleException(final HttpException ex, final HttpResponse response) {
if (ex instanceof MethodNotSupportedException) {
response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
} else if (ex instanceof UnsupportedHttpVersionException) {
response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED);
} else if (ex instanceof ProtocolException) {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
} else {
response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage());
ByteArrayEntity entity = new ByteArrayEntity(msg);
entity.setContentType("text/plain; charset=US-ASCII");
response.setEntity(entity);
}
/**
* The default implementation of this method attempts to resolve an
* {@link HttpRequestHandler} for the request URI of the given request
* and, if found, executes its
* {@link HttpRequestHandler#handle(HttpRequest, HttpResponse, HttpContext)}
* method.
* <p>
* Super-classes can override this method in order to provide a custom
* implementation of the request processing logic.
*
* @param request the HTTP request.
* @param response the HTTP response.
* @param context the execution context.
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
protected void doService(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpRequestHandler handler = null;
if (this.handlerResolver != null) {
String requestURI = request.getRequestLine().getUri();
handler = this.handlerResolver.lookup(requestURI);
}
if (handler != null) {
handler.handle(request, response, context);
} else {
response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/HttpService.java | Java | gpl3 | 15,142 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Maintains a map of objects keyed by a request URI pattern.
* <br>
* Patterns may have three formats:
* <ul>
* <li><code>*</code></li>
* <li><code>*<uri></code></li>
* <li><code><uri>*</code></li>
* </ul>
* <br>
* This class can be used to resolve an object matching a particular request
* URI.
*
* @since 4.0
*/
public class UriPatternMatcher {
/**
* TODO: Replace with ConcurrentHashMap
*/
private final Map map;
public UriPatternMatcher() {
super();
this.map = new HashMap();
}
/**
* Registers the given object for URIs matching the given pattern.
*
* @param pattern the pattern to register the handler for.
* @param obj the object.
*/
public synchronized void register(final String pattern, final Object obj) {
if (pattern == null) {
throw new IllegalArgumentException("URI request pattern may not be null");
}
this.map.put(pattern, obj);
}
/**
* Removes registered object, if exists, for the given pattern.
*
* @param pattern the pattern to unregister.
*/
public synchronized void unregister(final String pattern) {
if (pattern == null) {
return;
}
this.map.remove(pattern);
}
/**
* @deprecated use {@link #setObjects(Map)}
*/
public synchronized void setHandlers(final Map map) {
if (map == null) {
throw new IllegalArgumentException("Map of handlers may not be null");
}
this.map.clear();
this.map.putAll(map);
}
/**
* Sets objects from the given map.
* @param map the map containing objects keyed by their URI patterns.
*/
public synchronized void setObjects(final Map map) {
if (map == null) {
throw new IllegalArgumentException("Map of handlers may not be null");
}
this.map.clear();
this.map.putAll(map);
}
/**
* Looks up an object matching the given request URI.
*
* @param requestURI the request URI
* @return object or <code>null</code> if no match is found.
*/
public synchronized Object lookup(String requestURI) {
if (requestURI == null) {
throw new IllegalArgumentException("Request URI may not be null");
}
//Strip away the query part part if found
int index = requestURI.indexOf("?");
if (index != -1) {
requestURI = requestURI.substring(0, index);
}
// direct match?
Object obj = this.map.get(requestURI);
if (obj == null) {
// pattern match?
String bestMatch = null;
for (Iterator it = this.map.keySet().iterator(); it.hasNext();) {
String pattern = (String) it.next();
if (matchUriRequestPattern(pattern, requestURI)) {
// we have a match. is it any better?
if (bestMatch == null
|| (bestMatch.length() < pattern.length())
|| (bestMatch.length() == pattern.length() && pattern.endsWith("*"))) {
obj = this.map.get(pattern);
bestMatch = pattern;
}
}
}
}
return obj;
}
/**
* Tests if the given request URI matches the given pattern.
*
* @param pattern the pattern
* @param requestUri the request URI
* @return <code>true</code> if the request URI matches the pattern,
* <code>false</code> otherwise.
*/
protected boolean matchUriRequestPattern(final String pattern, final String requestUri) {
if (pattern.equals("*")) {
return true;
} else {
return
(pattern.endsWith("*") && requestUri.startsWith(pattern.substring(0, pattern.length() - 1))) ||
(pattern.startsWith("*") && requestUri.endsWith(pattern.substring(1, pattern.length())));
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/UriPatternMatcher.java | Java | gpl3 | 5,359 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.util.HashMap;
import java.util.Map;
/**
* Default implementation of {@link HttpContext}.
* <p>
* Please note methods of this class are not synchronized and therefore may
* be threading unsafe.
*
* @since 4.0
*/
public class BasicHttpContext implements HttpContext {
private final HttpContext parentContext;
private Map map = null;
public BasicHttpContext() {
this(null);
}
public BasicHttpContext(final HttpContext parentContext) {
super();
this.parentContext = parentContext;
}
public Object getAttribute(final String id) {
if (id == null) {
throw new IllegalArgumentException("Id may not be null");
}
Object obj = null;
if (this.map != null) {
obj = this.map.get(id);
}
if (obj == null && this.parentContext != null) {
obj = this.parentContext.getAttribute(id);
}
return obj;
}
public void setAttribute(final String id, final Object obj) {
if (id == null) {
throw new IllegalArgumentException("Id may not be null");
}
if (this.map == null) {
this.map = new HashMap();
}
this.map.put(id, obj);
}
public Object removeAttribute(final String id) {
if (id == null) {
throw new IllegalArgumentException("Id may not be null");
}
if (this.map != null) {
return this.map.remove(id);
} else {
return null;
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/protocol/BasicHttpContext.java | Java | gpl3 | 2,767 |