code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpResponseFactory;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpResponseFactory;
import org.apache.ogt.http.impl.DefaultHttpServerConnection;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.BasicHttpProcessor;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpExpectationVerifier;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.protocol.HttpRequestHandlerRegistry;
import org.apache.ogt.http.protocol.HttpService;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.ResponseConnControl;
import org.apache.ogt.http.protocol.ResponseContent;
import org.apache.ogt.http.protocol.ResponseDate;
import org.apache.ogt.http.protocol.ResponseServer;
/**
* Local HTTP server for tests that require one.
* Based on the <code>ElementalHttpServer</code> example in HttpCore.
*/
public class LocalTestServer {
/**
* The local address to bind to.
* The host is an IP number rather than "localhost" to avoid surprises
* on hosts that map "localhost" to an IPv6 address or something else.
* The port is 0 to let the system pick one.
*/
public final static InetSocketAddress TEST_SERVER_ADDR =
new InetSocketAddress("127.0.0.1", 0);
/** The request handler registry. */
private final HttpRequestHandlerRegistry handlerRegistry;
private final HttpService httpservice;
/** Optional SSL context */
private final SSLContext sslcontext;
/** The server socket, while being served. */
private volatile ServerSocket servicedSocket;
/** The request listening thread, while listening. */
private volatile ListenerThread listenerThread;
/** Set of active worker threads */
private final Set<Worker> workers;
/** The number of connections this accepted. */
private final AtomicInteger acceptedConnections = new AtomicInteger(0);
/**
* Creates a new test server.
*
* @param proc the HTTP processors to be used by the server, or
* <code>null</code> to use a
* {@link #newProcessor default} processor
* @param reuseStrat the connection reuse strategy to be used by the
* server, or <code>null</code> to use
* {@link #newConnectionReuseStrategy() default}
* strategy.
* @param params the parameters to be used by the server, or
* <code>null</code> to use
* {@link #newDefaultParams default} parameters
* @param sslcontext optional SSL context if the server is to leverage
* SSL/TLS transport security
*/
public LocalTestServer(
final BasicHttpProcessor proc,
final ConnectionReuseStrategy reuseStrat,
final HttpResponseFactory responseFactory,
final HttpExpectationVerifier expectationVerifier,
final HttpParams params,
final SSLContext sslcontext) {
super();
this.handlerRegistry = new HttpRequestHandlerRegistry();
this.workers = Collections.synchronizedSet(new HashSet<Worker>());
this.httpservice = new HttpService(
proc != null ? proc : newProcessor(),
reuseStrat != null ? reuseStrat: newConnectionReuseStrategy(),
responseFactory != null ? responseFactory: newHttpResponseFactory(),
handlerRegistry,
expectationVerifier,
params != null ? params : newDefaultParams());
this.sslcontext = sslcontext;
}
/**
* Creates a new test server with SSL/TLS encryption.
*
* @param sslcontext SSL context
*/
public LocalTestServer(final SSLContext sslcontext) {
this(null, null, null, null, null, sslcontext);
}
/**
* Creates a new test server.
*
* @param proc the HTTP processors to be used by the server, or
* <code>null</code> to use a
* {@link #newProcessor default} processor
* @param params the parameters to be used by the server, or
* <code>null</code> to use
* {@link #newDefaultParams default} parameters
*/
public LocalTestServer(
BasicHttpProcessor proc,
HttpParams params) {
this(proc, null, null, null, params, null);
}
/**
* Obtains an HTTP protocol processor with default interceptors.
*
* @return a protocol processor for server-side use
*/
protected HttpProcessor newProcessor() {
return new ImmutableHttpProcessor(
new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
}
/**
* Obtains a set of reasonable default parameters for a server.
*
* @return default parameters
*/
protected HttpParams newDefaultParams() {
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER,
"LocalTestServer/1.1");
return params;
}
protected ConnectionReuseStrategy newConnectionReuseStrategy() {
return new DefaultConnectionReuseStrategy();
}
protected HttpResponseFactory newHttpResponseFactory() {
return new DefaultHttpResponseFactory();
}
/**
* Returns the number of connections this test server has accepted.
*/
public int getAcceptedConnectionCount() {
return acceptedConnections.get();
}
/**
* {@link #register Registers} a set of default request handlers.
* <pre>
* URI pattern Handler
* ----------- -------
* /echo/* {@link EchoHandler EchoHandler}
* /random/* {@link RandomHandler RandomHandler}
* </pre>
*/
public void registerDefaultHandlers() {
handlerRegistry.register("/echo/*", new EchoHandler());
handlerRegistry.register("/random/*", new RandomHandler());
}
/**
* Registers a handler with the local registry.
*
* @param pattern the URL pattern to match
* @param handler the handler to apply
*/
public void register(String pattern, HttpRequestHandler handler) {
handlerRegistry.register(pattern, handler);
}
/**
* Unregisters a handler from the local registry.
*
* @param pattern the URL pattern
*/
public void unregister(String pattern) {
handlerRegistry.unregister(pattern);
}
/**
* Starts this test server.
*/
public void start() throws Exception {
if (servicedSocket != null) {
throw new IllegalStateException(this.toString() + " already running");
}
ServerSocket ssock;
if (sslcontext != null) {
SSLServerSocketFactory sf = sslcontext.getServerSocketFactory();
ssock = sf.createServerSocket();
} else {
ssock = new ServerSocket();
}
ssock.setReuseAddress(true); // probably pointless for port '0'
ssock.bind(TEST_SERVER_ADDR);
servicedSocket = ssock;
listenerThread = new ListenerThread();
listenerThread.setDaemon(false);
listenerThread.start();
}
/**
* Stops this test server.
*/
public void stop() throws Exception {
if (servicedSocket == null) {
return; // not running
}
ListenerThread t = listenerThread;
if (t != null) {
t.shutdown();
}
synchronized (workers) {
for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) {
Worker worker = it.next();
worker.shutdown();
}
}
}
public void awaitTermination(long timeMs) throws InterruptedException {
if (listenerThread != null) {
listenerThread.join(timeMs);
}
}
@Override
public String toString() {
ServerSocket ssock = servicedSocket; // avoid synchronization
StringBuilder sb = new StringBuilder(80);
sb.append("LocalTestServer/");
if (ssock == null)
sb.append("stopped");
else
sb.append(ssock.getLocalSocketAddress());
return sb.toString();
}
/**
* Obtains the local address the server is listening on
*
* @return the service address
*/
public InetSocketAddress getServiceAddress() {
ServerSocket ssock = servicedSocket; // avoid synchronization
if (ssock == null) {
throw new IllegalStateException("not running");
}
return (InetSocketAddress) ssock.getLocalSocketAddress();
}
/**
* The request listener.
* Accepts incoming connections and launches a service thread.
*/
class ListenerThread extends Thread {
private volatile Exception exception;
ListenerThread() {
super();
}
@Override
public void run() {
try {
while (!interrupted()) {
Socket socket = servicedSocket.accept();
acceptedConnections.incrementAndGet();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(socket, httpservice.getParams());
// Start worker thread
Worker worker = new Worker(conn);
workers.add(worker);
worker.setDaemon(true);
worker.start();
}
} catch (Exception ex) {
this.exception = ex;
} finally {
try {
servicedSocket.close();
} catch (IOException ignore) {
}
}
}
public void shutdown() {
interrupt();
try {
servicedSocket.close();
} catch (IOException ignore) {
}
}
public Exception getException() {
return this.exception;
}
}
class Worker extends Thread {
private final HttpServerConnection conn;
private volatile Exception exception;
public Worker(final HttpServerConnection conn) {
this.conn = conn;
}
@Override
public void run() {
HttpContext context = new BasicHttpContext();
try {
while (this.conn.isOpen() && !Thread.interrupted()) {
httpservice.handleRequest(this.conn, context);
}
} catch (Exception ex) {
this.exception = ex;
} finally {
workers.remove(this);
try {
this.conn.shutdown();
} catch (IOException ignore) {
}
}
}
public void shutdown() {
interrupt();
try {
this.conn.shutdown();
} catch (IOException ignore) {
}
}
public Exception getException() {
return this.exception;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import org.apache.commons.codec.BinaryDecoder;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.util.EncodingUtils;
public class BasicAuthTokenExtractor {
public String extract(final HttpRequest request) throws HttpException {
String auth = null;
Header h = request.getFirstHeader(AUTH.WWW_AUTH_RESP);
if (h != null) {
String s = h.getValue();
if (s != null) {
auth = s.trim();
}
}
if (auth != null) {
int i = auth.indexOf(' ');
if (i == -1) {
throw new ProtocolException("Invalid Authorization header: " + auth);
}
String authscheme = auth.substring(0, i);
if (authscheme.equalsIgnoreCase("basic")) {
String s = auth.substring(i + 1).trim();
try {
byte[] credsRaw = EncodingUtils.getAsciiBytes(s);
BinaryDecoder codec = new Base64();
auth = EncodingUtils.getAsciiString(codec.decode(credsRaw));
} catch (DecoderException ex) {
throw new ProtocolException("Malformed BASIC credentials");
}
}
}
return auth;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.net.InetSocketAddress;
import org.apache.ogt.http.HttpHost;
import org.junit.After;
/**
* Base class for tests using {@link LocalTestServer}. The server will not be started
* per default.
*/
public abstract class BasicServerTestBase {
/** The local server for testing. */
protected LocalTestServer localServer;
@After
public void tearDown() throws Exception {
if (localServer != null) {
localServer.stop();
}
}
/**
* Obtains the address of the local test server.
*
* @return the test server host, with a scheme name of "http"
*/
protected HttpHost getServerHttp() {
InetSocketAddress address = localServer.getServiceAddress();
return new HttpHost(
address.getHostName(),
address.getPort(),
"http");
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.conn.scheme.PlainSocketFactory;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.conn.scheme.SchemeSocketFactory;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.BasicHttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.junit.Before;
/**
* Base class for tests using {@link LocalTestServer LocalTestServer}.
* Note that the test server will be {@link #setUp set up} before each
* individual tests and {@link #tearDown teared down} afterwards.
* Use this base class <i>exclusively</i> for tests that require the
* server. If you have some tests that require the server and others
* that don't, split them in two different classes.
*/
public abstract class ServerTestBase extends BasicServerTestBase {
/** The available schemes. */
protected SchemeRegistry supportedSchemes;
/** The default parameters for the client side. */
protected HttpParams defaultParams;
/** The HTTP processor for the client side. */
protected BasicHttpProcessor httpProcessor;
/** The default context for the client side. */
protected BasicHttpContext httpContext;
/** The request executor for the client side. */
protected HttpRequestExecutor httpExecutor;
/**
* Prepares the local server for testing.
* Derived classes that override this method MUST call
* the implementation here. That SHOULD be done at the
* beginning of the overriding method.
* <br/>
* Derived methods can modify for example the default parameters
* being set up, or the interceptors.
* <p>
* This method will re-use the helper objects from a previous run
* if they are still available. For example, the local test server
* will be re-started rather than re-created.
* {@link #httpContext httpContext} will always be re-created.
* Tests that modify the other helper objects should afterwards
* set the respective attributes to <code>null</code> in a
* <code>finally{}</code> block to force re-creation for
* subsequent tests.
* Of course that shouldn't be done with the test server,
* or only after shutting that down.
*
* @throws Exception in case of a problem
*/
@Before
public void setUp() throws Exception {
if (defaultParams == null) {
defaultParams = new SyncBasicHttpParams();
HttpProtocolParams.setVersion
(defaultParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset
(defaultParams, "UTF-8");
HttpProtocolParams.setUserAgent
(defaultParams, "TestAgent/1.1");
HttpProtocolParams.setUseExpectContinue
(defaultParams, false);
}
if (supportedSchemes == null) {
supportedSchemes = new SchemeRegistry();
SchemeSocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", 80, sf));
}
if (httpProcessor == null) {
httpProcessor = new BasicHttpProcessor();
httpProcessor.addInterceptor(new RequestContent());
httpProcessor.addInterceptor(new RequestConnControl()); // optional
}
// the context is created each time, it may get modified by test cases
httpContext = new BasicHttpContext(null);
if (httpExecutor == null) {
httpExecutor = new HttpRequestExecutor();
}
if (localServer == null) {
localServer = new LocalTestServer(null, null);
localServer.registerDefaultHandlers();
}
localServer.start();
} // setUp
/**
* Opens a connection to the given target using
* {@link #defaultParams default parameters}.
* Maps to {@link #connectTo(HttpHost,HttpParams)
* connectTo(target,defaultParams)}.
*
* @param target the target to connect to
*
* @return a new connection opened to the target
*
* @throws Exception in case of a problem
*/
protected DefaultHttpClientConnection connectTo(HttpHost target)
throws Exception {
return connectTo(target, defaultParams);
}
/**
* Opens a connection to the given target using the given parameters.
*
* @param target the target to connect to
*
* @return a new connection opened to the target
*
* @throws Exception in case of a problem
*/
protected DefaultHttpClientConnection connectTo(HttpHost target,
HttpParams params)
throws Exception {
Scheme schm = supportedSchemes.get(target.getSchemeName());
int port = schm.resolvePort(target.getPort());
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
InetSocketAddress address = new InetSocketAddress(
InetAddress.getByName(target.getHostName()), port);
Socket sock = schm.getSchemeSocketFactory().connectSocket(null, address, null, params);
conn.bind(sock, params);
return conn;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.protocol.HttpContext;
public class RequestBasicAuth implements HttpRequestInterceptor {
private final BasicAuthTokenExtractor authTokenExtractor;
public RequestBasicAuth() {
super();
this.authTokenExtractor = new BasicAuthTokenExtractor();
}
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
context.setAttribute("creds", this.authTokenExtractor.extract(request));
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.io.IOException;
import java.util.Locale;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.MethodNotSupportedException;
import org.apache.ogt.http.entity.ByteArrayEntity;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.util.EntityUtils;
/**
* A handler that echos the incoming request entity.
*
*
*
* <!-- empty lines to avoid 'svn diff' problems -->
*/
public class EchoHandler
implements HttpRequestHandler {
// public default constructor
/**
* Handles a request by echoing the incoming request entity.
* If there is no request entity, an empty document is returned.
*
* @param request the request
* @param response the response
* @param context the context
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
public void handle(final HttpRequest request,
final HttpResponse response,
final HttpContext context)
throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!"GET".equals(method) &&
!"POST".equals(method) &&
!"PUT".equals(method)
) {
throw new MethodNotSupportedException
(method + " not supported by " + getClass().getName());
}
HttpEntity entity = null;
if (request instanceof HttpEntityEnclosingRequest)
entity = ((HttpEntityEnclosingRequest)request).getEntity();
// For some reason, just putting the incoming entity into
// the response will not work. We have to buffer the message.
byte[] data;
if (entity == null) {
data = new byte [0];
} else {
data = EntityUtils.toByteArray(entity);
}
ByteArrayEntity bae = new ByteArrayEntity(data);
if (entity != null) {
bae.setContentType(entity.getContentType());
}
entity = bae;
response.setStatusCode(HttpStatus.SC_OK);
response.setEntity(entity);
} // handle
} // class EchoHandler
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
/**
* This example demonstrates the recommended way of using API to make sure
* the underlying connection gets released back to the connection manager.
*/
public class ClientConnectionRelease {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://www.apache.org/");
// Execute HTTP request
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println("----------------------------------------");
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to bother about connection release
if (entity != null) {
InputStream instream = entity.getContent();
try {
instream.read();
// do something useful with the response
} catch (IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;
} catch (RuntimeException ex) {
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection immediately.
httpget.abort();
throw ex;
} finally {
// Closing the input stream will trigger connection release
try { instream.close(); } catch (Exception ignore) {}
}
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.util.ArrayList;
import java.util.List;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.client.entity.UrlEncodedFormEntity;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.methods.HttpPost;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.message.BasicNameValuePair;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.util.EntityUtils;
/**
* A example that demonstrates how HttpClient APIs can be used to perform
* form-based logon.
*/
public class ClientFormLogin {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
EntityUtils.consume(entity);
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
"org=self_registered_users&" +
"goto=/portal/dt&" +
"gotoOnFail=/portal/dt?error=true");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "username"));
nvps.add(new BasicNameValuePair("IDToken2", "password"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
EntityUtils.consume(entity);
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* An example that performs GETs from multiple threads.
*
*/
public class ClientMultiThreadedExecution {
public static void main(String[] args) throws Exception {
// Create an HttpClient with the ThreadSafeClientConnManager.
// This connection manager must be used if more than one thread will
// be using the HttpClient.
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
cm.setMaxTotal(100);
HttpClient httpclient = new DefaultHttpClient(cm);
try {
// create an array of URIs to perform GETs on
String[] urisToGet = {
"http://hc.apache.org/",
"http://hc.apache.org/httpcomponents-core-ga/",
"http://hc.apache.org/httpcomponents-client-ga/",
"http://svn.apache.org/viewvc/httpcomponents/"
};
// create a thread for each URI
GetThread[] threads = new GetThread[urisToGet.length];
for (int i = 0; i < threads.length; i++) {
HttpGet httpget = new HttpGet(urisToGet[i]);
threads[i] = new GetThread(httpclient, httpget, i + 1);
}
// start the threads
for (int j = 0; j < threads.length; j++) {
threads[j].start();
}
// join the threads
for (int j = 0; j < threads.length; j++) {
threads[j].join();
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
/**
* A thread that performs a GET.
*/
static class GetThread extends Thread {
private final HttpClient httpClient;
private final HttpContext context;
private final HttpGet httpget;
private final int id;
public GetThread(HttpClient httpClient, HttpGet httpget, int id) {
this.httpClient = httpClient;
this.context = new BasicHttpContext();
this.httpget = httpget;
this.id = id;
}
/**
* Executes the GetMethod and prints some status information.
*/
@Override
public void run() {
System.out.println(id + " - about to get something from " + httpget.getURI());
try {
// execute the method
HttpResponse response = httpClient.execute(httpget, context);
System.out.println(id + " - get executed");
// get the response body as an array of bytes
HttpEntity entity = response.getEntity();
if (entity != null) {
byte[] bytes = EntityUtils.toByteArray(entity);
System.out.println(id + " - " + bytes.length + " bytes read");
}
} catch (Exception e) {
httpget.abort();
System.out.println(id + " - error: " + e);
}
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.ssl.SSLSocketFactory;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* This example demonstrates how to create secure connections with a custom SSL
* context.
*/
public class ClientCustomSSL {
public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("my.keystore"));
try {
trustStore.load(instream, "nopassword".toCharArray());
} finally {
try { instream.close(); } catch (Exception ignore) {}
}
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
Scheme sch = new Scheme("https", 443, socketFactory);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
HttpGet httpget = new HttpGet("https://localhost/");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.conn.ConnectTimeoutException;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeSocketFactory;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.util.EntityUtils;
/**
* How to send a request via SOCKS proxy using {@link HttpClient}.
*
* @since 4.1
*/
public class ClientExecuteSOCKS {
public static void main(String[] args)throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getParams().setParameter("socks.host", "mysockshost");
httpclient.getParams().setParameter("socks.port", 1234);
httpclient.getConnectionManager().getSchemeRegistry().register(
new Scheme("http", 80, new MySchemeSocketFactory()));
HttpHost target = new HttpHost("www.apache.org", 80, "http");
HttpGet req = new HttpGet("/");
System.out.println("executing request to " + target + " via SOCKS proxy");
HttpResponse rsp = httpclient.execute(target, req);
HttpEntity entity = rsp.getEntity();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
static class MySchemeSocketFactory implements SchemeSocketFactory {
public Socket createSocket(final HttpParams params) throws IOException {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
String proxyHost = (String) params.getParameter("socks.host");
Integer proxyPort = (Integer) params.getParameter("socks.port");
InetSocketAddress socksaddr = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
return new Socket(proxy);
}
public Socket connectSocket(
final Socket socket,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpParams params)
throws IOException, UnknownHostException, ConnectTimeoutException {
if (remoteAddress == null) {
throw new IllegalArgumentException("Remote address may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
Socket sock;
if (socket != null) {
sock = socket;
} else {
sock = createSocket(params);
}
if (localAddress != null) {
sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
sock.bind(localAddress);
}
int timeout = HttpConnectionParams.getConnectionTimeout(params);
try {
sock.connect(remoteAddress, timeout);
} catch (SocketTimeoutException ex) {
throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
+ remoteAddress.getAddress() + " timed out");
}
return sock;
}
public boolean isSecure(final Socket sock) throws IllegalArgumentException {
return false;
}
}
} | Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.client.ResponseHandler;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.impl.client.BasicResponseHandler;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
/**
* This example demonstrates the use of the {@link ResponseHandler} to simplify
* the process of processing the HTTP response and releasing associated resources.
*/
public class ClientWithResponseHandler {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://www.google.com/");
System.out.println("executing request " + httpget.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
System.out.println("----------------------------------------");
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.util.List;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.CookieStore;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.impl.client.BasicCookieStore;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* This example demonstrates the use of a local HTTP context populated with
* custom attributes.
*/
public class ClientCustomContext {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet("http://www.google.com/");
System.out.println("executing request " + httpget.getURI());
// Pass local context as a parameter
HttpResponse response = httpclient.execute(httpget, localContext);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
System.out.println("Local cookie: " + cookies.get(i));
}
// Consume response content
EntityUtils.consume(entity);
System.out.println("----------------------------------------");
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.AuthState;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* A simple example that uses HttpClient to execute an HTTP request against
* a target site that requires user authentication.
*/
public class ClientInteractiveAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
// Create local execution context
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("http://localhost/test");
boolean trying = true;
while (trying) {
System.out.println("executing request " + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget, localContext);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
// Consume response content
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
int sc = response.getStatusLine().getStatusCode();
AuthState authState = null;
if (sc == HttpStatus.SC_UNAUTHORIZED) {
// Target host authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
}
if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
// Proxy authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
}
if (authState != null) {
System.out.println("----------------------------------------");
AuthScope authScope = authState.getAuthScope();
System.out.println("Please provide credentials");
System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort());
System.out.println(" Realm: " + authScope.getRealm());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter username: ");
String user = console.readLine();
System.out.print("Enter password: ");
String password = console.readLine();
if (user != null && user.length() > 0) {
Credentials creds = new UsernamePasswordCredentials(user, password);
httpclient.getCredentialsProvider().setCredentials(authScope, creds);
trying = true;
} else {
trying = false;
}
} else {
trying = false;
}
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* A simple example that uses HttpClient to execute an HTTP request against
* a target site that requires user authentication.
*/
public class ClientAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
HttpGet httpget = new HttpGet("https://localhost/protected");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import java.security.Principal;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.methods.HttpUriRequest;
import org.apache.ogt.http.client.params.AuthPolicy;
import org.apache.ogt.http.impl.auth.NegotiateSchemeFactory;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* Kerberos auth example.
*
* <p><b>Information</b></p>
* <p>For the best compatibility use Java >= 1.6 as it supports SPNEGO authentication more
completely.</p>
* <p><em>NegotiateSchemeFactory</em> kas two custom methods</p>
* <p><em>#setStripPort(boolean)</em> - default is false, with strip the port off the Kerberos
* service name if true. Found useful with JBoss Negotiation. Can be used with Java >= 1.5</p>
* <p><em>#setSpengoGenerator(SpnegoTokenGenerator)</em> - default is null, class to use to wrap
* kerberos token. An example is in contrib - <em>org.apache.ogt.http.contrib.auth.BouncySpnegoTokenGenerator</em>.
* Requires use of <a href="http://www.bouncycastle.org/java.html">bouncy castle libs</a>.
* Useful with Java 1.5.
* </p>
* <p><b>Addtional Config Files</b></p>
* <p>Two files control how Java uses/configures Kerberos. Very basic examples are below. There
* is a large amount of information on the web.</p>
* <p><a href="http://java.sun.com/j2se/1.5.0/docs/guide/security/jaas/spec/com/sun/security/auth/module/Krb5LoginModule.html">http://java.sun.com/j2se/1.5.0/docs/guide/security/jaas/spec/com/sun/security/auth/module/Krb5LoginModule.html</a>
* <p><b>krb5.conf</b></p>
* <pre>
* [libdefaults]
* default_realm = AD.EXAMPLE.NET
* udp_preference_limit = 1
* [realms]
* AD.EXAMPLE.NET = {
* kdc = AD.EXAMPLE.NET
* }
* DEV.EXAMPLE.NET = {
* kdc = DEV.EXAMPLE.NET
* }
* [domain_realms]
* .ad.example.net = AD.EXAMPLE.NET
* ad.example.net = AD.EXAMPLE.NET
* .dev.example.net = DEV.EXAMPLE.NET
* dev.example.net = DEV.EXAMPLE.NET
* gb.dev.example.net = DEV.EXAMPLE.NET
* .gb.dev.example.net = DEV.EXAMPLE.NET
* </pre>
* <b>login.conf</b>
* <pre>
*com.sun.security.jgss.login {
* com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true debug=true;
*};
*
*com.sun.security.jgss.initiate {
* com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true debug=true;
*};
*
*com.sun.security.jgss.accept {
* com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true debug=true;
*};
* </pre>
* <p><b>Windows specific configuration</b></p>
* <p>
* The registry key <em>allowtgtsessionkey</em> should be added, and set correctly, to allow
* session keys to be sent in the Kerberos Ticket-Granting Ticket.
* </p>
* <p>
* On the Windows Server 2003 and Windows 2000 SP4, here is the required registry setting:
* </p>
* <pre>
* HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\Parameters
* Value Name: allowtgtsessionkey
* Value Type: REG_DWORD
* Value: 0x01
* </pre>
* <p>
* Here is the location of the registry setting on Windows XP SP2:
* </p>
* <pre>
* HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\
* Value Name: allowtgtsessionkey
* Value Type: REG_DWORD
* Value: 0x01
* </pre>
*
* @since 4.1
*/
public class ClientKerberosAuthentication {
public static void main(String[] args) throws Exception {
System.setProperty("java.security.auth.login.config", "login.conf");
System.setProperty("java.security.krb5.conf", "krb5.conf");
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
NegotiateSchemeFactory nsf = new NegotiateSchemeFactory();
// nsf.setStripPort(false);
// nsf.setSpengoGenerator(new BouncySpnegoTokenGenerator());
httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, nsf);
Credentials use_jaas_creds = new Credentials() {
public String getPassword() {
return null;
}
public Principal getUserPrincipal() {
return null;
}
};
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(null, -1, null),
use_jaas_creds);
HttpUriRequest request = new HttpGet("http://kerberoshost/");
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
System.out.println("----------------------------------------");
// This ensures the connection gets released back to the manager
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.conn.params.ConnRoutePNames;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* A simple example that uses HttpClient to execute an HTTP request
* over a secure connection tunneled through an authenticating proxy.
*/
public class ClientProxyAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 8080),
new UsernamePasswordCredentials("username", "password"));
HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https");
HttpHost proxy = new HttpHost("localhost", 8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("via proxy: " + proxy);
System.out.println("to target: " + targetHost);
HttpResponse response = httpclient.execute(targetHost, httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* How to send a request directly using {@link HttpClient}.
*
* @since 4.0
*/
public class ClientExecuteDirect {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpHost target = new HttpHost("www.apache.org", 80, "http");
HttpGet req = new HttpGet("/");
System.out.println("executing request to " + target);
HttpResponse rsp = httpclient.execute(target, req);
HttpEntity entity = rsp.getEntity();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.AuthCache;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.impl.auth.BasicScheme;
import org.apache.ogt.http.impl.client.BasicAuthCache;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* An example of HttpClient can be customized to authenticate
* preemptively using BASIC scheme.
* <b/>
* Generally, preemptive authentication can be considered less
* secure than a response to an authentication challenge
* and therefore discouraged.
*/
public class ClientPreemptiveBasicAuthentication {
public static void main(String[] args) throws Exception {
HttpHost targetHost = new HttpHost("localhost", 80, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local
// auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.HttpEntity;
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;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.entity.HttpEntityWrapper;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* Demonstration of the use of protocol interceptors to transparently
* modify properties of HTTP messages sent / received by the HTTP client.
* <p/>
* In this particular case HTTP client is made capable of transparent content
* GZIP compression by adding two protocol interceptors: a request interceptor
* that adds 'Accept-Encoding: gzip' header to all outgoing requests and
* a response interceptor that automatically expands compressed response
* entities by wrapping them with a uncompressing decorator class. The use of
* protocol interceptors makes content compression completely transparent to
* the consumer of the {@link org.apache.ogt.http.client.HttpClient HttpClient}
* interface.
*/
public class ClientGZipContentCompression {
public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
}
});
httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpEntity entity = response.getEntity();
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")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
HttpGet httpget = new HttpGet("http://www.apache.org/");
// Execute HTTP request
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(response.getLastHeader("Content-Encoding"));
System.out.println(response.getLastHeader("Content-Length"));
System.out.println("----------------------------------------");
HttpEntity entity = response.getEntity();
if (entity != null) {
String content = EntityUtils.toString(entity);
System.out.println(content);
System.out.println("----------------------------------------");
System.out.println("Uncompressed size: "+content.length());
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
static class 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 is not known
return -1;
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.util.concurrent.TimeUnit;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.ogt.http.util.EntityUtils;
/**
* Example demonstrating how to evict expired and idle connections
* from the connection pool.
*/
public class ClientEvictExpiredConnections {
public static void main(String[] args) throws Exception {
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
cm.setMaxTotal(100);
HttpClient httpclient = new DefaultHttpClient(cm);
try {
// create an array of URIs to perform GETs on
String[] urisToGet = {
"http://jakarta.apache.org/",
"http://jakarta.apache.org/commons/",
"http://jakarta.apache.org/commons/httpclient/",
"http://svn.apache.org/viewvc/jakarta/httpcomponents/"
};
IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
connEvictor.start();
for (int i = 0; i < urisToGet.length; i++) {
String requestURI = urisToGet[i];
HttpGet req = new HttpGet(requestURI);
System.out.println("executing request " + requestURI);
HttpResponse rsp = httpclient.execute(req);
HttpEntity entity = rsp.getEntity();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
EntityUtils.consume(entity);
}
// Sleep 10 sec and let the connection evictor do its job
Thread.sleep(20000);
// Shut down the evictor thread
connEvictor.shutdown();
connEvictor.join();
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
public static class IdleConnectionEvictor extends Thread {
private final ClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionEvictor(ClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 5 sec
connMgr.closeIdleConnections(5, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.AuthCache;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.impl.auth.DigestScheme;
import org.apache.ogt.http.impl.client.BasicAuthCache;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* An example of HttpClient can be customized to authenticate
* preemptively using DIGEST scheme.
* <b/>
* Generally, preemptive authentication can be considered less
* secure than a response to an authentication challenge
* and therefore discouraged.
*/
public class ClientPreemptiveDigestAuthentication {
public static void main(String[] args) throws Exception {
HttpHost targetHost = new HttpHost("localhost", 80, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate DIGEST scheme object, initialize it and add it to the local
// auth cache
DigestScheme digestAuth = new DigestScheme();
// Suppose we already know the realm name
digestAuth.overrideParamter("realm", "some realm");
// Suppose we already know the expected nonce value
digestAuth.overrideParamter("nonce", "whatever");
authCache.put(targetHost, digestAuth);
// Add AuthCache to the execution context
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
/**
* This example demonstrates how to abort an HTTP method before its normal completion.
*/
public class ClientAbortMethod {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://www.apache.org/");
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
// Do not feel like reading the response body
// Call abort on the request object
httpget.abort();
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.io.File;
import java.io.FileInputStream;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpPost;
import org.apache.ogt.http.entity.InputStreamEntity;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* Example how to use unbuffered chunk-encoded POST request.
*/
public class ClientChunkEncodedPost {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
File file = new File(args[0]);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
// It may be more appropriate to use FileEntity class in this particular
// instance but we are using a more generic InputStreamEntity to demonstrate
// the capability to stream out data from any arbitrary source
//
// FileEntity entity = new FileEntity(file, "binary/octet-stream");
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Chunked?: " + resEntity.isChunked());
}
EntityUtils.consume(resEntity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.conn.params.ConnRoutePNames;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* How to send a request via proxy using {@link HttpClient}.
*
* @since 4.0
*/
public class ClientExecuteProxy {
public static void main(String[] args)throws Exception {
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpHost target = new HttpHost("issues.apache.org", 443, "https");
HttpGet req = new HttpGet("/");
System.out.println("executing request to " + target + " via " + proxy);
HttpResponse rsp = httpclient.execute(target, req);
HttpEntity entity = rsp.getEntity();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
} | Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.conn;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.conn.scheme.PlainSocketFactory;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.conn.scheme.SchemeSocketFactory;
import org.apache.ogt.http.conn.ClientConnectionRequest;
import org.apache.ogt.http.conn.ManagedClientConnection;
import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.ogt.http.message.BasicHttpRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
/**
* How to open a direct connection using
* {@link ClientConnectionManager ClientConnectionManager}.
* This exemplifies the <i>opening</i> of the connection only.
* The subsequent message exchange in this example should not
* be used as a template.
*
* @since 4.0
*/
public class ManagerConnectDirect {
/**
* Main entry point to this example.
*
* @param args ignored
*/
public final static void main(String[] args) throws Exception {
HttpHost target = new HttpHost("www.apache.org", 80, "http");
// Register the "http" protocol scheme, it is required
// by the default operator to look up socket factories.
SchemeRegistry supportedSchemes = new SchemeRegistry();
SchemeSocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", 80, sf));
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
ClientConnectionManager clcm = new ThreadSafeClientConnManager(supportedSchemes);
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
System.out.println("preparing route to " + target);
HttpRoute route = new HttpRoute
(target, null, supportedSchemes.getScheme(target).isLayered());
System.out.println("requesting connection for " + route);
ClientConnectionRequest connRequest = clcm.requestConnection(route, null);
ManagedClientConnection conn = connRequest.getConnection(0, null);
try {
System.out.println("opening connection");
conn.open(route, ctx, params);
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i=0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
System.out.println("closing connection");
conn.close();
} finally {
if (conn.isOpen()) {
System.out.println("shutting down connection");
try {
conn.shutdown();
} catch (Exception ex) {
System.out.println("problem during shutdown");
ex.printStackTrace();
}
}
System.out.println("releasing connection");
clcm.releaseConnection(conn, -1, null);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.conn;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.conn.ClientConnectionRequest;
import org.apache.ogt.http.conn.ManagedClientConnection;
import org.apache.ogt.http.conn.scheme.PlainSocketFactory;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.conn.ssl.SSLSocketFactory;
import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.ogt.http.message.BasicHttpRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
/**
* How to open a secure connection through a proxy using
* {@link ClientConnectionManager ClientConnectionManager}.
* This exemplifies the <i>opening</i> of the connection only.
* The message exchange, both subsequently and for tunnelling,
* should not be used as a template.
*
* @since 4.0
*/
public class ManagerConnectProxy {
/**
* Main entry point to this example.
*
* @param args ignored
*/
public final static void main(String[] args) throws Exception {
// make sure to use a proxy that supports CONNECT
HttpHost target = new HttpHost("issues.apache.org", 443, "https");
HttpHost proxy = new HttpHost("127.0.0.1", 8666, "http");
// Register the "http" and "https" protocol schemes, they are
// required by the default operator to look up socket factories.
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
ClientConnectionManager clcm = new ThreadSafeClientConnManager(supportedSchemes);
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
System.out.println("preparing route to " + target + " via " + proxy);
HttpRoute route = new HttpRoute
(target, null, proxy,
supportedSchemes.getScheme(target).isLayered());
System.out.println("requesting connection for " + route);
ClientConnectionRequest connRequest = clcm.requestConnection(route, null);
ManagedClientConnection conn = connRequest.getConnection(0, null);
try {
System.out.println("opening connection");
conn.open(route, ctx, params);
String authority = target.getHostName() + ":" + target.getPort();
HttpRequest connect = new BasicHttpRequest("CONNECT", authority, HttpVersion.HTTP_1_1);
connect.addHeader("Host", authority);
System.out.println("opening tunnel to " + target);
conn.sendRequestHeader(connect);
// there is no request entity
conn.flush();
System.out.println("receiving confirmation for tunnel");
HttpResponse connected = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
System.out.println(connected.getStatusLine());
Header[] headers = connected.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
int status = connected.getStatusLine().getStatusCode();
if ((status < 200) || (status > 299)) {
System.out.println("unexpected status code " + status);
System.exit(1);
}
System.out.println("receiving response body (ignored)");
conn.receiveResponseEntity(connected);
conn.tunnelTarget(false, params);
System.out.println("layering secure connection");
conn.layerProtocol(ctx, params);
// finally we have the secure connection and can send the request
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
headers = rsp.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
System.out.println("closing connection");
conn.close();
} finally {
if (conn.isOpen()) {
System.out.println("shutting down connection");
try {
conn.shutdown();
} catch (Exception ex) {
System.out.println("problem during shutdown");
ex.printStackTrace();
}
}
System.out.println("releasing connection");
clcm.releaseConnection(conn, -1, null);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.conn;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.conn.ClientConnectionOperator;
import org.apache.ogt.http.conn.OperatedClientConnection;
import org.apache.ogt.http.conn.scheme.PlainSocketFactory;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.conn.ssl.SSLSocketFactory;
import org.apache.ogt.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.ogt.http.message.BasicHttpRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
/**
* How to open a secure connection through a proxy using
* {@link ClientConnectionOperator ClientConnectionOperator}.
* This exemplifies the <i>opening</i> of the connection only.
* The message exchange, both subsequently and for tunnelling,
* should not be used as a template.
*
* @since 4.0
*/
public class OperatorConnectProxy {
public static void main(String[] args) throws Exception {
// make sure to use a proxy that supports CONNECT
HttpHost target = new HttpHost("issues.apache.org", 443, "https");
HttpHost proxy = new HttpHost("127.0.0.1", 8666, "http");
// some general setup
// Register the "http" and "https" protocol schemes, they are
// required by the default operator to look up socket factories.
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("http",
80, PlainSocketFactory.getSocketFactory()));
supportedSchemes.register(new Scheme("https",
443, SSLSocketFactory.getSocketFactory()));
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
// one operator can be used for many connections
ClientConnectionOperator scop = new DefaultClientConnectionOperator(supportedSchemes);
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
// In a real application, request interceptors should be used
// to add the required headers.
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
OperatedClientConnection conn = scop.createConnection();
try {
System.out.println("opening connection to " + proxy);
scop.openConnection(conn, proxy, null, ctx, params);
// Creates a request to tunnel a connection.
// For details see RFC 2817, section 5.2
String authority = target.getHostName() + ":" + target.getPort();
HttpRequest connect = new BasicHttpRequest("CONNECT", authority,
HttpVersion.HTTP_1_1);
// In a real application, request interceptors should be used
// to add the required headers.
connect.addHeader("Host", authority);
System.out.println("opening tunnel to " + target);
conn.sendRequestHeader(connect);
// there is no request entity
conn.flush();
System.out.println("receiving confirmation for tunnel");
HttpResponse connected = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
printResponseHeader(connected);
System.out.println("----------------------------------------");
int status = connected.getStatusLine().getStatusCode();
if ((status < 200) || (status > 299)) {
System.out.println("unexpected status code " + status);
System.exit(1);
}
System.out.println("receiving response body (ignored)");
conn.receiveResponseEntity(connected);
// Now we have a tunnel to the target. As we will be creating a
// layered TLS/SSL socket immediately afterwards, updating the
// connection with the new target is optional - but good style.
// The scheme part of the target is already "https", though the
// connection is not yet switched to the TLS/SSL protocol.
conn.update(null, target, false, params);
System.out.println("layering secure connection");
scop.updateSecureConnection(conn, target, ctx, params);
// finally we have the secure connection and can send the request
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
printResponseHeader(rsp);
System.out.println("----------------------------------------");
} finally {
System.out.println("closing connection");
conn.close();
}
}
private final static void printResponseHeader(HttpResponse rsp) {
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i=0; i<headers.length; i++) {
System.out.println(headers[i]);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.conn;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.conn.ClientConnectionOperator;
import org.apache.ogt.http.conn.OperatedClientConnection;
import org.apache.ogt.http.conn.scheme.PlainSocketFactory;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.ogt.http.message.BasicHttpRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
/**
* How to open a direct connection using
* {@link ClientConnectionOperator ClientConnectionOperator}.
* This exemplifies the <i>opening</i> of the connection only.
* The subsequent message exchange in this example should not
* be used as a template.
*
* @since 4.0
*/
public class OperatorConnectDirect {
public static void main(String[] args) throws Exception {
HttpHost target = new HttpHost("jakarta.apache.org", 80, "http");
// some general setup
// Register the "http" protocol scheme, it is required
// by the default operator to look up socket factories.
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
// one operator can be used for many connections
ClientConnectionOperator scop = new DefaultClientConnectionOperator(supportedSchemes);
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
OperatedClientConnection conn = scop.createConnection();
try {
System.out.println("opening connection to " + target);
scop.openConnection(conn, target, null, ctx, params);
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
} finally {
System.out.println("closing connection");
conn.close();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.cookie.params;
import java.util.Collection;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.params.HttpAbstractParamBean;
import org.apache.ogt.http.params.HttpParams;
/**
* This is a Java Bean class that can be used to wrap an instance of
* {@link HttpParams} and manipulate HTTP cookie parameters using Java Beans
* conventions.
*
* @since 4.0
*/
@NotThreadSafe
public class CookieSpecParamBean extends HttpAbstractParamBean {
public CookieSpecParamBean (final HttpParams params) {
super(params);
}
public void setDatePatterns (final Collection <String> patterns) {
params.setParameter(CookieSpecPNames.DATE_PATTERNS, patterns);
}
public void setSingleHeader (final boolean singleHeader) {
params.setBooleanParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, singleHeader);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.cookie.params;
/**
* Parameter names for HTTP cookie management classes.
*
* @since 4.0
*/
public interface CookieSpecPNames {
/**
* Defines valid date patterns to be used for parsing non-standard
* <code>expires</code> attribute. Only required for compatibility
* with non-compliant servers that still use <code>expires</code>
* defined in the Netscape draft instead of the standard
* <code>max-age</code> attribute.
* <p>
* This parameter expects a value of type {@link java.util.Collection}.
* The collection elements must be of type {@link String} compatible
* with the syntax of {@link java.text.SimpleDateFormat}.
* </p>
*/
public static final String DATE_PATTERNS = "http.protocol.cookie-datepatterns";
/**
* Defines whether cookies should be forced into a single
* <code>Cookie</code> request header. Otherwise, each cookie is formatted
* as a separate <code>Cookie</code> header.
* <p>
* This parameter expects a value of type {@link Boolean}.
* </p>
*/
public static final String SINGLE_COOKIE_HEADER = "http.protocol.single-cookie-header";
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.cookie;
import java.util.Date;
/**
* Cookie interface represents a token or short packet of state information
* (also referred to as "magic-cookie") that the HTTP agent and the target
* server can exchange to maintain a session. In its simples form an HTTP
* cookie is merely a name / value pair.
*
* @since 4.0
*/
public interface Cookie {
/**
* Returns the name.
*
* @return String name The name
*/
String getName();
/**
* Returns the value.
*
* @return String value The current value.
*/
String getValue();
/**
* Returns the comment describing the purpose of this cookie, or
* <tt>null</tt> if no such comment has been defined.
*
* @return comment
*/
String getComment();
/**
* If a user agent (web browser) presents this cookie to a user, the
* cookie's purpose will be described by the information at this URL.
*/
String getCommentURL();
/**
* Returns the expiration {@link Date} of the cookie, or <tt>null</tt>
* if none exists.
* <p><strong>Note:</strong> the object returned by this method is
* considered immutable. Changing it (e.g. using setTime()) could result
* in undefined behaviour. Do so at your peril. </p>
* @return Expiration {@link Date}, or <tt>null</tt>.
*/
Date getExpiryDate();
/**
* Returns <tt>false</tt> if the cookie should be discarded at the end
* of the "session"; <tt>true</tt> otherwise.
*
* @return <tt>false</tt> if the cookie should be discarded at the end
* of the "session"; <tt>true</tt> otherwise
*/
boolean isPersistent();
/**
* Returns domain attribute of the cookie. The value of the Domain
* attribute specifies the domain for which the cookie is valid.
*
* @return the value of the domain attribute.
*/
String getDomain();
/**
* Returns the path attribute of the cookie. The value of the Path
* attribute specifies the subset of URLs on the origin server to which
* this cookie applies.
*
* @return The value of the path attribute.
*/
String getPath();
/**
* Get the Port attribute. It restricts the ports to which a cookie
* may be returned in a Cookie request header.
*/
int[] getPorts();
/**
* Indicates whether this cookie requires a secure connection.
*
* @return <code>true</code> if this cookie should only be sent
* over secure connections, <code>false</code> otherwise.
*/
boolean isSecure();
/**
* Returns the version of the cookie specification to which this
* cookie conforms.
*
* @return the version of the cookie.
*/
int getVersion();
/**
* Returns true if this cookie has expired.
* @param date Current time
*
* @return <tt>true</tt> if the cookie has expired.
*/
boolean isExpired(final Date date);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.cookie;
/**
* This interface represents a cookie attribute handler responsible
* for parsing, validating, and matching a specific cookie attribute,
* such as path, domain, port, etc.
*
* Different cookie specifications can provide a specific
* implementation for this class based on their cookie handling
* rules.
*
*
* @since 4.0
*/
public interface CookieAttributeHandler {
/**
* Parse the given cookie attribute value and update the corresponding
* {@link org.apache.ogt.http.cookie.Cookie} property.
*
* @param cookie {@link org.apache.ogt.http.cookie.Cookie} to be updated
* @param value cookie attribute value from the cookie response header
*/
void parse(SetCookie cookie, String value)
throws MalformedCookieException;
/**
* Peforms cookie validation for the given attribute value.
*
* @param cookie {@link org.apache.ogt.http.cookie.Cookie} to validate
* @param origin the cookie source to validate against
* @throws MalformedCookieException if cookie validation fails for this attribute
*/
void validate(Cookie cookie, CookieOrigin origin)
throws MalformedCookieException;
/**
* Matches the given value (property of the destination host where request is being
* submitted) with the corresponding cookie attribute.
*
* @param cookie {@link org.apache.ogt.http.cookie.Cookie} to match
* @param origin the cookie source to match against
* @return <tt>true</tt> if the match is successful; <tt>false</tt> otherwise
*/
boolean match(Cookie cookie, CookieOrigin origin);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.cookie;
import java.util.List;
import org.apache.ogt.http.Header;
/**
* Defines the cookie management specification.
* <p>Cookie management specification must define
* <ul>
* <li> rules of parsing "Set-Cookie" header
* <li> rules of validation of parsed cookies
* <li> formatting of "Cookie" header
* </ul>
* for a given host, port and path of origin
*
*
* @since 4.0
*/
public interface CookieSpec {
/**
* Returns version of the state management this cookie specification
* conforms to.
*
* @return version of the state management specification
*/
int getVersion();
/**
* Parse the <tt>"Set-Cookie"</tt> Header into an array of Cookies.
*
* <p>This method will not perform the validation of the resultant
* {@link Cookie}s</p>
*
* @see #validate
*
* @param header the <tt>Set-Cookie</tt> received from the server
* @param origin details of the cookie origin
* @return an array of <tt>Cookie</tt>s parsed from the header
* @throws MalformedCookieException if an exception occurs during parsing
*/
List<Cookie> parse(Header header, CookieOrigin origin) throws MalformedCookieException;
/**
* Validate the cookie according to validation rules defined by the
* cookie specification.
*
* @param cookie the Cookie to validate
* @param origin details of the cookie origin
* @throws MalformedCookieException if the cookie is invalid
*/
void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException;
/**
* Determines if a Cookie matches the target location.
*
* @param cookie the Cookie to be matched
* @param origin the target to test against
*
* @return <tt>true</tt> if the cookie should be submitted with a request
* with given attributes, <tt>false</tt> otherwise.
*/
boolean match(Cookie cookie, CookieOrigin origin);
/**
* Create <tt>"Cookie"</tt> headers for an array of Cookies.
*
* @param cookies the Cookies format into a Cookie header
* @return a Header for the given Cookies.
* @throws IllegalArgumentException if an input parameter is illegal
*/
List<Header> formatCookies(List<Cookie> cookies);
/**
* Returns a request header identifying what version of the state management
* specification is understood. May be <code>null</code> if the cookie
* specification does not support <tt>Cookie2</tt> header.
*/
Header getVersionHeader();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.cookie;
import org.apache.ogt.http.params.HttpParams;
/**
* Factory for {@link CookieSpec} implementations.
*
* @since 4.0
*/
public interface CookieSpecFactory {
/**
* Creates an instance of {@link CookieSpec} using given HTTP parameters.
*
* @param params HTTP parameters.
*
* @return cookie spec.
*/
CookieSpec newInstance(HttpParams params);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.cookie;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.ogt.http.annotation.ThreadSafe;
import org.apache.ogt.http.params.HttpParams;
/**
* Cookie specification registry that can be used to obtain the corresponding
* cookie specification implementation for a given type of type or version of
* cookie.
*
*
* @since 4.0
*/
@ThreadSafe
public final class CookieSpecRegistry {
private final ConcurrentHashMap<String,CookieSpecFactory> registeredSpecs;
public CookieSpecRegistry() {
super();
this.registeredSpecs = new ConcurrentHashMap<String,CookieSpecFactory>();
}
/**
* Registers a {@link CookieSpecFactory} with the given identifier.
* If a specification with the given name already exists it will be overridden.
* This nameis the same one used to retrieve the {@link CookieSpecFactory}
* from {@link #getCookieSpec(String)}.
*
* @param name the identifier for this specification
* @param factory the {@link CookieSpecFactory} class to register
*
* @see #getCookieSpec(String)
*/
public void register(final String name, final CookieSpecFactory factory) {
if (name == null) {
throw new IllegalArgumentException("Name may not be null");
}
if (factory == null) {
throw new IllegalArgumentException("Cookie spec factory may not be null");
}
registeredSpecs.put(name.toLowerCase(Locale.ENGLISH), factory);
}
/**
* Unregisters the {@link CookieSpecFactory} with the given ID.
*
* @param id the identifier of the {@link CookieSpec cookie specification} to unregister
*/
public void unregister(final String id) {
if (id == null) {
throw new IllegalArgumentException("Id may not be null");
}
registeredSpecs.remove(id.toLowerCase(Locale.ENGLISH));
}
/**
* Gets the {@link CookieSpec cookie specification} with the given ID.
*
* @param name the {@link CookieSpec cookie specification} identifier
* @param params the {@link HttpParams HTTP parameters} for the cookie
* specification.
*
* @return {@link CookieSpec cookie specification}
*
* @throws IllegalStateException if a policy with the given name cannot be found
*/
public CookieSpec getCookieSpec(final String name, final HttpParams params)
throws IllegalStateException {
if (name == null) {
throw new IllegalArgumentException("Name may not be null");
}
CookieSpecFactory factory = registeredSpecs.get(name.toLowerCase(Locale.ENGLISH));
if (factory != null) {
return factory.newInstance(params);
} else {
throw new IllegalStateException("Unsupported cookie spec: " + name);
}
}
/**
* Gets the {@link CookieSpec cookie specification} with the given name.
*
* @param name the {@link CookieSpec cookie specification} identifier
*
* @return {@link CookieSpec cookie specification}
*
* @throws IllegalStateException if a policy with the given name cannot be found
*/
public CookieSpec getCookieSpec(final String name)
throws IllegalStateException {
return getCookieSpec(name, null);
}
/**
* Obtains a list containing the names of all registered {@link CookieSpec cookie
* specs}.
*
* Note that the DEFAULT policy (if present) is likely to be the same
* as one of the other policies, but does not have to be.
*
* @return list of registered cookie spec names
*/
public List<String> getSpecNames(){
return new ArrayList<String>(registeredSpecs.keySet());
}
/**
* Populates the internal collection of registered {@link CookieSpec cookie
* specs} with the content of the map passed as a parameter.
*
* @param map cookie specs
*/
public void setItems(final Map<String, CookieSpecFactory> map) {
if (map == null) {
return;
}
registeredSpecs.clear();
registeredSpecs.putAll(map);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.cookie;
/**
* ClientCookie extends the standard {@link Cookie} interface with
* additional client specific functionality such ability to retrieve
* original cookie attributes exactly as they were specified by the
* origin server. This is important for generating the <tt>Cookie</tt>
* header because some cookie specifications require that the
* <tt>Cookie</tt> header should include certain attributes only if
* they were specified in the <tt>Set-Cookie</tt> header.
*
*
* @since 4.0
*/
public interface ClientCookie extends Cookie {
// RFC2109 attributes
public static final String VERSION_ATTR = "version";
public static final String PATH_ATTR = "path";
public static final String DOMAIN_ATTR = "domain";
public static final String MAX_AGE_ATTR = "max-age";
public static final String SECURE_ATTR = "secure";
public static final String COMMENT_ATTR = "comment";
public static final String EXPIRES_ATTR = "expires";
// RFC2965 attributes
public static final String PORT_ATTR = "port";
public static final String COMMENTURL_ATTR = "commenturl";
public static final String DISCARD_ATTR = "discard";
String getAttribute(String name);
boolean containsAttribute(String name);
} | Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.cookie;
import java.util.Locale;
import org.apache.ogt.http.annotation.Immutable;
/**
* CookieOrigin class encapsulates details of an origin server that
* are relevant when parsing, validating or matching HTTP cookies.
*
* @since 4.0
*/
@Immutable
public final class CookieOrigin {
private final String host;
private final int port;
private final String path;
private final boolean secure;
public CookieOrigin(final String host, int port, final String path, boolean secure) {
super();
if (host == null) {
throw new IllegalArgumentException(
"Host of origin may not be null");
}
if (host.trim().length() == 0) {
throw new IllegalArgumentException(
"Host of origin may not be blank");
}
if (port < 0) {
throw new IllegalArgumentException("Invalid port: " + port);
}
if (path == null) {
throw new IllegalArgumentException(
"Path of origin may not be null.");
}
this.host = host.toLowerCase(Locale.ENGLISH);
this.port = port;
if (path.trim().length() != 0) {
this.path = path;
} else {
this.path = "/";
}
this.secure = secure;
}
public String getHost() {
return this.host;
}
public String getPath() {
return this.path;
}
public int getPort() {
return this.port;
}
public boolean isSecure() {
return this.secure;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append('[');
if (this.secure) {
buffer.append("(secure)");
}
buffer.append(this.host);
buffer.append(':');
buffer.append(Integer.toString(this.port));
buffer.append(this.path);
buffer.append(']');
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.cookie;
import java.util.Date;
/**
* This interface represents a <code>Set-Cookie</code> response header sent by the
* origin server to the HTTP agent in order to maintain a conversational state.
*
* @since 4.0
*/
public interface SetCookie extends Cookie {
void setValue(String value);
/**
* If a user agent (web browser) presents this cookie to a user, the
* cookie's purpose will be described using this comment.
*
* @param comment
*
* @see #getComment()
*/
void setComment(String comment);
/**
* Sets expiration date.
* <p><strong>Note:</strong> the object returned by this method is considered
* immutable. Changing it (e.g. using setTime()) could result in undefined
* behaviour. Do so at your peril.</p>
*
* @param expiryDate the {@link Date} after which this cookie is no longer valid.
*
* @see Cookie#getExpiryDate
*
*/
void setExpiryDate (Date expiryDate);
/**
* Sets the domain attribute.
*
* @param domain The value of the domain attribute
*
* @see Cookie#getDomain
*/
void setDomain(String domain);
/**
* Sets the path attribute.
*
* @param path The value of the path attribute
*
* @see Cookie#getPath
*
*/
void setPath(String path);
/**
* Sets the secure attribute of the cookie.
* <p>
* When <tt>true</tt> the cookie should only be sent
* using a secure protocol (https). This should only be set when
* the cookie's originating server used a secure protocol to set the
* cookie's value.
*
* @param secure The value of the secure attribute
*
* @see #isSecure()
*/
void setSecure (boolean secure);
/**
* Sets the version of the cookie specification to which this
* cookie conforms.
*
* @param version the version of the cookie.
*
* @see Cookie#getVersion
*/
void setVersion(int version);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.cookie;
/**
* Constants and static helpers related to the HTTP state management.
*
*
* @since 4.0
*/
public interface SM {
public static final String COOKIE = "Cookie";
public static final String COOKIE2 = "Cookie2";
public static final String SET_COOKIE = "Set-Cookie";
public static final String SET_COOKIE2 = "Set-Cookie2";
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.cookie;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.annotation.Immutable;
/**
* Signals that a cookie is in some way invalid or illegal in a given
* context
*
*
* @since 4.0
*/
@Immutable
public class MalformedCookieException extends ProtocolException {
private static final long serialVersionUID = -6695462944287282185L;
/**
* Creates a new MalformedCookieException with a <tt>null</tt> detail message.
*/
public MalformedCookieException() {
super();
}
/**
* Creates a new MalformedCookieException with a specified message string.
*
* @param message The exception detail message
*/
public MalformedCookieException(String message) {
super(message);
}
/**
* Creates a new MalformedCookieException 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 MalformedCookieException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.cookie;
import java.io.Serializable;
import java.util.Comparator;
import org.apache.ogt.http.annotation.Immutable;
/**
* This cookie comparator can be used to compare identity of cookies.
* <p>
* Cookies are considered identical if their names are equal and
* their domain attributes match ignoring case.
*
* @since 4.0
*/
@Immutable
public class CookieIdentityComparator implements Serializable, Comparator<Cookie> {
private static final long serialVersionUID = 4466565437490631532L;
public int compare(final Cookie c1, final Cookie c2) {
int res = c1.getName().compareTo(c2.getName());
if (res == 0) {
// do not differentiate empty and null domains
String d1 = c1.getDomain();
if (d1 == null) {
d1 = "";
} else if (d1.indexOf('.') == -1) {
d1 = d1 + ".local";
}
String d2 = c2.getDomain();
if (d2 == null) {
d2 = "";
} else if (d2.indexOf('.') == -1) {
d2 = d2 + ".local";
}
res = d1.compareToIgnoreCase(d2);
}
if (res == 0) {
String p1 = c1.getPath();
if (p1 == null) {
p1 = "/";
}
String p2 = c2.getPath();
if (p2 == null) {
p2 = "/";
}
res = p1.compareTo(p2);
}
return res;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.cookie;
/**
* This interface represents a <code>Set-Cookie2</code> response header sent by the
* origin server to the HTTP agent in order to maintain a conversational state.
*
* @since 4.0
*/
public interface SetCookie2 extends SetCookie {
/**
* If a user agent (web browser) presents this cookie to a user, the
* cookie's purpose will be described by the information at this URL.
*/
void setCommentURL(String commentURL);
/**
* Sets the Port attribute. It restricts the ports to which a cookie
* may be returned in a Cookie request header.
*/
void setPorts(int[] ports);
/**
* Set the Discard attribute.
*
* Note: <tt>Discard</tt> attribute overrides <tt>Max-age</tt>.
*
* @see #isPersistent()
*/
void setDiscard(boolean discard);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.cookie;
import java.io.Serializable;
import java.util.Comparator;
import org.apache.ogt.http.annotation.Immutable;
/**
* This cookie comparator ensures that multiple cookies satisfying
* a common criteria are ordered in the <tt>Cookie</tt> header such
* that those with more specific Path attributes precede those with
* less specific.
*
* <p>
* This comparator assumes that Path attributes of two cookies
* path-match a commmon request-URI. Otherwise, the result of the
* comparison is undefined.
* </p>
*
*
* @since 4.0
*/
@Immutable
public class CookiePathComparator implements Serializable, Comparator<Cookie> {
private static final long serialVersionUID = 7523645369616405818L;
private String normalizePath(final Cookie cookie) {
String path = cookie.getPath();
if (path == null) {
path = "/";
}
if (!path.endsWith("/")) {
path = path + '/';
}
return path;
}
public int compare(final Cookie c1, final Cookie c2) {
String path1 = normalizePath(c1);
String path2 = normalizePath(c2);
if (path1.equals(path2)) {
return 0;
} else if (path1.startsWith(path2)) {
return -1;
} else if (path2.startsWith(path1)) {
return 1;
} else {
// Does not really matter
return 0;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.cookie;
import org.apache.ogt.http.annotation.Immutable;
/**
* Signals that a cookie violates a restriction imposed by the cookie
* specification.
*
* @since 4.1
*/
@Immutable
public class CookieRestrictionViolationException extends MalformedCookieException {
private static final long serialVersionUID = 7371235577078589013L;
/**
* Creates a new CookeFormatViolationException with a <tt>null</tt> detail
* message.
*/
public CookieRestrictionViolationException() {
super();
}
/**
* Creates a new CookeRestrictionViolationException with a specified
* message string.
*
* @param message The exception detail message
*/
public CookieRestrictionViolationException(String message) {
super(message);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.params;
/**
* Parameter names for HTTP client parameters.
*
* @since 4.0
*/
public interface ClientPNames {
/**
* Defines the class name of the default {@link org.apache.ogt.http.conn.ClientConnectionManager}
* <p>
* This parameter expects a value of type {@link String}.
* </p>
*/
public static final String CONNECTION_MANAGER_FACTORY_CLASS_NAME = "http.connection-manager.factory-class-name";
/**
* @deprecated use #CONNECTION_MANAGER_FACTORY_CLASS_NAME
*/
@Deprecated
public static final String CONNECTION_MANAGER_FACTORY = "http.connection-manager.factory-object";
/**
* Defines whether redirects should be handled automatically
* <p>
* This parameter expects a value of type {@link Boolean}.
* </p>
*/
public static final String HANDLE_REDIRECTS = "http.protocol.handle-redirects";
/**
* Defines whether relative redirects should be rejected. HTTP specification
* requires the location value be an absolute URI.
* <p>
* This parameter expects a value of type {@link Boolean}.
* </p>
*/
public static final String REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect";
/**
* Defines the maximum number of redirects to be followed.
* The limit on number of redirects is intended to prevent infinite loops.
* <p>
* This parameter expects a value of type {@link Integer}.
* </p>
*/
public static final String MAX_REDIRECTS = "http.protocol.max-redirects";
/**
* Defines whether circular redirects (redirects to the same location) should be allowed.
* The HTTP spec is not sufficiently clear whether circular redirects are permitted,
* therefore optionally they can be enabled
* <p>
* This parameter expects a value of type {@link Boolean}.
* </p>
*/
public static final String ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects";
/**
* Defines whether authentication should be handled automatically.
* <p>
* This parameter expects a value of type {@link Boolean}.
* </p>
*/
public static final String HANDLE_AUTHENTICATION = "http.protocol.handle-authentication";
/**
* Defines the name of the cookie specification to be used for HTTP state management.
* <p>
* This parameter expects a value of type {@link String}.
* </p>
*/
public static final String COOKIE_POLICY = "http.protocol.cookie-policy";
/**
* Defines the virtual host name to be used in the <code>Host</code>
* request header instead of the physical host name.
* <p>
* This parameter expects a value of type {@link org.apache.ogt.http.HttpHost}.
* </p>
*/
public static final String VIRTUAL_HOST = "http.virtual-host";
/**
* Defines the request headers to be sent per default with each request.
* <p>
* This parameter expects a value of type {@link java.util.Collection}. The
* collection is expected to contain {@link org.apache.ogt.http.Header}s.
* </p>
*/
public static final String DEFAULT_HEADERS = "http.default-headers";
/**
* Defines the default host. The default value will be used if the target host is
* not explicitly specified in the request URI.
* <p>
* This parameter expects a value of type {@link org.apache.ogt.http.HttpHost}.
* </p>
*/
public static final String DEFAULT_HOST = "http.default-host";
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.params;
import org.apache.ogt.http.auth.params.AuthPNames;
import org.apache.ogt.http.conn.params.ConnConnectionPNames;
import org.apache.ogt.http.conn.params.ConnManagerPNames;
import org.apache.ogt.http.conn.params.ConnRoutePNames;
import org.apache.ogt.http.cookie.params.CookieSpecPNames;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
/**
* Collected parameter names for the HttpClient module.
* This interface combines the parameter definitions of the HttpClient
* module and all dependency modules or informational units.
* It does not define additional parameter names, but references
* other interfaces defining parameter names.
* <br/>
* This interface is meant as a navigation aid for developers.
* When referring to parameter names, you should use the interfaces
* in which the respective constants are actually defined.
*
* @since 4.0
*/
@SuppressWarnings("deprecation")
public interface AllClientPNames extends
CoreConnectionPNames, CoreProtocolPNames,
ClientPNames, AuthPNames, CookieSpecPNames,
ConnConnectionPNames, ConnManagerPNames, ConnRoutePNames {
// no additional definitions
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.params;
import org.apache.ogt.http.annotation.Immutable;
/**
* Standard cookie specifications supported by HttpClient.
*
* @since 4.0
*/
@Immutable
public final class CookiePolicy {
/**
* The policy that provides high degree of compatibilty
* with common cookie management of popular HTTP agents.
*/
public static final String BROWSER_COMPATIBILITY = "compatibility";
/**
* The Netscape cookie draft compliant policy.
*/
public static final String NETSCAPE = "netscape";
/**
* The RFC 2109 compliant policy.
*/
public static final String RFC_2109 = "rfc2109";
/**
* The RFC 2965 compliant policy.
*/
public static final String RFC_2965 = "rfc2965";
/**
* The default 'best match' policy.
*/
public static final String BEST_MATCH = "best-match";
/**
* The policy that ignores cookies.
*
* @since 4.1-beta1
*/
public static final String IGNORE_COOKIES = "ignoreCookies";
private CookiePolicy() {
super();
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.params;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.params.HttpParams;
/**
* An adaptor for manipulating HTTP client parameters in {@link HttpParams}.
*
* @since 4.0
*/
@Immutable
public class HttpClientParams {
private HttpClientParams() {
super();
}
public static boolean isRedirecting(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getBooleanParameter
(ClientPNames.HANDLE_REDIRECTS, true);
}
public static void setRedirecting(final HttpParams params, boolean value) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setBooleanParameter
(ClientPNames.HANDLE_REDIRECTS, value);
}
public static boolean isAuthenticating(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getBooleanParameter
(ClientPNames.HANDLE_AUTHENTICATION, true);
}
public static void setAuthenticating(final HttpParams params, boolean value) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setBooleanParameter
(ClientPNames.HANDLE_AUTHENTICATION, value);
}
public static String getCookiePolicy(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
String cookiePolicy = (String)
params.getParameter(ClientPNames.COOKIE_POLICY);
if (cookiePolicy == null) {
return CookiePolicy.BEST_MATCH;
}
return cookiePolicy;
}
public static void setCookiePolicy(final HttpParams params, final String cookiePolicy) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setParameter(ClientPNames.COOKIE_POLICY, cookiePolicy);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.params;
import java.util.Collection;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.conn.ClientConnectionManagerFactory;
import org.apache.ogt.http.params.HttpAbstractParamBean;
import org.apache.ogt.http.params.HttpParams;
/**
* This is a Java Bean class that can be used to wrap an instance of
* {@link HttpParams} and manipulate HTTP client parameters using
* Java Beans conventions.
*
* @since 4.0
*/
@NotThreadSafe
public class ClientParamBean extends HttpAbstractParamBean {
public ClientParamBean (final HttpParams params) {
super(params);
}
public void setConnectionManagerFactoryClassName (final String factory) {
params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, factory);
}
@Deprecated
public void setConnectionManagerFactory(ClientConnectionManagerFactory factory) {
params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY, factory);
}
public void setHandleRedirects (final boolean handle) {
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, handle);
}
public void setRejectRelativeRedirect (final boolean reject) {
params.setBooleanParameter(ClientPNames.REJECT_RELATIVE_REDIRECT, reject);
}
public void setMaxRedirects (final int maxRedirects) {
params.setIntParameter(ClientPNames.MAX_REDIRECTS, maxRedirects);
}
public void setAllowCircularRedirects (final boolean allow) {
params.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, allow);
}
public void setHandleAuthentication (final boolean handle) {
params.setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, handle);
}
public void setCookiePolicy (final String policy) {
params.setParameter(ClientPNames.COOKIE_POLICY, policy);
}
public void setVirtualHost (final HttpHost host) {
params.setParameter(ClientPNames.VIRTUAL_HOST, host);
}
public void setDefaultHeaders (final Collection <Header> headers) {
params.setParameter(ClientPNames.DEFAULT_HEADERS, headers);
}
public void setDefaultHost (final HttpHost host) {
params.setParameter(ClientPNames.DEFAULT_HOST, host);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.params;
import org.apache.ogt.http.annotation.Immutable;
/**
* Standard authentication schemes supported by HttpClient.
*
* @since 4.0
*/
@Immutable
public final class AuthPolicy {
private AuthPolicy() {
super();
}
/**
* The NTLM scheme is a proprietary Microsoft Windows Authentication
* protocol (considered to be the most secure among currently supported
* authentication schemes).
*/
public static final String NTLM = "NTLM";
/**
* Digest authentication scheme as defined in RFC2617.
*/
public static final String DIGEST = "Digest";
/**
* Basic authentication scheme as defined in RFC2617 (considered inherently
* insecure, but most widely supported)
*/
public static final String BASIC = "Basic";
/**
* SPNEGO/Kerberos Authentication scheme.
*
* @since 4.1
*/
public static final String SPNEGO = "negotiate";
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client;
import java.util.Date;
import java.util.List;
import org.apache.ogt.http.cookie.Cookie;
/**
* This interface represents an abstract store for {@link Cookie}
* objects.
*
* @since 4.0
*/
public interface CookieStore {
/**
* Adds an {@link Cookie}, replacing any existing equivalent cookies.
* If the given cookie has already expired it will not be added, but existing
* values will still be removed.
*
* @param cookie the {@link Cookie cookie} to be added
*/
void addCookie(Cookie cookie);
/**
* Returns all cookies contained in this store.
*
* @return all cookies
*/
List<Cookie> getCookies();
/**
* Removes all of {@link Cookie}s in this store that have expired by
* the specified {@link java.util.Date}.
*
* @return true if any cookies were purged.
*/
boolean clearExpired(Date date);
/**
* Clears all cookies.
*/
void clear();
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client;
import org.apache.ogt.http.annotation.Immutable;
/**
* Signals a circular redirect
*
*
* @since 4.0
*/
@Immutable
public class CircularRedirectException extends RedirectException {
private static final long serialVersionUID = 6830063487001091803L;
/**
* Creates a new CircularRedirectException with a <tt>null</tt> detail message.
*/
public CircularRedirectException() {
super();
}
/**
* Creates a new CircularRedirectException with the specified detail message.
*
* @param message The exception detail message
*/
public CircularRedirectException(String message) {
super(message);
}
/**
* Creates a new CircularRedirectException 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 CircularRedirectException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client;
import org.apache.ogt.http.annotation.Immutable;
/**
* Signals a non 2xx HTTP response.
*
* @since 4.0
*/
@Immutable
public class HttpResponseException extends ClientProtocolException {
private static final long serialVersionUID = -7186627969477257933L;
private final int statusCode;
public HttpResponseException(int statusCode, final String s) {
super(s);
this.statusCode = statusCode;
}
public int getStatusCode() {
return this.statusCode;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client;
import java.net.URI;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.protocol.HttpContext;
/**
* A handler for determining if an HTTP request should be redirected to
* a new location in response to an HTTP response received from the target
* server.
* <p>
* Implementations of this interface must be thread-safe. Access to shared
* data must be synchronized as methods of this interface may be executed
* from multiple threads.
*
* @since 4.0
*
* @deprecated use {@link RedirectStrategy}
*/
@Deprecated
public interface RedirectHandler {
/**
* Determines if a request should be redirected to a new location
* given the response from the target server.
*
* @param response the response received from the target server
* @param context the context for the request execution
*
* @return <code>true</code> if the request should be redirected, <code>false</code>
* otherwise
*/
boolean isRedirectRequested(HttpResponse response, HttpContext context);
/**
* Determines the location request is expected to be redirected to
* given the response from the target server and the current request
* execution context.
*
* @param response the response received from the target server
* @param context the context for the request execution
*
* @return redirect URI
*/
URI getLocationURI(HttpResponse response, HttpContext context)
throws ProtocolException;
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.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.annotation.Immutable;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Class responsible for handling Content Encoding requests in HTTP.
* <p>
* Instances of this class are stateless, therefore they're thread-safe and immutable.
*
* @see "http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5"
*
* @since 4.1
*/
@Immutable
public class RequestAcceptEncoding implements HttpRequestInterceptor {
/**
* Adds the header {@code "Accept-Encoding: gzip,deflate"} to the request.
*/
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
/* Signal support for Accept-Encoding transfer encodings. */
request.addHeader("Accept-Encoding", "gzip,deflate");
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.protocol;
/**
* {@link org.apache.ogt.http.protocol.HttpContext} attribute names for
* client side HTTP protocol processing.
*
* @since 4.0
*/
public interface ClientContext {
/**
* Attribute name of a {@link org.apache.ogt.http.conn.scheme.Scheme}
* object that represents the actual protocol scheme registry.
*/
public static final String SCHEME_REGISTRY = "http.scheme-registry";
/**
* Attribute name of a {@link org.apache.ogt.http.cookie.CookieSpecRegistry}
* object that represents the actual cookie specification registry.
*/
public static final String COOKIESPEC_REGISTRY = "http.cookiespec-registry";
/**
* Attribute name of a {@link org.apache.ogt.http.cookie.CookieSpec}
* object that represents the actual cookie specification.
*/
public static final String COOKIE_SPEC = "http.cookie-spec";
/**
* Attribute name of a {@link org.apache.ogt.http.cookie.CookieOrigin}
* object that represents the actual details of the origin server.
*/
public static final String COOKIE_ORIGIN = "http.cookie-origin";
/**
* Attribute name of a {@link org.apache.ogt.http.client.CookieStore}
* object that represents the actual cookie store.
*/
public static final String COOKIE_STORE = "http.cookie-store";
/**
* Attribute name of a {@link org.apache.ogt.http.auth.AuthSchemeRegistry}
* object that represents the actual authentication scheme registry.
*/
public static final String AUTHSCHEME_REGISTRY = "http.authscheme-registry";
/**
* Attribute name of a {@link org.apache.ogt.http.client.CredentialsProvider}
* object that represents the actual credentials provider.
*/
public static final String CREDS_PROVIDER = "http.auth.credentials-provider";
/**
* Attribute name of a {@link org.apache.ogt.http.client.AuthCache} object
* that represents the auth scheme cache.
*/
public static final String AUTH_CACHE = "http.auth.auth-cache";
/**
* Attribute name of a {@link org.apache.ogt.http.auth.AuthState}
* object that represents the actual target authentication state.
*/
public static final String TARGET_AUTH_STATE = "http.auth.target-scope";
/**
* Attribute name of a {@link org.apache.ogt.http.auth.AuthState}
* object that represents the actual proxy authentication state.
*/
public static final String PROXY_AUTH_STATE = "http.auth.proxy-scope";
/**
* @deprecated do not use
*/
@Deprecated
public static final String AUTH_SCHEME_PREF = "http.auth.scheme-pref";
/**
* Attribute name of a {@link java.lang.Object} object that represents
* the actual user identity such as user {@link java.security.Principal}.
*/
public static final String USER_TOKEN = "http.user-token";
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.protocol;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthState;
import org.apache.ogt.http.auth.AuthenticationException;
import org.apache.ogt.http.auth.ContextAwareAuthScheme;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.conn.HttpRoutedConnection;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Generates authentication header for the proxy host, if required,
* based on the actual state of the HTTP authentication context.
*
* @since 4.0
*/
@Immutable
public class RequestProxyAuthentication implements HttpRequestInterceptor {
private final Log log = LogFactory.getLog(getClass());
public RequestProxyAuthentication() {
super();
}
@SuppressWarnings("deprecation")
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");
}
if (request.containsHeader(AUTH.PROXY_AUTH_RESP)) {
return;
}
HttpRoutedConnection conn = (HttpRoutedConnection) context.getAttribute(
ExecutionContext.HTTP_CONNECTION);
if (conn == null) {
this.log.debug("HTTP connection not set in the context");
return;
}
HttpRoute route = conn.getRoute();
if (route.isTunnelled()) {
return;
}
// Obtain authentication state
AuthState authState = (AuthState) context.getAttribute(
ClientContext.PROXY_AUTH_STATE);
if (authState == null) {
this.log.debug("Proxy auth state not set in the context");
return;
}
AuthScheme authScheme = authState.getAuthScheme();
if (authScheme == null) {
return;
}
Credentials creds = authState.getCredentials();
if (creds == null) {
this.log.debug("User credentials not available");
return;
}
if (authState.getAuthScope() != null || !authScheme.isConnectionBased()) {
try {
Header header;
if (authScheme instanceof ContextAwareAuthScheme) {
header = ((ContextAwareAuthScheme) authScheme).authenticate(
creds, request, context);
} else {
header = authScheme.authenticate(creds, request);
}
request.addHeader(header);
} catch (AuthenticationException ex) {
if (this.log.isErrorEnabled()) {
this.log.error("Proxy authentication error: " + ex.getMessage());
}
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.protocol;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthState;
import org.apache.ogt.http.client.AuthCache;
import org.apache.ogt.http.client.params.AuthPolicy;
import org.apache.ogt.http.impl.client.BasicAuthCache;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Response interceptor that adds successfully completed {@link AuthScheme}s
* to the local {@link AuthCache} instance. Cached {@link AuthScheme}s can be
* re-used when executing requests against known hosts, thus avoiding
* additional authentication round-trips.
*
* @since 4.1
*/
@Immutable
public class ResponseAuthCache implements HttpResponseInterceptor {
private final Log log = LogFactory.getLog(getClass());
public ResponseAuthCache() {
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 (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
if (target != null && targetState != null) {
if (isCachable(targetState)) {
if (authCache == null) {
authCache = new BasicAuthCache();
context.setAttribute(ClientContext.AUTH_CACHE, authCache);
}
cache(authCache, target, targetState);
}
}
HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE);
if (proxy != null && proxyState != null) {
if (isCachable(proxyState)) {
if (authCache == null) {
authCache = new BasicAuthCache();
context.setAttribute(ClientContext.AUTH_CACHE, authCache);
}
cache(authCache, proxy, proxyState);
}
}
}
private boolean isCachable(final AuthState authState) {
AuthScheme authScheme = authState.getAuthScheme();
if (authScheme == null || !authScheme.isComplete()) {
return false;
}
String schemeName = authScheme.getSchemeName();
return schemeName.equalsIgnoreCase(AuthPolicy.BASIC) ||
schemeName.equalsIgnoreCase(AuthPolicy.DIGEST);
}
private void cache(final AuthCache authCache, final HttpHost host, final AuthState authState) {
AuthScheme authScheme = authState.getAuthScheme();
if (authState.getAuthScope() != null) {
if (authState.getCredentials() != null) {
if (this.log.isDebugEnabled()) {
this.log.debug("Caching '" + authScheme.getSchemeName() +
"' auth scheme for " + host);
}
authCache.put(host, authScheme);
} else {
authCache.remove(host);
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.protocol;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.client.CookieStore;
import org.apache.ogt.http.client.methods.HttpUriRequest;
import org.apache.ogt.http.client.params.HttpClientParams;
import org.apache.ogt.http.conn.HttpRoutedConnection;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.CookieSpecRegistry;
import org.apache.ogt.http.cookie.SetCookie2;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Request interceptor that matches cookies available in the current
* {@link CookieStore} to the request being executed and generates
* corresponding <code>Cookie</code> request headers.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.cookie.params.CookieSpecPNames#DATE_PATTERNS}</li>
* <li>{@link org.apache.ogt.http.cookie.params.CookieSpecPNames#SINGLE_COOKIE_HEADER}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#COOKIE_POLICY}</li>
* </ul>
*
* @since 4.0
*/
@Immutable
public class RequestAddCookies implements HttpRequestInterceptor {
private final Log log = LogFactory.getLog(getClass());
public RequestAddCookies() {
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");
}
String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase("CONNECT")) {
return;
}
// Obtain cookie store
CookieStore cookieStore = (CookieStore) context.getAttribute(
ClientContext.COOKIE_STORE);
if (cookieStore == null) {
this.log.debug("Cookie store not specified in HTTP context");
return;
}
// Obtain the registry of cookie specs
CookieSpecRegistry registry = (CookieSpecRegistry) context.getAttribute(
ClientContext.COOKIESPEC_REGISTRY);
if (registry == null) {
this.log.debug("CookieSpec registry not specified in HTTP context");
return;
}
// Obtain the target host (required)
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
if (targetHost == null) {
this.log.debug("Target host not set in the context");
return;
}
// Obtain the client connection (required)
HttpRoutedConnection conn = (HttpRoutedConnection) context.getAttribute(
ExecutionContext.HTTP_CONNECTION);
if (conn == null) {
this.log.debug("HTTP connection not set in the context");
return;
}
String policy = HttpClientParams.getCookiePolicy(request.getParams());
if (this.log.isDebugEnabled()) {
this.log.debug("CookieSpec selected: " + policy);
}
URI requestURI;
if (request instanceof HttpUriRequest) {
requestURI = ((HttpUriRequest) request).getURI();
} else {
try {
requestURI = new URI(request.getRequestLine().getUri());
} catch (URISyntaxException ex) {
throw new ProtocolException("Invalid request URI: " +
request.getRequestLine().getUri(), ex);
}
}
String hostName = targetHost.getHostName();
int port = targetHost.getPort();
if (port < 0) {
HttpRoute route = conn.getRoute();
if (route.getHopCount() == 1) {
port = conn.getRemotePort();
} else {
// Target port will be selected by the proxy.
// Use conventional ports for known schemes
String scheme = targetHost.getSchemeName();
if (scheme.equalsIgnoreCase("http")) {
port = 80;
} else if (scheme.equalsIgnoreCase("https")) {
port = 443;
} else {
port = 0;
}
}
}
CookieOrigin cookieOrigin = new CookieOrigin(
hostName,
port,
requestURI.getPath(),
conn.isSecure());
// Get an instance of the selected cookie policy
CookieSpec cookieSpec = registry.getCookieSpec(policy, request.getParams());
// Get all cookies available in the HTTP state
List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies());
// Find cookies matching the given origin
List<Cookie> matchedCookies = new ArrayList<Cookie>();
Date now = new Date();
for (Cookie cookie : cookies) {
if (!cookie.isExpired(now)) {
if (cookieSpec.match(cookie, cookieOrigin)) {
if (this.log.isDebugEnabled()) {
this.log.debug("Cookie " + cookie + " match " + cookieOrigin);
}
matchedCookies.add(cookie);
}
} else {
if (this.log.isDebugEnabled()) {
this.log.debug("Cookie " + cookie + " expired");
}
}
}
// Generate Cookie request headers
if (!matchedCookies.isEmpty()) {
List<Header> headers = cookieSpec.formatCookies(matchedCookies);
for (Header header : headers) {
request.addHeader(header);
}
}
int ver = cookieSpec.getVersion();
if (ver > 0) {
boolean needVersionHeader = false;
for (Cookie cookie : matchedCookies) {
if (ver != cookie.getVersion() || !(cookie instanceof SetCookie2)) {
needVersionHeader = true;
}
}
if (needVersionHeader) {
Header header = cookieSpec.getVersionHeader();
if (header != null) {
// Advertise cookie version support
request.addHeader(header);
}
}
}
// Stick the CookieSpec and CookieOrigin instances to the HTTP context
// so they could be obtained by the response interceptor
context.setAttribute(ClientContext.COOKIE_SPEC, cookieSpec);
context.setAttribute(ClientContext.COOKIE_ORIGIN, cookieOrigin);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.protocol;
import java.io.IOException;
import java.util.Locale;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
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.annotation.Immutable;
import org.apache.ogt.http.client.entity.DeflateDecompressingEntity;
import org.apache.ogt.http.client.entity.GzipDecompressingEntity;
import org.apache.ogt.http.protocol.HttpContext;
/**
* {@link HttpResponseInterceptor} responsible for processing Content-Encoding
* responses.
* <p>
* Instances of this class are stateless and immutable, therefore threadsafe.
*
* @since 4.1
*
*/
@Immutable
public class ResponseContentEncoding implements HttpResponseInterceptor {
/**
* Handles the following {@code Content-Encoding}s by
* using the appropriate decompressor to wrap the response Entity:
* <ul>
* <li>gzip - see {@link GzipDecompressingEntity}</li>
* <li>deflate - see {@link DeflateDecompressingEntity}</li>
* <li>identity - no action needed</li>
* </ul>
*
* @param response the response which contains the entity
* @param context not currently used
*
* @throws HttpException if the {@code Content-Encoding} is none of the above
*/
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpEntity entity = response.getEntity();
// It wasn't a 304 Not Modified response, 204 No Content or similar
if (entity != null) {
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (HeaderElement codec : codecs) {
String codecname = codec.getName().toLowerCase(Locale.US);
if ("gzip".equals(codecname) || "x-gzip".equals(codecname)) {
response.setEntity(new GzipDecompressingEntity(response.getEntity()));
return;
} else if ("deflate".equals(codecname)) {
response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
return;
} else if ("identity".equals(codecname)) {
/* Don't need to transform the content - no-op */
return;
} else {
throw new HttpException("Unsupported Content-Coding: " + codec.getName());
}
}
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.protocol;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.AuthState;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.client.AuthCache;
import org.apache.ogt.http.client.CredentialsProvider;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Request interceptor that can preemptively authenticate against known hosts,
* if there is a cached {@link AuthScheme} instance in the local
* {@link AuthCache} associated with the given target or proxy host.
*
* @since 4.1
*/
@Immutable
public class RequestAuthCache implements HttpRequestInterceptor {
private final Log log = LogFactory.getLog(getClass());
public RequestAuthCache() {
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");
}
AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
if (authCache == null) {
this.log.debug("Auth cache not set in the context");
return;
}
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
ClientContext.CREDS_PROVIDER);
if (credsProvider == null) {
this.log.debug("Credentials provider not set in the context");
return;
}
HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
if (target != null && targetState != null && targetState.getAuthScheme() == null) {
AuthScheme authScheme = authCache.get(target);
if (authScheme != null) {
doPreemptiveAuth(target, authScheme, targetState, credsProvider);
}
}
HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE);
if (proxy != null && proxyState != null && proxyState.getAuthScheme() == null) {
AuthScheme authScheme = authCache.get(proxy);
if (authScheme != null) {
doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider);
}
}
}
private void doPreemptiveAuth(
final HttpHost host,
final AuthScheme authScheme,
final AuthState authState,
final CredentialsProvider credsProvider) {
String schemeName = authScheme.getSchemeName();
if (this.log.isDebugEnabled()) {
this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
}
AuthScope authScope = new AuthScope(host.getHostName(), host.getPort(),
AuthScope.ANY_REALM, schemeName);
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(authScheme);
authState.setCredentials(creds);
} else {
this.log.debug("No credentials for preemptive authentication");
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.protocol;
import java.util.List;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.auth.AuthSchemeRegistry;
import org.apache.ogt.http.client.CookieStore;
import org.apache.ogt.http.client.CredentialsProvider;
import org.apache.ogt.http.cookie.CookieSpecRegistry;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Configuration facade for {@link HttpContext} instances.
*
* @since 4.0
*/
@NotThreadSafe
public class ClientContextConfigurer implements ClientContext {
private final HttpContext context;
public ClientContextConfigurer (final HttpContext context) {
if (context == null)
throw new IllegalArgumentException("HTTP context may not be null");
this.context = context;
}
public void setCookieSpecRegistry(final CookieSpecRegistry registry) {
this.context.setAttribute(COOKIESPEC_REGISTRY, registry);
}
public void setAuthSchemeRegistry(final AuthSchemeRegistry registry) {
this.context.setAttribute(AUTHSCHEME_REGISTRY, registry);
}
public void setCookieStore(final CookieStore store) {
this.context.setAttribute(COOKIE_STORE, store);
}
public void setCredentialsProvider(final CredentialsProvider provider) {
this.context.setAttribute(CREDS_PROVIDER, provider);
}
/**
* @deprecated (4.1-alpha1) Use {@link HttpParams#setParameter(String, Object)} to set the parameters
* {@link org.apache.ogt.http.auth.params.AuthPNames#TARGET_AUTH_PREF AuthPNames#TARGET_AUTH_PREF} and
* {@link org.apache.ogt.http.auth.params.AuthPNames#PROXY_AUTH_PREF AuthPNames#PROXY_AUTH_PREF} instead
*/
@Deprecated
public void setAuthSchemePref(final List<String> list) {
this.context.setAttribute(AUTH_SCHEME_PREF, list);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.protocol;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthState;
import org.apache.ogt.http.auth.AuthenticationException;
import org.apache.ogt.http.auth.ContextAwareAuthScheme;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Generates authentication header for the target host, if required,
* based on the actual state of the HTTP authentication context.
*
* @since 4.0
*/
@Immutable
public class RequestTargetAuthentication implements HttpRequestInterceptor {
private final Log log = LogFactory.getLog(getClass());
public RequestTargetAuthentication() {
super();
}
@SuppressWarnings("deprecation")
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");
}
String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase("CONNECT")) {
return;
}
if (request.containsHeader(AUTH.WWW_AUTH_RESP)) {
return;
}
// Obtain authentication state
AuthState authState = (AuthState) context.getAttribute(
ClientContext.TARGET_AUTH_STATE);
if (authState == null) {
this.log.debug("Target auth state not set in the context");
return;
}
AuthScheme authScheme = authState.getAuthScheme();
if (authScheme == null) {
return;
}
Credentials creds = authState.getCredentials();
if (creds == null) {
this.log.debug("User credentials not available");
return;
}
if (authState.getAuthScope() != null || !authScheme.isConnectionBased()) {
try {
Header header;
if (authScheme instanceof ContextAwareAuthScheme) {
header = ((ContextAwareAuthScheme) authScheme).authenticate(
creds, request, context);
} else {
header = authScheme.authenticate(creds, request);
}
request.addHeader(header);
} catch (AuthenticationException ex) {
if (this.log.isErrorEnabled()) {
this.log.error("Authentication error: " + ex.getMessage());
}
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.protocol;
import java.io.IOException;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderIterator;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.client.CookieStore;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SM;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Response interceptor that populates the current {@link CookieStore} with data
* contained in response cookies received in the given the HTTP response.
*
* @since 4.0
*/
@Immutable
public class ResponseProcessCookies implements HttpResponseInterceptor {
private final Log log = LogFactory.getLog(getClass());
public ResponseProcessCookies() {
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 (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
// Obtain actual CookieSpec instance
CookieSpec cookieSpec = (CookieSpec) context.getAttribute(
ClientContext.COOKIE_SPEC);
if (cookieSpec == null) {
this.log.debug("Cookie spec not specified in HTTP context");
return;
}
// Obtain cookie store
CookieStore cookieStore = (CookieStore) context.getAttribute(
ClientContext.COOKIE_STORE);
if (cookieStore == null) {
this.log.debug("Cookie store not specified in HTTP context");
return;
}
// Obtain actual CookieOrigin instance
CookieOrigin cookieOrigin = (CookieOrigin) context.getAttribute(
ClientContext.COOKIE_ORIGIN);
if (cookieOrigin == null) {
this.log.debug("Cookie origin not specified in HTTP context");
return;
}
HeaderIterator it = response.headerIterator(SM.SET_COOKIE);
processCookies(it, cookieSpec, cookieOrigin, cookieStore);
// see if the cookie spec supports cookie versioning.
if (cookieSpec.getVersion() > 0) {
// process set-cookie2 headers.
// Cookie2 will replace equivalent Cookie instances
it = response.headerIterator(SM.SET_COOKIE2);
processCookies(it, cookieSpec, cookieOrigin, cookieStore);
}
}
private void processCookies(
final HeaderIterator iterator,
final CookieSpec cookieSpec,
final CookieOrigin cookieOrigin,
final CookieStore cookieStore) {
while (iterator.hasNext()) {
Header header = iterator.nextHeader();
try {
List<Cookie> cookies = cookieSpec.parse(header, cookieOrigin);
for (Cookie cookie : cookies) {
try {
cookieSpec.validate(cookie, cookieOrigin);
cookieStore.addCookie(cookie);
if (this.log.isDebugEnabled()) {
this.log.debug("Cookie accepted: \""
+ cookie + "\". ");
}
} catch (MalformedCookieException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Cookie rejected: \""
+ cookie + "\". " + ex.getMessage());
}
}
}
} catch (MalformedCookieException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Invalid cookie header: \""
+ header + "\". " + ex.getMessage());
}
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.protocol;
import java.io.IOException;
import java.util.Collection;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.client.params.ClientPNames;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Request interceptor that adds default request headers.
*
* @since 4.0
*/
@Immutable
public class RequestDefaultHeaders implements HttpRequestInterceptor {
public RequestDefaultHeaders() {
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;
}
// Add default headers
@SuppressWarnings("unchecked")
Collection<Header> defHeaders = (Collection<Header>) request.getParams().getParameter(
ClientPNames.DEFAULT_HEADERS);
if (defHeaders != null) {
for (Header defHeader : defHeaders) {
request.addHeader(defHeader);
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.protocol;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.conn.HttpRoutedConnection;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.protocol.HttpContext;
/**
* This protocol interceptor is responsible for adding <code>Connection</code>
* or <code>Proxy-Connection</code> headers to the outgoing requests, which
* is essential for managing persistence of <code>HTTP/1.0</code> connections.
*
* @since 4.0
*/
@Immutable
public class RequestClientConnControl implements HttpRequestInterceptor {
private final Log log = LogFactory.getLog(getClass());
private static final String PROXY_CONN_DIRECTIVE = "Proxy-Connection";
public RequestClientConnControl() {
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")) {
request.setHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
return;
}
// Obtain the client connection (required)
HttpRoutedConnection conn = (HttpRoutedConnection) context.getAttribute(
ExecutionContext.HTTP_CONNECTION);
if (conn == null) {
this.log.debug("HTTP connection not set in the context");
return;
}
HttpRoute route = conn.getRoute();
if (route.getHopCount() == 1 || route.isTunnelled()) {
if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) {
request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
}
}
if (route.getHopCount() == 2 && !route.isTunnelled()) {
if (!request.containsHeader(PROXY_CONN_DIRECTIVE)) {
request.addHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client;
import java.util.Map;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthenticationException;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.protocol.HttpContext;
/**
/**
* A handler for determining if an HTTP response represents an authentication
* challenge that was sent back to the client as a result of authentication
* failure.
* <p>
* Implementations of this interface must be thread-safe. Access to shared
* data must be synchronized as methods of this interface may be executed
* from multiple threads.
*
* @since 4.0
*/
public interface AuthenticationHandler {
/**
* Determines if the given HTTP response response represents
* an authentication challenge that was sent back as a result
* of authentication failure
* @param response HTTP response.
* @param context HTTP context.
* @return <code>true</code> if user authentication is required,
* <code>false</code> otherwise.
*/
boolean isAuthenticationRequested(
HttpResponse response,
HttpContext context);
/**
* Extracts from the given HTTP response a collection of authentication
* challenges, each of which represents an authentication scheme supported
* by the authentication host.
*
* @param response HTTP response.
* @param context HTTP context.
* @return a collection of challenges keyed by names of corresponding
* authentication schemes.
* @throws MalformedChallengeException if one of the authentication
* challenges is not valid or malformed.
*/
Map<String, Header> getChallenges(
HttpResponse response,
HttpContext context) throws MalformedChallengeException;
/**
* Selects one authentication challenge out of all available and
* creates and generates {@link AuthScheme} instance capable of
* processing that challenge.
* @param challenges collection of challenges.
* @param response HTTP response.
* @param context HTTP context.
* @return authentication scheme to use for authentication.
* @throws AuthenticationException if an authentication scheme
* could not be selected.
*/
AuthScheme selectScheme(
Map<String, Header> challenges,
HttpResponse response,
HttpContext context) throws AuthenticationException;
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.annotation.Immutable;
/**
* Signals violation of HTTP specification caused by an invalid redirect
*
*
* @since 4.0
*/
@Immutable
public class RedirectException extends ProtocolException {
private static final long serialVersionUID = 4418824536372559326L;
/**
* Creates a new RedirectException with a <tt>null</tt> detail message.
*/
public RedirectException() {
super();
}
/**
* Creates a new RedirectException with the specified detail message.
*
* @param message The exception detail message
*/
public RedirectException(String message) {
super(message);
}
/**
* Creates a new RedirectException 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 RedirectException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.client.methods.HttpUriRequest;
import org.apache.ogt.http.protocol.HttpContext;
/**
* A strategy for determining if an HTTP request should be redirected to
* a new location in response to an HTTP response received from the target
* server.
* <p>
* Implementations of this interface must be thread-safe. Access to shared
* data must be synchronized as methods of this interface may be executed
* from multiple threads.
*
* @since 4.1
*/
public interface RedirectStrategy {
/**
* Determines if a request should be redirected to a new location
* given the response from the target server.
*
* @param request the executed request
* @param response the response received from the target server
* @param context the context for the request execution
*
* @return <code>true</code> if the request should be redirected, <code>false</code>
* otherwise
*/
boolean isRedirected(
HttpRequest request,
HttpResponse response,
HttpContext context) throws ProtocolException;
/**
* Determines the redirect location given the response from the target
* server and the current request execution context and generates a new
* request to be sent to the location.
*
* @param request the executed request
* @param response the response received from the target server
* @param context the context for the request execution
*
* @return redirected request
*/
HttpUriRequest getRedirect(
HttpRequest request,
HttpResponse response,
HttpContext context) throws ProtocolException;
} | Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client;
import java.io.IOException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.methods.HttpUriRequest;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.HttpContext;
/**
* This interface represents only the most basic contract for HTTP request
* execution. It imposes no restrictions or particular details on the request
* execution process and leaves the specifics of state management,
* authentication and redirect handling up to individual implementations.
* This should make it easier to decorate the interface with additional
* functionality such as response content caching.
* <p/>
* The usual execution flow can be demonstrated by the code snippet below:
* <PRE>
* HttpClient httpclient = new DefaultHttpClient();
*
* // Prepare a request object
* HttpGet httpget = new HttpGet("http://www.apache.org/");
*
* // Execute the request
* HttpResponse response = httpclient.execute(httpget);
*
* // Examine the response status
* System.out.println(response.getStatusLine());
*
* // Get hold of the response entity
* HttpEntity entity = response.getEntity();
*
* // If the response does not enclose an entity, there is no need
* // to worry about connection release
* if (entity != null) {
* InputStream instream = entity.getContent();
* try {
*
* BufferedReader reader = new BufferedReader(
* new InputStreamReader(instream));
* // do something useful with the response
* System.out.println(reader.readLine());
*
* } catch (IOException ex) {
*
* // In case of an IOException the connection will be released
* // back to the connection manager automatically
* throw ex;
*
* } catch (RuntimeException ex) {
*
* // In case of an unexpected exception you may want to abort
* // the HTTP request in order to shut down the underlying
* // connection and release it back to the connection manager.
* httpget.abort();
* throw ex;
*
* } finally {
*
* // Closing the input stream will trigger connection release
* instream.close();
*
* }
*
* // When HttpClient instance is no longer needed,
* // shut down the connection manager to ensure
* // immediate deallocation of all system resources
* httpclient.getConnectionManager().shutdown();
* }
* </PRE>
*
* @since 4.0
*/
public interface HttpClient {
/**
* Obtains the parameters for this client.
* These parameters will become defaults for all requests being
* executed with this client, and for the parameters of
* dependent objects in this client.
*
* @return the default parameters
*/
HttpParams getParams();
/**
* Obtains the connection manager used by this client.
*
* @return the connection manager
*/
ClientConnectionManager getConnectionManager();
/**
* Executes a request using the default context.
*
* @param request the request to execute
*
* @return the response to the request. This is always a final response,
* never an intermediate response with an 1xx status code.
* Whether redirects or authentication challenges will be returned
* or handled automatically depends on the implementation and
* configuration of this client.
* @throws IOException in case of a problem or the connection was aborted
* @throws ClientProtocolException in case of an http protocol error
*/
HttpResponse execute(HttpUriRequest request)
throws IOException, ClientProtocolException;
/**
* Executes a request using the given context.
* The route to the target will be determined by the HTTP client.
*
* @param request the request to execute
* @param context the context to use for the execution, or
* <code>null</code> to use the default context
*
* @return the response to the request. This is always a final response,
* never an intermediate response with an 1xx status code.
* Whether redirects or authentication challenges will be returned
* or handled automatically depends on the implementation and
* configuration of this client.
* @throws IOException in case of a problem or the connection was aborted
* @throws ClientProtocolException in case of an http protocol error
*/
HttpResponse execute(HttpUriRequest request, HttpContext context)
throws IOException, ClientProtocolException;
/**
* Executes a request to the target using the default context.
*
* @param target the target host for the request.
* Implementations may accept <code>null</code>
* if they can still determine a route, for example
* to a default target or by inspecting the request.
* @param request the request to execute
*
* @return the response to the request. This is always a final response,
* never an intermediate response with an 1xx status code.
* Whether redirects or authentication challenges will be returned
* or handled automatically depends on the implementation and
* configuration of this client.
* @throws IOException in case of a problem or the connection was aborted
* @throws ClientProtocolException in case of an http protocol error
*/
HttpResponse execute(HttpHost target, HttpRequest request)
throws IOException, ClientProtocolException;
/**
* Executes a request to the target using the given context.
*
* @param target the target host for the request.
* Implementations may accept <code>null</code>
* if they can still determine a route, for example
* to a default target or by inspecting the request.
* @param request the request to execute
* @param context the context to use for the execution, or
* <code>null</code> to use the default context
*
* @return the response to the request. This is always a final response,
* never an intermediate response with an 1xx status code.
* Whether redirects or authentication challenges will be returned
* or handled automatically depends on the implementation and
* configuration of this client.
* @throws IOException in case of a problem or the connection was aborted
* @throws ClientProtocolException in case of an http protocol error
*/
HttpResponse execute(HttpHost target, HttpRequest request,
HttpContext context)
throws IOException, ClientProtocolException;
/**
* Executes a request using the default context and processes the
* response using the given response handler.
*
* @param request the request to execute
* @param responseHandler the response handler
*
* @return the response object as generated by the response handler.
* @throws IOException in case of a problem or the connection was aborted
* @throws ClientProtocolException in case of an http protocol error
*/
<T> T execute(
HttpUriRequest request,
ResponseHandler<? extends T> responseHandler)
throws IOException, ClientProtocolException;
/**
* Executes a request using the given context and processes the
* response using the given response handler.
*
* @param request the request to execute
* @param responseHandler the response handler
*
* @return the response object as generated by the response handler.
* @throws IOException in case of a problem or the connection was aborted
* @throws ClientProtocolException in case of an http protocol error
*/
<T> T execute(
HttpUriRequest request,
ResponseHandler<? extends T> responseHandler,
HttpContext context)
throws IOException, ClientProtocolException;
/**
* Executes a request to the target using the default context and
* processes the response using the given response handler.
*
* @param target the target host for the request.
* Implementations may accept <code>null</code>
* if they can still determine a route, for example
* to a default target or by inspecting the request.
* @param request the request to execute
* @param responseHandler the response handler
*
* @return the response object as generated by the response handler.
* @throws IOException in case of a problem or the connection was aborted
* @throws ClientProtocolException in case of an http protocol error
*/
<T> T execute(
HttpHost target,
HttpRequest request,
ResponseHandler<? extends T> responseHandler)
throws IOException, ClientProtocolException;
/**
* Executes a request to the target using the given context and
* processes the response using the given response handler.
*
* @param target the target host for the request.
* Implementations may accept <code>null</code>
* if they can still determine a route, for example
* to a default target or by inspecting the request.
* @param request the request to execute
* @param responseHandler the response handler
* @param context the context to use for the execution, or
* <code>null</code> to use the default context
*
* @return the response object as generated by the response handler.
* @throws IOException in case of a problem or the connection was aborted
* @throws ClientProtocolException in case of an http protocol error
*/
<T> T execute(
HttpHost target,
HttpRequest request,
ResponseHandler<? extends T> responseHandler,
HttpContext context)
throws IOException, ClientProtocolException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client;
import java.io.IOException;
import org.apache.ogt.http.protocol.HttpContext;
/**
* A handler for determining if an HttpRequest should be retried after a
* recoverable exception during execution.
* <p>
* Implementations of this interface must be thread-safe. Access to shared
* data must be synchronized as methods of this interface may be executed
* from multiple threads.
*
* @since 4.0
*/
public interface HttpRequestRetryHandler {
/**
* Determines if a method should be retried after an IOException
* occurs during execution.
*
* @param exception the exception that occurred
* @param executionCount the number of times this method has been
* unsuccessfully executed
* @param context the context for the request execution
*
* @return <code>true</code> if the method should be retried, <code>false</code>
* otherwise
*/
boolean retryRequest(IOException exception, int executionCount, HttpContext context);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.protocol.HttpContext;
/**
* A client-side request director.
* The director decides which steps are necessary to execute a request.
* It establishes connections and optionally processes redirects and
* authentication challenges. The director may therefore generate and
* send a sequence of requests in order to execute one initial request.
*
* @since 4.0
*/
public interface RequestDirector {
/**
* Executes a request.
* <br/><b>Note:</b>
* For the time being, a new director is instantiated for each request.
* This is the same behavior as for <code>HttpMethodDirector</code>
* in HttpClient 3.
*
* @param target the target host for the request.
* Implementations may accept <code>null</code>
* if they can still determine a route, for example
* to a default target or by inspecting the request.
* @param request the request to execute
* @param context the context for executing the request
*
* @return the final response to the request.
* This is never an intermediate response with status code 1xx.
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
* or if the connection was aborted
*/
HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
throws HttpException, IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client;
import org.apache.ogt.http.protocol.HttpContext;
/**
* A handler for determining if the given execution context is user specific
* or not. The token object returned by this handler is expected to uniquely
* identify the current user if the context is user specific or to be
* <code>null</code> if the context does not contain any resources or details
* specific to the current user.
* <p/>
* The user token will be used to ensure that user specific resources will not
* be shared with or reused by other users.
*
* @since 4.0
*/
public interface UserTokenHandler {
/**
* The token object returned by this method is expected to uniquely
* identify the current user if the context is user specific or to be
* <code>null</code> if it is not.
*
* @param context the execution context
*
* @return user token that uniquely identifies the user or
* <code>null</null> if the context is not user specific.
*/
Object getUserToken(HttpContext context);
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.auth.AuthScheme;
/**
* Abstract {@link AuthScheme} cache. Initialized {@link AuthScheme} objects
* from this cache can be used to preemptively authenticate against known
* hosts.
*
* @since 4.1
*/
public interface AuthCache {
void put(HttpHost host, AuthScheme authScheme);
AuthScheme get(HttpHost host);
void remove(HttpHost host);
void clear();
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client;
import java.io.IOException;
import org.apache.ogt.http.HttpResponse;
/**
* Handler that encapsulates the process of generating a response object
* from a {@link HttpResponse}.
*
*
* @since 4.0
*/
public interface ResponseHandler<T> {
/**
* Processes an {@link HttpResponse} and returns some value
* corresponding to that response.
*
* @param response The response to process
* @return A value determined by the response
*
* @throws ClientProtocolException in case of an http protocol error
* @throws IOException in case of a problem or the connection was aborted
*/
T handleResponse(HttpResponse response) throws ClientProtocolException, IOException;
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.annotation.Immutable;
/**
* Signals failure to retry the request due to non-repeatable request
* entity.
*
*
* @since 4.0
*/
@Immutable
public class NonRepeatableRequestException extends ProtocolException {
private static final long serialVersionUID = 82685265288806048L;
/**
* Creates a new NonRepeatableEntityException with a <tt>null</tt> detail message.
*/
public NonRepeatableRequestException() {
super();
}
/**
* Creates a new NonRepeatableEntityException with the specified detail message.
*
* @param message The exception detail message
*/
public NonRepeatableRequestException(String message) {
super(message);
}
/**
* Creates a new NonRepeatableEntityException with the specified detail message.
*
* @param message The exception detail message
* @param cause the cause
*/
public NonRepeatableRequestException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client;
import java.io.IOException;
import org.apache.ogt.http.annotation.Immutable;
/**
* Signals an error in the HTTP protocol.
*
* @since 4.0
*/
@Immutable
public class ClientProtocolException extends IOException {
private static final long serialVersionUID = -5596590843227115865L;
public ClientProtocolException() {
super();
}
public ClientProtocolException(String s) {
super(s);
}
public ClientProtocolException(Throwable cause) {
initCause(cause);
}
public ClientProtocolException(String message, Throwable cause) {
super(message);
initCause(cause);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.entity.HttpEntityWrapper;
/**
* Common base class for decompressing {@link HttpEntity} implementations.
*
* @since 4.1
*/
abstract class DecompressingEntity extends HttpEntityWrapper {
/**
* Default buffer size.
*/
private static final int BUFFER_SIZE = 1024 * 2;
/**
* Creates a new {@link DecompressingEntity}.
*
* @param wrapped
* the non-null {@link HttpEntity} to be wrapped
*/
public DecompressingEntity(final HttpEntity wrapped) {
super(wrapped);
}
/**
* {@inheritDoc}
*/
@Override
public void writeTo(OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream instream = getContent();
byte[] buffer = new byte[BUFFER_SIZE];
int l;
while ((l = instream.read(buffer)) != -1) {
outstream.write(buffer, 0, l);
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.entity;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.client.utils.URLEncodedUtils;
import org.apache.ogt.http.entity.StringEntity;
import org.apache.ogt.http.protocol.HTTP;
/**
* An entity composed of a list of url-encoded pairs.
* This is typically useful while sending an HTTP POST request.
*
* @since 4.0
*/
@NotThreadSafe // AbstractHttpEntity is not thread-safe
public class UrlEncodedFormEntity extends StringEntity {
/**
* Constructs a new {@link UrlEncodedFormEntity} with the list
* of parameters in the specified encoding.
*
* @param parameters list of name/value pairs
* @param encoding encoding the name/value pairs be encoded with
* @throws UnsupportedEncodingException if the encoding isn't supported
*/
public UrlEncodedFormEntity (
final List <? extends NameValuePair> parameters,
final String encoding) throws UnsupportedEncodingException {
super(URLEncodedUtils.format(parameters, encoding), encoding);
setContentType(URLEncodedUtils.CONTENT_TYPE + HTTP.CHARSET_PARAM +
(encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET));
}
/**
* Constructs a new {@link UrlEncodedFormEntity} with the list
* of parameters with the default encoding of {@link HTTP#DEFAULT_CONTENT_CHARSET}
*
* @param parameters list of name/value pairs
* @throws UnsupportedEncodingException if the default encoding isn't supported
*/
public UrlEncodedFormEntity (
final List <? extends NameValuePair> parameters) throws UnsupportedEncodingException {
this(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.entity.HttpEntityWrapper;
/**
* {@link HttpEntityWrapper} responsible for handling deflate Content Coded responses. In RFC2616
* terms, <code>deflate</code> means a <code>zlib</code> stream as defined in RFC1950. Some server
* implementations have misinterpreted RFC2616 to mean that a <code>deflate</code> stream as
* defined in RFC1951 should be used (or maybe they did that since that's how IE behaves?). It's
* confusing that <code>deflate</code> in HTTP 1.1 means <code>zlib</code> streams rather than
* <code>deflate</code> streams. We handle both types in here, since that's what is seen on the
* internet. Moral - prefer <code>gzip</code>!
*
* @see GzipDecompressingEntity
*
* @since 4.1
*/
public class DeflateDecompressingEntity extends DecompressingEntity {
/**
* Creates a new {@link DeflateDecompressingEntity} which will wrap the specified
* {@link HttpEntity}.
*
* @param entity
* a non-null {@link HttpEntity} to be wrapped
*/
public DeflateDecompressingEntity(final HttpEntity entity) {
super(entity);
}
/**
* {@inheritDoc}
*/
@Override
public InputStream getContent() throws IOException {
InputStream wrapped = this.wrappedEntity.getContent();
/*
* A zlib stream will have a header.
*
* CMF | FLG [| DICTID ] | ...compressed data | ADLER32 |
*
* * CMF is one byte.
*
* * FLG is one byte.
*
* * DICTID is four bytes, and only present if FLG.FDICT is set.
*
* Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950,
* section 2.2. http://tools.ietf.org/html/rfc1950#page-4
*
* We need to see if it looks like a proper zlib stream, or whether it is just a deflate
* stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers
* implement deflate Content-Encoding using deflate streams, rather than zlib streams.
*
* We could start looking at the bytes, but to be honest, someone else has already read
* the RFCs and implemented that for us. So we'll just use the JDK libraries and exception
* handling to do this. If that proves slow, then we could potentially change this to check
* the first byte - does it look like a CMF? What about the second byte - does it look like
* a FLG, etc.
*/
/* We read a small buffer to sniff the content. */
byte[] peeked = new byte[6];
PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length);
int headerLength = pushback.read(peeked);
if (headerLength == -1) {
throw new IOException("Unable to read the response");
}
/* We try to read the first uncompressed byte. */
byte[] dummy = new byte[1];
Inflater inf = new Inflater();
try {
int n;
while ((n = inf.inflate(dummy)) == 0) {
if (inf.finished()) {
/* Not expecting this, so fail loudly. */
throw new IOException("Unable to read the response");
}
if (inf.needsDictionary()) {
/* Need dictionary - then it must be zlib stream with DICTID part? */
break;
}
if (inf.needsInput()) {
inf.setInput(peeked);
}
}
if (n == -1) {
throw new IOException("Unable to read the response");
}
/*
* We read something without a problem, so it's a valid zlib stream. Just need to reset
* and return an unused InputStream now.
*/
pushback.unread(peeked, 0, headerLength);
return new InflaterInputStream(pushback);
} catch (DataFormatException e) {
/* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try
* again. */
pushback.unread(peeked, 0, headerLength);
return new InflaterInputStream(pushback, new Inflater(true));
}
}
/**
* {@inheritDoc}
*/
@Override
public Header getContentEncoding() {
/* This HttpEntityWrapper has dealt with the Content-Encoding. */
return null;
}
/**
* {@inheritDoc}
*/
@Override
public long getContentLength() {
/* Length of inflated content is unknown. */
return -1;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.entity;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.entity.HttpEntityWrapper;
/**
* {@link HttpEntityWrapper} for handling gzip Content Coded responses.
*
* @since 4.1
*/
public class GzipDecompressingEntity extends DecompressingEntity {
/**
* Creates a new {@link GzipDecompressingEntity} which will wrap the specified
* {@link HttpEntity}.
*
* @param entity
* the non-null {@link HttpEntity} to be wrapped
*/
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
/**
* {@inheritDoc}
*/
@Override
public InputStream getContent() throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
/**
* {@inheritDoc}
*/
@Override
public Header getContentEncoding() {
/* This HttpEntityWrapper has dealt with the Content-Encoding. */
return null;
}
/**
* {@inheritDoc}
*/
@Override
public long getContentLength() {
/* length of ungzipped content is not known */
return -1;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.methods;
import java.net.URI;
import org.apache.ogt.http.annotation.NotThreadSafe;
/**
* HTTP DELETE method
* <p>
* The HTTP DELETE method is defined in section 9.7 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The DELETE method requests that the origin server delete the resource
* identified by the Request-URI. [...] The client cannot
* be guaranteed that the operation has been carried out, even if the
* status code returned from the origin server indicates that the action
* has been completed successfully.
* </blockquote>
*
* @since 4.0
*/
@NotThreadSafe // HttpRequestBase is @NotThreadSafe
public class HttpDelete extends HttpRequestBase {
public final static String METHOD_NAME = "DELETE";
public HttpDelete() {
super();
}
public HttpDelete(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpDelete(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.methods;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.RequestLine;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.client.utils.CloneUtils;
import org.apache.ogt.http.conn.ClientConnectionRequest;
import org.apache.ogt.http.conn.ConnectionReleaseTrigger;
import org.apache.ogt.http.message.AbstractHttpMessage;
import org.apache.ogt.http.message.BasicRequestLine;
import org.apache.ogt.http.message.HeaderGroup;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
/**
* Basic implementation of an HTTP request that can be modified.
*
*
* @since 4.0
*/
@NotThreadSafe
public abstract class HttpRequestBase extends AbstractHttpMessage
implements HttpUriRequest, AbortableHttpRequest, Cloneable {
private Lock abortLock;
private boolean aborted;
private URI uri;
private ClientConnectionRequest connRequest;
private ConnectionReleaseTrigger releaseTrigger;
public HttpRequestBase() {
super();
this.abortLock = new ReentrantLock();
}
public abstract String getMethod();
public ProtocolVersion getProtocolVersion() {
return HttpProtocolParams.getVersion(getParams());
}
/**
* Returns the original request URI.
* <p>
* Please note URI remains unchanged in the course of request execution and
* is not updated if the request is redirected to another location.
*/
public URI getURI() {
return this.uri;
}
public RequestLine getRequestLine() {
String method = getMethod();
ProtocolVersion ver = getProtocolVersion();
URI uri = getURI();
String uritext = null;
if (uri != null) {
uritext = uri.toASCIIString();
}
if (uritext == null || uritext.length() == 0) {
uritext = "/";
}
return new BasicRequestLine(method, uritext, ver);
}
public void setURI(final URI uri) {
this.uri = uri;
}
public void setConnectionRequest(final ClientConnectionRequest connRequest)
throws IOException {
this.abortLock.lock();
try {
if (this.aborted) {
throw new IOException("Request already aborted");
}
this.releaseTrigger = null;
this.connRequest = connRequest;
} finally {
this.abortLock.unlock();
}
}
public void setReleaseTrigger(final ConnectionReleaseTrigger releaseTrigger)
throws IOException {
this.abortLock.lock();
try {
if (this.aborted) {
throw new IOException("Request already aborted");
}
this.connRequest = null;
this.releaseTrigger = releaseTrigger;
} finally {
this.abortLock.unlock();
}
}
public void abort() {
ClientConnectionRequest localRequest;
ConnectionReleaseTrigger localTrigger;
this.abortLock.lock();
try {
if (this.aborted) {
return;
}
this.aborted = true;
localRequest = connRequest;
localTrigger = releaseTrigger;
} finally {
this.abortLock.unlock();
}
// Trigger the callbacks outside of the lock, to prevent
// deadlocks in the scenario where the callbacks have
// their own locks that may be used while calling
// setReleaseTrigger or setConnectionRequest.
if (localRequest != null) {
localRequest.abortRequest();
}
if (localTrigger != null) {
try {
localTrigger.abortConnection();
} catch (IOException ex) {
// ignore
}
}
}
public boolean isAborted() {
return this.aborted;
}
@Override
public Object clone() throws CloneNotSupportedException {
HttpRequestBase clone = (HttpRequestBase) super.clone();
clone.abortLock = new ReentrantLock();
clone.aborted = false;
clone.releaseTrigger = null;
clone.connRequest = null;
clone.headergroup = (HeaderGroup) CloneUtils.clone(this.headergroup);
clone.params = (HttpParams) CloneUtils.clone(this.params);
return clone;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.methods;
import java.net.URI;
import org.apache.ogt.http.annotation.NotThreadSafe;
/**
* HTTP GET method.
* <p>
* The HTTP GET method is defined in section 9.3 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The GET method means retrieve whatever information (in the form of an
* entity) is identified by the Request-URI. If the Request-URI refers
* to a data-producing process, it is the produced data which shall be
* returned as the entity in the response and not the source text of the
* process, unless that text happens to be the output of the process.
* </blockquote>
* </p>
*
* @since 4.0
*/
@NotThreadSafe
public class HttpGet extends HttpRequestBase {
public final static String METHOD_NAME = "GET";
public HttpGet() {
super();
}
public HttpGet(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpGet(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.methods;
import java.net.URI;
import org.apache.ogt.http.annotation.NotThreadSafe;
/**
* HTTP TRACE method.
* <p>
* The HTTP TRACE method is defined in section 9.6 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The TRACE method is used to invoke a remote, application-layer loop-
* back of the request message. The final recipient of the request
* SHOULD reflect the message received back to the client as the
* entity-body of a 200 (OK) response. The final recipient is either the
* origin server or the first proxy or gateway to receive a Max-Forwards
* value of zero (0) in the request (see section 14.31). A TRACE request
* MUST NOT include an entity.
* </blockquote>
* </p>
*
* @since 4.0
*/
@NotThreadSafe
public class HttpTrace extends HttpRequestBase {
public final static String METHOD_NAME = "TRACE";
public HttpTrace() {
super();
}
public HttpTrace(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpTrace(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.methods;
import java.net.URI;
import org.apache.ogt.http.annotation.NotThreadSafe;
/**
* HTTP POST method.
* <p>
* The HTTP POST method is defined in section 9.5 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The POST method is used to request that the origin server accept the entity
* enclosed in the request as a new subordinate of the resource identified by
* the Request-URI in the Request-Line. POST is designed to allow a uniform
* method to cover the following functions:
* <ul>
* <li>Annotation of existing resources</li>
* <li>Posting a message to a bulletin board, newsgroup, mailing list, or
* similar group of articles</li>
* <li>Providing a block of data, such as the result of submitting a form,
* to a data-handling process</li>
* <li>Extending a database through an append operation</li>
* </ul>
* </blockquote>
* </p>
*
* @since 4.0
*/
@NotThreadSafe
public class HttpPost extends HttpEntityEnclosingRequestBase {
public final static String METHOD_NAME = "POST";
public HttpPost() {
super();
}
public HttpPost(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpPost(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.methods;
import java.net.URI;
import org.apache.ogt.http.annotation.NotThreadSafe;
/**
* HTTP PUT method.
* <p>
* The HTTP PUT method is defined in section 9.6 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The PUT method requests that the enclosed entity be stored under the
* supplied Request-URI. If the Request-URI refers to an already
* existing resource, the enclosed entity SHOULD be considered as a
* modified version of the one residing on the origin server.
* </blockquote>
* </p>
*
* @since 4.0
*/
@NotThreadSafe
public class HttpPut extends HttpEntityEnclosingRequestBase {
public final static String METHOD_NAME = "PUT";
public HttpPut() {
super();
}
public HttpPut(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpPut(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.methods;
import java.net.URI;
import org.apache.ogt.http.annotation.NotThreadSafe;
/**
* HTTP HEAD method.
* <p>
* The HTTP HEAD method is defined in section 9.4 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The HEAD method is identical to GET except that the server MUST NOT
* return a message-body in the response. The metainformation contained
* in the HTTP headers in response to a HEAD request SHOULD be identical
* to the information sent in response to a GET request. This method can
* be used for obtaining metainformation about the entity implied by the
* request without transferring the entity-body itself. This method is
* often used for testing hypertext links for validity, accessibility,
* and recent modification.
* </blockquote>
* </p>
*
* @since 4.0
*/
@NotThreadSafe
public class HttpHead extends HttpRequestBase {
public final static String METHOD_NAME = "HEAD";
public HttpHead() {
super();
}
public HttpHead(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpHead(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.methods;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.client.utils.CloneUtils;
import org.apache.ogt.http.protocol.HTTP;
/**
* Basic implementation of an entity enclosing HTTP request
* that can be modified
*
* @since 4.0
*/
@NotThreadSafe // HttpRequestBase is @NotThreadSafe
public abstract class HttpEntityEnclosingRequestBase
extends HttpRequestBase implements HttpEntityEnclosingRequest {
private HttpEntity entity;
public HttpEntityEnclosingRequestBase() {
super();
}
public HttpEntity getEntity() {
return this.entity;
}
public void setEntity(final HttpEntity entity) {
this.entity = entity;
}
public boolean expectContinue() {
Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE);
return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue());
}
@Override
public Object clone() throws CloneNotSupportedException {
HttpEntityEnclosingRequestBase clone =
(HttpEntityEnclosingRequestBase) super.clone();
if (this.entity != null) {
clone.entity = (HttpEntity) CloneUtils.clone(this.entity);
}
return clone;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.methods;
import java.net.URI;
import org.apache.ogt.http.HttpRequest;
/**
* Extended version of the {@link HttpRequest} interface that provides
* convenience methods to access request properties such as request URI
* and method type.
*
*
* <!-- empty lines to avoid svn diff problems -->
* @since 4.0
*/
public interface HttpUriRequest extends HttpRequest {
/**
* Returns the HTTP method this request uses, such as <code>GET</code>,
* <code>PUT</code>, <code>POST</code>, or other.
*/
String getMethod();
/**
* Returns the URI this request uses, such as
* <code>http://example.org/path/to/file</code>.
* <br/>
* Note that the URI may be absolute URI (as above) or may be a relative URI.
* <p>
* Implementations are encouraged to return
* the URI that was initially requested.
* </p>
* <p>
* To find the final URI after any redirects have been processed,
* please see the section entitled
* <a href="http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d4e205">HTTP execution context</a>
* in the
* <a href="http://hc.apache.org/httpcomponents-client-ga/tutorial/html">HttpClient Tutorial</a>
* </p>
*/
URI getURI();
/**
* Aborts execution of the request.
*
* @throws UnsupportedOperationException if the abort operation
* is not supported / cannot be implemented.
*/
void abort() throws UnsupportedOperationException;
/**
* Tests if the request execution has been aborted.
*
* @return <code>true</code> if the request execution has been aborted,
* <code>false</code> otherwise.
*/
boolean isAborted();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.methods;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.HeaderIterator;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.annotation.NotThreadSafe;
/**
* HTTP OPTIONS method.
* <p>
* The HTTP OPTIONS method is defined in section 9.2 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The OPTIONS method represents a request for information about the
* communication options available on the request/response chain
* identified by the Request-URI. This method allows the client to
* determine the options and/or requirements associated with a resource,
* or the capabilities of a server, without implying a resource action
* or initiating a resource retrieval.
* </blockquote>
* </p>
*
* @since 4.0
*/
@NotThreadSafe
public class HttpOptions extends HttpRequestBase {
public final static String METHOD_NAME = "OPTIONS";
public HttpOptions() {
super();
}
public HttpOptions(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpOptions(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
public Set<String> getAllowedMethods(final HttpResponse response) {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
HeaderIterator it = response.headerIterator("Allow");
Set<String> methods = new HashSet<String>();
while (it.hasNext()) {
Header header = it.nextHeader();
HeaderElement[] elements = header.getElements();
for (HeaderElement element : elements) {
methods.add(element.getName());
}
}
return methods;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.methods;
import java.io.IOException;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.ClientConnectionRequest;
import org.apache.ogt.http.conn.ConnectionReleaseTrigger;
import org.apache.ogt.http.conn.ManagedClientConnection;
import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager;
/**
* Interface representing an HTTP request that can be aborted by shutting
* down the underlying HTTP connection.
*
*
* <!-- empty lines to avoid svn diff problems -->
* @since 4.0
*/
public interface AbortableHttpRequest {
/**
* Sets the {@link ClientConnectionRequest} callback that can be
* used to abort a long-lived request for a connection.
* If the request is already aborted, throws an {@link IOException}.
*
* @see ClientConnectionManager
* @see ThreadSafeClientConnManager
*/
void setConnectionRequest(ClientConnectionRequest connRequest) throws IOException;
/**
* Sets the {@link ConnectionReleaseTrigger} callback that can
* be used to abort an active connection.
* Typically, this will be the {@link ManagedClientConnection} itself.
* If the request is already aborted, throws an {@link IOException}.
*/
void setReleaseTrigger(ConnectionReleaseTrigger releaseTrigger) throws IOException;
/**
* Aborts this http request. Any active execution of this method should
* return immediately. If the request has not started, it will abort after
* the next execution. Aborting this request will cause all subsequent
* executions with this request to fail.
*
* @see HttpClient#execute(HttpUriRequest)
* @see HttpClient#execute(org.apache.ogt.http.HttpHost,
* org.apache.ogt.http.HttpRequest)
* @see HttpClient#execute(HttpUriRequest,
* org.apache.ogt.http.protocol.HttpContext)
* @see HttpClient#execute(org.apache.ogt.http.HttpHost,
* org.apache.ogt.http.HttpRequest, org.apache.ogt.http.protocol.HttpContext)
*/
void abort();
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.Credentials;
/**
* Abstract credentials provider that maintains a collection of user
* credentials.
* <p>
* Implementations of this interface must be thread-safe. Access to shared
* data must be synchronized as methods of this interface may be executed
* from multiple threads.
*
* @since 4.0
*/
public interface CredentialsProvider {
/**
* Sets the {@link Credentials credentials} for the given authentication
* scope. Any previous credentials for the given scope will be overwritten.
*
* @param authscope the {@link AuthScope authentication scope}
* @param credentials the authentication {@link Credentials credentials}
* for the given scope.
*
* @see #getCredentials(AuthScope)
*/
void setCredentials(AuthScope authscope, Credentials credentials);
/**
* Get the {@link Credentials credentials} for the given authentication scope.
*
* @param authscope the {@link AuthScope authentication scope}
* @return the credentials
*
* @see #setCredentials(AuthScope, Credentials)
*/
Credentials getCredentials(AuthScope authscope);
/**
* Clears all credentials.
*/
void clear();
}
| Java |
/*
* $HeadURL$
* $Revision$
* $Date$
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.utils;
import org.apache.ogt.http.annotation.Immutable;
/**
* Facade that provides conversion between Unicode and Punycode domain names.
* It will use an appropriate implementation.
*
* @since 4.0
*/
@Immutable
public class Punycode {
private static final Idn impl;
static {
Idn _impl;
try {
_impl = new JdkIdn();
} catch (Exception e) {
_impl = new Rfc3492Idn();
}
impl = _impl;
}
public static String toUnicode(String punycode) {
return impl.toUnicode(punycode);
}
}
| Java |
/*
* $HeadURL$
* $Revision$
* $Date$
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.utils;
import java.util.StringTokenizer;
import org.apache.ogt.http.annotation.Immutable;
/**
* Implementation from pseudo code in RFC 3492.
*
* @since 4.0
*/
@Immutable
public class Rfc3492Idn implements Idn {
private static final int base = 36;
private static final int tmin = 1;
private static final int tmax = 26;
private static final int skew = 38;
private static final int damp = 700;
private static final int initial_bias = 72;
private static final int initial_n = 128;
private static final char delimiter = '-';
private static final String ACE_PREFIX = "xn--";
private int adapt(int delta, int numpoints, boolean firsttime) {
if (firsttime) delta = delta / damp;
else delta = delta / 2;
delta = delta + (delta / numpoints);
int k = 0;
while (delta > ((base - tmin) * tmax) / 2) {
delta = delta / (base - tmin);
k = k + base;
}
return k + (((base - tmin + 1) * delta) / (delta + skew));
}
private int digit(char c) {
if ((c >= 'A') && (c <= 'Z')) return (c - 'A');
if ((c >= 'a') && (c <= 'z')) return (c - 'a');
if ((c >= '0') && (c <= '9')) return (c - '0') + 26;
throw new IllegalArgumentException("illegal digit: "+ c);
}
public String toUnicode(String punycode) {
StringBuilder unicode = new StringBuilder(punycode.length());
StringTokenizer tok = new StringTokenizer(punycode, ".");
while (tok.hasMoreTokens()) {
String t = tok.nextToken();
if (unicode.length() > 0) unicode.append('.');
if (t.startsWith(ACE_PREFIX)) t = decode(t.substring(4));
unicode.append(t);
}
return unicode.toString();
}
protected String decode(String input) {
int n = initial_n;
int i = 0;
int bias = initial_bias;
StringBuilder output = new StringBuilder(input.length());
int lastdelim = input.lastIndexOf(delimiter);
if (lastdelim != -1) {
output.append(input.subSequence(0, lastdelim));
input = input.substring(lastdelim + 1);
}
while (input.length() > 0) {
int oldi = i;
int w = 1;
for (int k = base;; k += base) {
if (input.length() == 0) break;
char c = input.charAt(0);
input = input.substring(1);
int digit = digit(c);
i = i + digit * w; // FIXME fail on overflow
int t;
if (k <= bias + tmin) {
t = tmin;
} else if (k >= bias + tmax) {
t = tmax;
} else {
t = k - bias;
}
if (digit < t) break;
w = w * (base - t); // FIXME fail on overflow
}
bias = adapt(i - oldi, output.length() + 1, (oldi == 0));
n = n + i / (output.length() + 1); // FIXME fail on overflow
i = i % (output.length() + 1);
// {if n is a basic code point then fail}
output.insert(i, (char) n);
i++;
}
return output.toString();
}
} | Java |
/*
* $HeadURL$
* $Revision$
* $Date$
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.ogt.http.annotation.Immutable;
/**
* Uses the java.net.IDN class through reflection.
*
* @since 4.0
*/
@Immutable
public class JdkIdn implements Idn {
private final Method toUnicode;
/**
*
* @throws ClassNotFoundException if java.net.IDN is not available
*/
public JdkIdn() throws ClassNotFoundException {
Class<?> clazz = Class.forName("java.net.IDN");
try {
toUnicode = clazz.getMethod("toUnicode", String.class);
} catch (SecurityException e) {
// doesn't happen
throw new IllegalStateException(e.getMessage(), e);
} catch (NoSuchMethodException e) {
// doesn't happen
throw new IllegalStateException(e.getMessage(), e);
}
}
public String toUnicode(String punycode) {
try {
return (String) toUnicode.invoke(null, punycode);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e.getMessage(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
throw new RuntimeException(t.getMessage(), t);
}
}
} | Java |
/*
* $HeadURL$
* $Revision$
* $Date$
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.utils;
/**
* Abstraction of international domain name (IDN) conversion.
*
* @since 4.0
*/
public interface Idn {
/**
* Converts a name from its punycode representation to Unicode.
* The name may be a single hostname or a dot-separated qualified domain name.
* @param punycode the Punycode representation
* @return the Unicode domain name
*/
String toUnicode(String punycode);
} | Java |
/*
* $HeadURL$
* $Revision$
* $Date$
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.client.utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.ogt.http.annotation.Immutable;
/**
* A collection of utilities to workaround limitations of Java clone framework.
*
* @since 4.0
*/
@Immutable
public class CloneUtils {
public static Object clone(final Object obj) throws CloneNotSupportedException {
if (obj == null) {
return null;
}
if (obj instanceof Cloneable) {
Class<?> clazz = obj.getClass ();
Method m;
try {
m = clazz.getMethod("clone", (Class[]) null);
} catch (NoSuchMethodException ex) {
throw new NoSuchMethodError(ex.getMessage());
}
try {
return m.invoke(obj, (Object []) null);
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
if (cause instanceof CloneNotSupportedException) {
throw ((CloneNotSupportedException) cause);
} else {
throw new Error("Unexpected exception", cause);
}
} catch (IllegalAccessException ex) {
throw new IllegalAccessError(ex.getMessage());
}
} else {
throw new CloneNotSupportedException();
}
}
/**
* This class should not be instantiated.
*/
private CloneUtils() {
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.client.utils;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Stack;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.annotation.Immutable;
/**
* A collection of utilities for {@link URI URIs}, to workaround
* bugs within the class or for ease-of-use features.
*
* @since 4.0
*/
@Immutable
public class URIUtils {
/**
* Constructs a {@link URI} using all the parameters. This should be
* used instead of
* {@link URI#URI(String, String, String, int, String, String, String)}
* or any of the other URI multi-argument URI constructors.
*
* @param scheme
* Scheme name
* @param host
* Host name
* @param port
* Port number
* @param path
* Path
* @param query
* Query
* @param fragment
* Fragment
*
* @throws URISyntaxException
* If both a scheme and a path are given but the path is
* relative, if the URI string constructed from the given
* components violates RFC 2396, or if the authority
* component of the string is present but cannot be parsed
* as a server-based authority
*/
public static URI createURI(
final String scheme,
final String host,
int port,
final String path,
final String query,
final String fragment) throws URISyntaxException {
StringBuilder buffer = new StringBuilder();
if (host != null) {
if (scheme != null) {
buffer.append(scheme);
buffer.append("://");
}
buffer.append(host);
if (port > 0) {
buffer.append(':');
buffer.append(port);
}
}
if (path == null || !path.startsWith("/")) {
buffer.append('/');
}
if (path != null) {
buffer.append(path);
}
if (query != null) {
buffer.append('?');
buffer.append(query);
}
if (fragment != null) {
buffer.append('#');
buffer.append(fragment);
}
return new URI(buffer.toString());
}
/**
* A convenience method for creating a new {@link URI} whose scheme, host
* and port are taken from the target host, but whose path, query and
* fragment are taken from the existing URI. The fragment is only used if
* dropFragment is false.
*
* @param uri
* Contains the path, query and fragment to use.
* @param target
* Contains the scheme, host and port to use.
* @param dropFragment
* True if the fragment should not be copied.
*
* @throws URISyntaxException
* If the resulting URI is invalid.
*/
public static URI rewriteURI(
final URI uri,
final HttpHost target,
boolean dropFragment) throws URISyntaxException {
if (uri == null) {
throw new IllegalArgumentException("URI may nor be null");
}
if (target != null) {
return URIUtils.createURI(
target.getSchemeName(),
target.getHostName(),
target.getPort(),
normalizePath(uri.getRawPath()),
uri.getRawQuery(),
dropFragment ? null : uri.getRawFragment());
} else {
return URIUtils.createURI(
null,
null,
-1,
normalizePath(uri.getRawPath()),
uri.getRawQuery(),
dropFragment ? null : uri.getRawFragment());
}
}
private static String normalizePath(String path) {
if (path == null) {
return null;
}
int n = 0;
for (; n < path.length(); n++) {
if (path.charAt(n) != '/') {
break;
}
}
if (n > 1) {
path = path.substring(n - 1);
}
return path;
}
/**
* A convenience method for
* {@link URIUtils#rewriteURI(URI, HttpHost, boolean)} that always keeps the
* fragment.
*/
public static URI rewriteURI(
final URI uri,
final HttpHost target) throws URISyntaxException {
return rewriteURI(uri, target, false);
}
/**
* Resolves a URI reference against a base URI. Work-around for bug in
* java.net.URI (<http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535>)
*
* @param baseURI the base URI
* @param reference the URI reference
* @return the resulting URI
*/
public static URI resolve(final URI baseURI, final String reference) {
return URIUtils.resolve(baseURI, URI.create(reference));
}
/**
* Resolves a URI reference against a base URI. Work-around for bugs in
* java.net.URI (e.g. <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535>)
*
* @param baseURI the base URI
* @param reference the URI reference
* @return the resulting URI
*/
public static URI resolve(final URI baseURI, URI reference){
if (baseURI == null) {
throw new IllegalArgumentException("Base URI may nor be null");
}
if (reference == null) {
throw new IllegalArgumentException("Reference URI may nor be null");
}
String s = reference.toString();
if (s.startsWith("?")) {
return resolveReferenceStartingWithQueryString(baseURI, reference);
}
boolean emptyReference = s.length() == 0;
if (emptyReference) {
reference = URI.create("#");
}
URI resolved = baseURI.resolve(reference);
if (emptyReference) {
String resolvedString = resolved.toString();
resolved = URI.create(resolvedString.substring(0,
resolvedString.indexOf('#')));
}
return removeDotSegments(resolved);
}
/**
* Resolves a reference starting with a query string.
*
* @param baseURI the base URI
* @param reference the URI reference starting with a query string
* @return the resulting URI
*/
private static URI resolveReferenceStartingWithQueryString(
final URI baseURI, final URI reference) {
String baseUri = baseURI.toString();
baseUri = baseUri.indexOf('?') > -1 ?
baseUri.substring(0, baseUri.indexOf('?')) : baseUri;
return URI.create(baseUri + reference.toString());
}
/**
* Removes dot segments according to RFC 3986, section 5.2.4
*
* @param uri the original URI
* @return the URI without dot segments
*/
private static URI removeDotSegments(URI uri) {
String path = uri.getPath();
if ((path == null) || (path.indexOf("/.") == -1)) {
// No dot segments to remove
return uri;
}
String[] inputSegments = path.split("/");
Stack<String> outputSegments = new Stack<String>();
for (int i = 0; i < inputSegments.length; i++) {
if ((inputSegments[i].length() == 0)
|| (".".equals(inputSegments[i]))) {
// Do nothing
} else if ("..".equals(inputSegments[i])) {
if (!outputSegments.isEmpty()) {
outputSegments.pop();
}
} else {
outputSegments.push(inputSegments[i]);
}
}
StringBuilder outputBuffer = new StringBuilder();
for (String outputSegment : outputSegments) {
outputBuffer.append('/').append(outputSegment);
}
try {
return new URI(uri.getScheme(), uri.getAuthority(),
outputBuffer.toString(), uri.getQuery(), uri.getFragment());
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Extracts target host from the given {@link URI}.
*
* @param uri
* @return the target host if the URI is absolute or <code>null</null> if the URI is
* relative or does not contain a valid host name.
*
* @since 4.1
*/
public static HttpHost extractHost(final URI uri) {
if (uri == null) {
return null;
}
HttpHost target = null;
if (uri.isAbsolute()) {
int port = uri.getPort(); // may be overridden later
String host = uri.getHost();
if (host == null) { // normal parse failed; let's do it ourselves
// authority does not seem to care about the valid character-set for host names
host = uri.getAuthority();
if (host != null) {
// Strip off any leading user credentials
int at = host.indexOf('@');
if (at >= 0) {
if (host.length() > at+1 ) {
host = host.substring(at+1);
} else {
host = null; // @ on its own
}
}
// Extract the port suffix, if present
if (host != null) {
int colon = host.indexOf(':');
if (colon >= 0) {
if (colon+1 < host.length()) {
port = Integer.parseInt(host.substring(colon+1));
}
host = host.substring(0,colon);
}
}
}
}
String scheme = uri.getScheme();
if (host != null) {
target = new HttpHost(host, port, scheme);
}
}
return target;
}
/**
* This class should not be instantiated.
*/
private URIUtils() {
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.