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.impl.conn.tsccm;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.annotation.ThreadSafe;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.ClientConnectionOperator;
import org.apache.ogt.http.conn.ClientConnectionRequest;
import org.apache.ogt.http.conn.ConnectionPoolTimeoutException;
import org.apache.ogt.http.conn.ManagedClientConnection;
import org.apache.ogt.http.conn.OperatedClientConnection;
import org.apache.ogt.http.conn.params.ConnPerRouteBean;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.ogt.http.impl.conn.SchemeRegistryFactory;
import org.apache.ogt.http.params.HttpParams;
/**
* Manages a pool of {@link OperatedClientConnection client connections} and
* is able to service connection requests from multiple execution threads.
* Connections are pooled on a per route basis. A request for a route which
* already the manager has persistent connections for available in the pool
* will be services by leasing a connection from the pool rather than
* creating a brand new connection.
* <p>
* ThreadSafeClientConnManager maintains a maximum limit of connection on
* a per route basis and in total. Per default this implementation will
* create no more than than 2 concurrent connections per given route
* and no more 20 connections in total. For many real-world applications
* these limits may prove too constraining, especially if they use HTTP
* as a transport protocol for their services. Connection limits, however,
* can be adjusted using HTTP parameters.
*
* @since 4.0
*/
@ThreadSafe
public class ThreadSafeClientConnManager implements ClientConnectionManager {
private final Log log;
/** The schemes supported by this connection manager. */
protected final SchemeRegistry schemeRegistry; // @ThreadSafe
@Deprecated
protected final AbstractConnPool connectionPool;
/** The pool of connections being managed. */
protected final ConnPoolByRoute pool;
/** The operator for opening and updating connections. */
protected final ClientConnectionOperator connOperator; // DefaultClientConnectionOperator is @ThreadSafe
protected final ConnPerRouteBean connPerRoute;
/**
* Creates a new thread safe connection manager.
*
* @param schreg the scheme registry.
*/
public ThreadSafeClientConnManager(final SchemeRegistry schreg) {
this(schreg, -1, TimeUnit.MILLISECONDS);
}
/**
* @since 4.1
*/
public ThreadSafeClientConnManager() {
this(SchemeRegistryFactory.createDefault());
}
/**
* Creates a new thread safe connection manager.
*
* @param schreg the scheme registry.
* @param connTTL max connection lifetime, <=0 implies "infinity"
* @param connTTLTimeUnit TimeUnit of connTTL
*
* @since 4.1
*/
public ThreadSafeClientConnManager(final SchemeRegistry schreg,
long connTTL, TimeUnit connTTLTimeUnit) {
super();
if (schreg == null) {
throw new IllegalArgumentException("Scheme registry may not be null");
}
this.log = LogFactory.getLog(getClass());
this.schemeRegistry = schreg;
this.connPerRoute = new ConnPerRouteBean();
this.connOperator = createConnectionOperator(schreg);
this.pool = createConnectionPool(connTTL, connTTLTimeUnit) ;
this.connectionPool = this.pool;
}
/**
* Creates a new thread safe connection manager.
*
* @param params the parameters for this manager.
* @param schreg the scheme registry.
*
* @deprecated use {@link ThreadSafeClientConnManager#ThreadSafeClientConnManager(SchemeRegistry)}
*/
@Deprecated
public ThreadSafeClientConnManager(HttpParams params,
SchemeRegistry schreg) {
if (schreg == null) {
throw new IllegalArgumentException("Scheme registry may not be null");
}
this.log = LogFactory.getLog(getClass());
this.schemeRegistry = schreg;
this.connPerRoute = new ConnPerRouteBean();
this.connOperator = createConnectionOperator(schreg);
this.pool = (ConnPoolByRoute) createConnectionPool(params) ;
this.connectionPool = this.pool;
}
@Override
protected void finalize() throws Throwable {
try {
shutdown();
} finally {
super.finalize();
}
}
/**
* Hook for creating the connection pool.
*
* @return the connection pool to use
*
* @deprecated use #createConnectionPool(long, TimeUnit))
*/
@Deprecated
protected AbstractConnPool createConnectionPool(final HttpParams params) {
return new ConnPoolByRoute(connOperator, params);
}
/**
* Hook for creating the connection pool.
*
* @return the connection pool to use
*
* @since 4.1
*/
protected ConnPoolByRoute createConnectionPool(long connTTL, TimeUnit connTTLTimeUnit) {
return new ConnPoolByRoute(connOperator, connPerRoute, 20, connTTL, connTTLTimeUnit);
}
/**
* Hook for creating the connection operator.
* It is called by the constructor.
* Derived classes can override this method to change the
* instantiation of the operator.
* The default implementation here instantiates
* {@link DefaultClientConnectionOperator DefaultClientConnectionOperator}.
*
* @param schreg the scheme registry.
*
* @return the connection operator to use
*/
protected ClientConnectionOperator
createConnectionOperator(SchemeRegistry schreg) {
return new DefaultClientConnectionOperator(schreg);// @ThreadSafe
}
public SchemeRegistry getSchemeRegistry() {
return this.schemeRegistry;
}
public ClientConnectionRequest requestConnection(
final HttpRoute route,
final Object state) {
final PoolEntryRequest poolRequest = pool.requestPoolEntry(
route, state);
return new ClientConnectionRequest() {
public void abortRequest() {
poolRequest.abortRequest();
}
public ManagedClientConnection getConnection(
long timeout, TimeUnit tunit) throws InterruptedException,
ConnectionPoolTimeoutException {
if (route == null) {
throw new IllegalArgumentException("Route may not be null.");
}
if (log.isDebugEnabled()) {
log.debug("Get connection: " + route + ", timeout = " + timeout);
}
BasicPoolEntry entry = poolRequest.getPoolEntry(timeout, tunit);
return new BasicPooledConnAdapter(ThreadSafeClientConnManager.this, entry);
}
};
}
public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) {
if (!(conn instanceof BasicPooledConnAdapter)) {
throw new IllegalArgumentException
("Connection class mismatch, " +
"connection not obtained from this manager.");
}
BasicPooledConnAdapter hca = (BasicPooledConnAdapter) conn;
if ((hca.getPoolEntry() != null) && (hca.getManager() != this)) {
throw new IllegalArgumentException
("Connection not obtained from this manager.");
}
synchronized (hca) {
BasicPoolEntry entry = (BasicPoolEntry) hca.getPoolEntry();
if (entry == null) {
return;
}
try {
// make sure that the response has been read completely
if (hca.isOpen() && !hca.isMarkedReusable()) {
// In MTHCM, there would be a call to
// SimpleHttpConnectionManager.finishLastResponse(conn);
// Consuming the response is handled outside in 4.0.
// make sure this connection will not be re-used
// Shut down rather than close, we might have gotten here
// because of a shutdown trigger.
// Shutdown of the adapter also clears the tracked route.
hca.shutdown();
}
} catch (IOException iox) {
if (log.isDebugEnabled())
log.debug("Exception shutting down released connection.",
iox);
} finally {
boolean reusable = hca.isMarkedReusable();
if (log.isDebugEnabled()) {
if (reusable) {
log.debug("Released connection is reusable.");
} else {
log.debug("Released connection is not reusable.");
}
}
hca.detach();
pool.freeEntry(entry, reusable, validDuration, timeUnit);
}
}
}
public void shutdown() {
log.debug("Shutting down");
pool.shutdown();
}
/**
* Gets the total number of pooled connections for the given route.
* This is the total number of connections that have been created and
* are still in use by this connection manager for the route.
* This value will not exceed the maximum number of connections per host.
*
* @param route the route in question
*
* @return the total number of pooled connections for that route
*/
public int getConnectionsInPool(final HttpRoute route) {
return pool.getConnectionsInPool(route);
}
/**
* Gets the total number of pooled connections. This is the total number of
* connections that have been created and are still in use by this connection
* manager. This value will not exceed the maximum number of connections
* in total.
*
* @return the total number of pooled connections
*/
public int getConnectionsInPool() {
return pool.getConnectionsInPool();
}
public void closeIdleConnections(long idleTimeout, TimeUnit tunit) {
if (log.isDebugEnabled()) {
log.debug("Closing connections idle longer than " + idleTimeout + " " + tunit);
}
pool.closeIdleConnections(idleTimeout, tunit);
}
public void closeExpiredConnections() {
log.debug("Closing expired connections");
pool.closeExpiredConnections();
}
/**
* since 4.1
*/
public int getMaxTotal() {
return pool.getMaxTotalConnections();
}
/**
* since 4.1
*/
public void setMaxTotal(int max) {
pool.setMaxTotalConnections(max);
}
/**
* @since 4.1
*/
public int getDefaultMaxPerRoute() {
return connPerRoute.getDefaultMaxPerRoute();
}
/**
* @since 4.1
*/
public void setDefaultMaxPerRoute(int max) {
connPerRoute.setDefaultMaxPerRoute(max);
}
/**
* @since 4.1
*/
public int getMaxForRoute(final HttpRoute route) {
return connPerRoute.getMaxForRoute(route);
}
/**
* @since 4.1
*/
public void setMaxForRoute(final HttpRoute route, int max) {
connPerRoute.setMaxForRoute(route, max);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.conn.tsccm;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.TimeUnit;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.conn.ClientConnectionOperator;
import org.apache.ogt.http.conn.OperatedClientConnection;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.impl.conn.AbstractPoolEntry;
/**
* Basic implementation of a connection pool entry.
*
* @since 4.0
*/
@NotThreadSafe
public class BasicPoolEntry extends AbstractPoolEntry {
private final long created;
private long updated;
private long validUntil;
private long expiry;
/**
* @deprecated do not use
*/
@Deprecated
public BasicPoolEntry(ClientConnectionOperator op,
HttpRoute route,
ReferenceQueue<Object> queue) {
super(op, route);
if (route == null) {
throw new IllegalArgumentException("HTTP route may not be null");
}
this.created = System.currentTimeMillis();
this.validUntil = Long.MAX_VALUE;
this.expiry = this.validUntil;
}
/**
* Creates a new pool entry.
*
* @param op the connection operator
* @param route the planned route for the connection
*/
public BasicPoolEntry(ClientConnectionOperator op,
HttpRoute route) {
this(op, route, -1, TimeUnit.MILLISECONDS);
}
/**
* Creates a new pool entry with a specified maximum lifetime.
*
* @param op the connection operator
* @param route the planned route for the connection
* @param connTTL maximum lifetime of this entry, <=0 implies "infinity"
* @param timeunit TimeUnit of connTTL
*
* @since 4.1
*/
public BasicPoolEntry(ClientConnectionOperator op,
HttpRoute route, long connTTL, TimeUnit timeunit) {
super(op, route);
if (route == null) {
throw new IllegalArgumentException("HTTP route may not be null");
}
this.created = System.currentTimeMillis();
if (connTTL > 0) {
this.validUntil = this.created + timeunit.toMillis(connTTL);
} else {
this.validUntil = Long.MAX_VALUE;
}
this.expiry = this.validUntil;
}
protected final OperatedClientConnection getConnection() {
return super.connection;
}
protected final HttpRoute getPlannedRoute() {
return super.route;
}
@Deprecated
protected final BasicPoolEntryRef getWeakRef() {
return null;
}
@Override
protected void shutdownEntry() {
super.shutdownEntry();
}
/**
* @since 4.1
*/
public long getCreated() {
return this.created;
}
/**
* @since 4.1
*/
public long getUpdated() {
return this.updated;
}
/**
* @since 4.1
*/
public long getExpiry() {
return this.expiry;
}
public long getValidUntil() {
return this.validUntil;
}
/**
* @since 4.1
*/
public void updateExpiry(long time, TimeUnit timeunit) {
this.updated = System.currentTimeMillis();
long newExpiry;
if (time > 0) {
newExpiry = this.updated + timeunit.toMillis(time);
} else {
newExpiry = Long.MAX_VALUE;
}
this.expiry = Math.min(validUntil, newExpiry);
}
/**
* @since 4.1
*/
public boolean isExpired(long now) {
return now >= this.expiry;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.conn.tsccm;
import java.io.IOException;
import java.util.ListIterator;
import java.util.Queue;
import java.util.LinkedList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.conn.OperatedClientConnection;
import org.apache.ogt.http.conn.params.ConnPerRoute;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.util.LangUtils;
/**
* A connection sub-pool for a specific route, used by {@link ConnPoolByRoute}.
* The methods in this class are unsynchronized. It is expected that the
* containing pool takes care of synchronization.
*
* @since 4.0
*/
@NotThreadSafe // e.g. numEntries, freeEntries,
public class RouteSpecificPool {
private final Log log = LogFactory.getLog(getClass());
/** The route this pool is for. */
protected final HttpRoute route; //Immutable
@Deprecated
protected final int maxEntries;
/** Connections per route */
protected final ConnPerRoute connPerRoute;
/**
* The list of free entries.
* This list is managed LIFO, to increase idle times and
* allow for closing connections that are not really needed.
*/
protected final LinkedList<BasicPoolEntry> freeEntries;
/** The list of threads waiting for this pool. */
protected final Queue<WaitingThread> waitingThreads;
/** The number of created entries. */
protected int numEntries;
/**
* @deprecated use {@link RouteSpecificPool#RouteSpecificPool(HttpRoute, ConnPerRoute)}
*/
@Deprecated
public RouteSpecificPool(HttpRoute route, int maxEntries) {
this.route = route;
this.maxEntries = maxEntries;
this.connPerRoute = new ConnPerRoute() {
public int getMaxForRoute(HttpRoute route) {
return RouteSpecificPool.this.maxEntries;
}
};
this.freeEntries = new LinkedList<BasicPoolEntry>();
this.waitingThreads = new LinkedList<WaitingThread>();
this.numEntries = 0;
}
/**
* Creates a new route-specific pool.
*
* @param route the route for which to pool
* @param connPerRoute the connections per route configuration
*/
public RouteSpecificPool(HttpRoute route, ConnPerRoute connPerRoute) {
this.route = route;
this.connPerRoute = connPerRoute;
this.maxEntries = connPerRoute.getMaxForRoute(route);
this.freeEntries = new LinkedList<BasicPoolEntry>();
this.waitingThreads = new LinkedList<WaitingThread>();
this.numEntries = 0;
}
/**
* Obtains the route for which this pool is specific.
*
* @return the route
*/
public final HttpRoute getRoute() {
return route;
}
/**
* Obtains the maximum number of entries allowed for this pool.
*
* @return the max entry number
*/
public final int getMaxEntries() {
return maxEntries;
}
/**
* Indicates whether this pool is unused.
* A pool is unused if there is neither an entry nor a waiting thread.
* All entries count, not only the free but also the allocated ones.
*
* @return <code>true</code> if this pool is unused,
* <code>false</code> otherwise
*/
public boolean isUnused() {
return (numEntries < 1) && waitingThreads.isEmpty();
}
/**
* Return remaining capacity of this pool
*
* @return capacity
*/
public int getCapacity() {
return connPerRoute.getMaxForRoute(route) - numEntries;
}
/**
* Obtains the number of entries.
* This includes not only the free entries, but also those that
* have been created and are currently issued to an application.
*
* @return the number of entries for the route of this pool
*/
public final int getEntryCount() {
return numEntries;
}
/**
* Obtains a free entry from this pool, if one is available.
*
* @return an available pool entry, or <code>null</code> if there is none
*/
public BasicPoolEntry allocEntry(final Object state) {
if (!freeEntries.isEmpty()) {
ListIterator<BasicPoolEntry> it = freeEntries.listIterator(freeEntries.size());
while (it.hasPrevious()) {
BasicPoolEntry entry = it.previous();
if (entry.getState() == null || LangUtils.equals(state, entry.getState())) {
it.remove();
return entry;
}
}
}
if (getCapacity() == 0 && !freeEntries.isEmpty()) {
BasicPoolEntry entry = freeEntries.remove();
entry.shutdownEntry();
OperatedClientConnection conn = entry.getConnection();
try {
conn.close();
} catch (IOException ex) {
log.debug("I/O error closing connection", ex);
}
return entry;
}
return null;
}
/**
* Returns an allocated entry to this pool.
*
* @param entry the entry obtained from {@link #allocEntry allocEntry}
* or presented to {@link #createdEntry createdEntry}
*/
public void freeEntry(BasicPoolEntry entry) {
if (numEntries < 1) {
throw new IllegalStateException
("No entry created for this pool. " + route);
}
if (numEntries <= freeEntries.size()) {
throw new IllegalStateException
("No entry allocated from this pool. " + route);
}
freeEntries.add(entry);
}
/**
* Indicates creation of an entry for this pool.
* The entry will <i>not</i> be added to the list of free entries,
* it is only recognized as belonging to this pool now. It can then
* be passed to {@link #freeEntry freeEntry}.
*
* @param entry the entry that was created for this pool
*/
public void createdEntry(BasicPoolEntry entry) {
if (!route.equals(entry.getPlannedRoute())) {
throw new IllegalArgumentException
("Entry not planned for this pool." +
"\npool: " + route +
"\nplan: " + entry.getPlannedRoute());
}
numEntries++;
}
/**
* Deletes an entry from this pool.
* Only entries that are currently free in this pool can be deleted.
* Allocated entries can not be deleted.
*
* @param entry the entry to delete from this pool
*
* @return <code>true</code> if the entry was found and deleted, or
* <code>false</code> if the entry was not found
*/
public boolean deleteEntry(BasicPoolEntry entry) {
final boolean found = freeEntries.remove(entry);
if (found)
numEntries--;
return found;
}
/**
* Forgets about an entry from this pool.
* This method is used to indicate that an entry
* {@link #allocEntry allocated}
* from this pool has been lost and will not be returned.
*/
public void dropEntry() {
if (numEntries < 1) {
throw new IllegalStateException
("There is no entry that could be dropped.");
}
numEntries--;
}
/**
* Adds a waiting thread.
* This pool makes no attempt to match waiting threads with pool entries.
* It is the caller's responsibility to check that there is no entry
* before adding a waiting thread.
*
* @param wt the waiting thread
*/
public void queueThread(WaitingThread wt) {
if (wt == null) {
throw new IllegalArgumentException
("Waiting thread must not be null.");
}
this.waitingThreads.add(wt);
}
/**
* Checks whether there is a waiting thread in this pool.
*
* @return <code>true</code> if there is a waiting thread,
* <code>false</code> otherwise
*/
public boolean hasThread() {
return !this.waitingThreads.isEmpty();
}
/**
* Returns the next thread in the queue.
*
* @return a waiting thread, or <code>null</code> if there is none
*/
public WaitingThread nextThread() {
return this.waitingThreads.peek();
}
/**
* Removes a waiting thread, if it is queued.
*
* @param wt the waiting thread
*/
public void removeThread(WaitingThread wt) {
if (wt == null)
return;
this.waitingThreads.remove(wt);
}
} // class RouteSpecificPool
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.conn;
import java.io.IOException;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.io.EofSensor;
import org.apache.ogt.http.io.HttpTransportMetrics;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Logs all data read to the wire LOG.
*
*
* @since 4.0
*/
@Immutable
public class LoggingSessionInputBuffer implements SessionInputBuffer, EofSensor {
/** Original session input buffer. */
private final SessionInputBuffer in;
private final EofSensor eofSensor;
/** The wire log to use for writing. */
private final Wire wire;
private final String charset;
/**
* Create an instance that wraps the specified session input buffer.
* @param in The session input buffer.
* @param wire The wire log to use.
* @param charset protocol charset, <code>ASCII</code> if <code>null</code>
*/
public LoggingSessionInputBuffer(
final SessionInputBuffer in, final Wire wire, final String charset) {
super();
this.in = in;
this.eofSensor = in instanceof EofSensor ? (EofSensor) in : null;
this.wire = wire;
this.charset = charset != null ? charset : HTTP.ASCII;
}
public LoggingSessionInputBuffer(final SessionInputBuffer in, final Wire wire) {
this(in, wire, null);
}
public boolean isDataAvailable(int timeout) throws IOException {
return this.in.isDataAvailable(timeout);
}
public int read(byte[] b, int off, int len) throws IOException {
int l = this.in.read(b, off, len);
if (this.wire.enabled() && l > 0) {
this.wire.input(b, off, l);
}
return l;
}
public int read() throws IOException {
int l = this.in.read();
if (this.wire.enabled() && l != -1) {
this.wire.input(l);
}
return l;
}
public int read(byte[] b) throws IOException {
int l = this.in.read(b);
if (this.wire.enabled() && l > 0) {
this.wire.input(b, 0, l);
}
return l;
}
public String readLine() throws IOException {
String s = this.in.readLine();
if (this.wire.enabled() && s != null) {
String tmp = s + "\r\n";
this.wire.input(tmp.getBytes(this.charset));
}
return s;
}
public int readLine(final CharArrayBuffer buffer) throws IOException {
int l = this.in.readLine(buffer);
if (this.wire.enabled() && l >= 0) {
int pos = buffer.length() - l;
String s = new String(buffer.buffer(), pos, l);
String tmp = s + "\r\n";
this.wire.input(tmp.getBytes(this.charset));
}
return l;
}
public HttpTransportMetrics getMetrics() {
return this.in.getMetrics();
}
public boolean isEof() {
if (this.eofSensor != null) {
return this.eofSensor.isEof();
} else {
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.impl.conn;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.annotation.ThreadSafe;
import org.apache.ogt.http.conn.ClientConnectionOperator;
import org.apache.ogt.http.conn.ConnectTimeoutException;
import org.apache.ogt.http.conn.HttpHostConnectException;
import org.apache.ogt.http.conn.OperatedClientConnection;
import org.apache.ogt.http.conn.scheme.LayeredSchemeSocketFactory;
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.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Default implementation of a {@link ClientConnectionOperator}. It uses a {@link SchemeRegistry}
* to look up {@link SchemeSocketFactory} objects.
* <p>
* This connection operator is multihome network aware and will attempt to retry failed connects
* against all known IP addresses sequentially until the connect is successful or all known
* addresses fail to respond. Please note the same
* {@link org.apache.ogt.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT} value will be used
* for each connection attempt, so in the worst case the total elapsed time before timeout
* can be <code>CONNECTION_TIMEOUT * n</code> where <code>n</code> is the number of IP addresses
* of the given host. One can disable multihome support by overriding
* the {@link #resolveHostname(String)} method and returning only one IP address for the given
* host name.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_LINGER}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_REUSEADDR}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
@ThreadSafe
public class DefaultClientConnectionOperator implements ClientConnectionOperator {
private final Log log = LogFactory.getLog(getClass());
/** The scheme registry for looking up socket factories. */
protected final SchemeRegistry schemeRegistry; // @ThreadSafe
/**
* Creates a new client connection operator for the given scheme registry.
*
* @param schemes the scheme registry
*/
public DefaultClientConnectionOperator(final SchemeRegistry schemes) {
if (schemes == null) {
throw new IllegalArgumentException("Scheme registry amy not be null");
}
this.schemeRegistry = schemes;
}
public OperatedClientConnection createConnection() {
return new DefaultClientConnection();
}
public void openConnection(
final OperatedClientConnection conn,
final HttpHost target,
final InetAddress local,
final HttpContext context,
final HttpParams params) throws IOException {
if (conn == null) {
throw new IllegalArgumentException("Connection may not be null");
}
if (target == null) {
throw new IllegalArgumentException("Target host may not be null");
}
if (params == null) {
throw new IllegalArgumentException("Parameters may not be null");
}
if (conn.isOpen()) {
throw new IllegalStateException("Connection must not be open");
}
Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
SchemeSocketFactory sf = schm.getSchemeSocketFactory();
InetAddress[] addresses = resolveHostname(target.getHostName());
int port = schm.resolvePort(target.getPort());
for (int i = 0; i < addresses.length; i++) {
InetAddress address = addresses[i];
boolean last = i == addresses.length - 1;
Socket sock = sf.createSocket(params);
conn.opening(sock, target);
InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
InetSocketAddress localAddress = null;
if (local != null) {
localAddress = new InetSocketAddress(local, 0);
}
if (this.log.isDebugEnabled()) {
this.log.debug("Connecting to " + remoteAddress);
}
try {
Socket connsock = sf.connectSocket(sock, remoteAddress, localAddress, params);
if (sock != connsock) {
sock = connsock;
conn.opening(sock, target);
}
prepareSocket(sock, context, params);
conn.openCompleted(sf.isSecure(sock), params);
return;
} catch (ConnectException ex) {
if (last) {
throw new HttpHostConnectException(target, ex);
}
} catch (ConnectTimeoutException ex) {
if (last) {
throw ex;
}
}
if (this.log.isDebugEnabled()) {
this.log.debug("Connect to " + remoteAddress + " timed out. " +
"Connection will be retried using another IP address");
}
}
}
public void updateSecureConnection(
final OperatedClientConnection conn,
final HttpHost target,
final HttpContext context,
final HttpParams params) throws IOException {
if (conn == null) {
throw new IllegalArgumentException("Connection may not be null");
}
if (target == null) {
throw new IllegalArgumentException("Target host may not be null");
}
if (params == null) {
throw new IllegalArgumentException("Parameters may not be null");
}
if (!conn.isOpen()) {
throw new IllegalStateException("Connection must be open");
}
final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
if (!(schm.getSchemeSocketFactory() instanceof LayeredSchemeSocketFactory)) {
throw new IllegalArgumentException
("Target scheme (" + schm.getName() +
") must have layered socket factory.");
}
LayeredSchemeSocketFactory lsf = (LayeredSchemeSocketFactory) schm.getSchemeSocketFactory();
Socket sock;
try {
sock = lsf.createLayeredSocket(
conn.getSocket(), target.getHostName(), target.getPort(), true);
} catch (ConnectException ex) {
throw new HttpHostConnectException(target, ex);
}
prepareSocket(sock, context, params);
conn.update(sock, target, lsf.isSecure(sock), params);
}
/**
* Performs standard initializations on a newly created socket.
*
* @param sock the socket to prepare
* @param context the context for the connection
* @param params the parameters from which to prepare the socket
*
* @throws IOException in case of an IO problem
*/
protected void prepareSocket(
final Socket sock,
final HttpContext context,
final HttpParams params) throws IOException {
sock.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
sock.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
int linger = HttpConnectionParams.getLinger(params);
if (linger >= 0) {
sock.setSoLinger(linger > 0, linger);
}
}
/**
* Resolves the given host name to an array of corresponding IP addresses, based on the
* configured name service on the system.
*
* @param host host name to resolve
* @return array of IP addresses
* @exception UnknownHostException if no IP address for the host could be determined.
*
* @since 4.1
*/
protected InetAddress[] resolveHostname(final String host) throws UnknownHostException {
return InetAddress.getAllByName(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.impl.conn;
import org.apache.ogt.http.annotation.Immutable;
/**
* Signals that the connection has been shut down or released back to the
* the connection pool
*
* @since 4.1
*/
@Immutable
public class ConnectionShutdownException extends IllegalStateException {
private static final long serialVersionUID = 5868657401162844497L;
/**
* Creates a new ConnectionShutdownException with a <tt>null</tt> detail message.
*/
public ConnectionShutdownException() {
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.impl.conn;
import java.io.IOException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.conn.ClientConnectionOperator;
import org.apache.ogt.http.conn.OperatedClientConnection;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.conn.routing.RouteTracker;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.HttpContext;
/**
* A pool entry for use by connection manager implementations.
* Pool entries work in conjunction with an
* {@link AbstractClientConnAdapter adapter}.
* The adapter is handed out to applications that obtain a connection.
* The pool entry stores the underlying connection and tracks the
* {@link HttpRoute route} established.
* The adapter delegates methods for establishing the route to
* its pool entry.
* <p>
* If the managed connections is released or revoked, the adapter
* gets disconnected, but the pool entry still contains the
* underlying connection and the established route.
*
* @since 4.0
*/
@NotThreadSafe
public abstract class AbstractPoolEntry {
/** The connection operator. */
protected final ClientConnectionOperator connOperator;
/** The underlying connection being pooled or used. */
protected final OperatedClientConnection connection;
/** The route for which this entry gets allocated. */
//@@@ currently accessed from connection manager(s) as attribute
//@@@ avoid that, derived classes should decide whether update is allowed
//@@@ SCCM: yes, TSCCM: no
protected volatile HttpRoute route;
/** Connection state object */
protected volatile Object state;
/** The tracked route, or <code>null</code> before tracking starts. */
protected volatile RouteTracker tracker;
/**
* Creates a new pool entry.
*
* @param connOperator the Connection Operator for this entry
* @param route the planned route for the connection,
* or <code>null</code>
*/
protected AbstractPoolEntry(ClientConnectionOperator connOperator,
HttpRoute route) {
super();
if (connOperator == null) {
throw new IllegalArgumentException("Connection operator may not be null");
}
this.connOperator = connOperator;
this.connection = connOperator.createConnection();
this.route = route;
this.tracker = null;
}
/**
* Returns the state object associated with this pool entry.
*
* @return The state object
*/
public Object getState() {
return state;
}
/**
* Assigns a state object to this pool entry.
*
* @param state The state object
*/
public void setState(final Object state) {
this.state = state;
}
/**
* Opens the underlying connection.
*
* @param route the route along which to open the connection
* @param context the context for opening the connection
* @param params the parameters for opening the connection
*
* @throws IOException in case of a problem
*/
public void open(HttpRoute route,
HttpContext context, HttpParams params)
throws IOException {
if (route == null) {
throw new IllegalArgumentException
("Route must not be null.");
}
if (params == null) {
throw new IllegalArgumentException
("Parameters must not be null.");
}
if ((this.tracker != null) && this.tracker.isConnected()) {
throw new IllegalStateException("Connection already open.");
}
// - collect the arguments
// - call the operator
// - update the tracking data
// In this order, we can be sure that only a successful
// opening of the connection will be tracked.
this.tracker = new RouteTracker(route);
final HttpHost proxy = route.getProxyHost();
connOperator.openConnection
(this.connection,
(proxy != null) ? proxy : route.getTargetHost(),
route.getLocalAddress(),
context, params);
RouteTracker localTracker = tracker; // capture volatile
// If this tracker was reset while connecting,
// fail early.
if (localTracker == null) {
throw new IOException("Request aborted");
}
if (proxy == null) {
localTracker.connectTarget(this.connection.isSecure());
} else {
localTracker.connectProxy(proxy, this.connection.isSecure());
}
}
/**
* Tracks tunnelling of the connection to the target.
* The tunnel has to be established outside by sending a CONNECT
* request to the (last) proxy.
*
* @param secure <code>true</code> if the tunnel should be
* considered secure, <code>false</code> otherwise
* @param params the parameters for tunnelling the connection
*
* @throws IOException in case of a problem
*/
public void tunnelTarget(boolean secure, HttpParams params)
throws IOException {
if (params == null) {
throw new IllegalArgumentException
("Parameters must not be null.");
}
if ((this.tracker == null) || !this.tracker.isConnected()) {
throw new IllegalStateException("Connection not open.");
}
if (this.tracker.isTunnelled()) {
throw new IllegalStateException
("Connection is already tunnelled.");
}
this.connection.update(null, tracker.getTargetHost(),
secure, params);
this.tracker.tunnelTarget(secure);
}
/**
* Tracks tunnelling of the connection to a chained proxy.
* The tunnel has to be established outside by sending a CONNECT
* request to the previous proxy.
*
* @param next the proxy to which the tunnel was established.
* See {@link org.apache.ogt.http.conn.ManagedClientConnection#tunnelProxy
* ManagedClientConnection.tunnelProxy}
* for details.
* @param secure <code>true</code> if the tunnel should be
* considered secure, <code>false</code> otherwise
* @param params the parameters for tunnelling the connection
*
* @throws IOException in case of a problem
*/
public void tunnelProxy(HttpHost next, boolean secure, HttpParams params)
throws IOException {
if (next == null) {
throw new IllegalArgumentException
("Next proxy must not be null.");
}
if (params == null) {
throw new IllegalArgumentException
("Parameters must not be null.");
}
//@@@ check for proxy in planned route?
if ((this.tracker == null) || !this.tracker.isConnected()) {
throw new IllegalStateException("Connection not open.");
}
this.connection.update(null, next, secure, params);
this.tracker.tunnelProxy(next, secure);
}
/**
* Layers a protocol on top of an established tunnel.
*
* @param context the context for layering
* @param params the parameters for layering
*
* @throws IOException in case of a problem
*/
public void layerProtocol(HttpContext context, HttpParams params)
throws IOException {
//@@@ is context allowed to be null? depends on operator?
if (params == null) {
throw new IllegalArgumentException
("Parameters must not be null.");
}
if ((this.tracker == null) || !this.tracker.isConnected()) {
throw new IllegalStateException("Connection not open.");
}
if (!this.tracker.isTunnelled()) {
//@@@ allow this?
throw new IllegalStateException
("Protocol layering without a tunnel not supported.");
}
if (this.tracker.isLayered()) {
throw new IllegalStateException
("Multiple protocol layering not supported.");
}
// - collect the arguments
// - call the operator
// - update the tracking data
// In this order, we can be sure that only a successful
// layering on top of the connection will be tracked.
final HttpHost target = tracker.getTargetHost();
connOperator.updateSecureConnection(this.connection, target,
context, params);
this.tracker.layerProtocol(this.connection.isSecure());
}
/**
* Shuts down the entry.
*
* If {@link #open(HttpRoute, HttpContext, HttpParams)} is in progress,
* this will cause that open to possibly throw an {@link IOException}.
*/
protected void shutdownEntry() {
tracker = null;
state = 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.impl.conn;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSession;
import org.apache.ogt.http.HttpConnectionMetrics;
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.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.ManagedClientConnection;
import org.apache.ogt.http.conn.OperatedClientConnection;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Abstract adapter from {@link OperatedClientConnection operated} to
* {@link ManagedClientConnection managed} client connections.
* Read and write methods are delegated to the wrapped connection.
* Operations affecting the connection state have to be implemented
* by derived classes. Operations for querying the connection state
* are delegated to the wrapped connection if there is one, or
* return a default value if there is none.
* <p>
* This adapter tracks the checkpoints for reusable communication states,
* as indicated by {@link #markReusable markReusable} and queried by
* {@link #isMarkedReusable isMarkedReusable}.
* All send and receive operations will automatically clear the mark.
* <p>
* Connection release calls are delegated to the connection manager,
* if there is one. {@link #abortConnection abortConnection} will
* clear the reusability mark first. The connection manager is
* expected to tolerate multiple calls to the release method.
*
* @since 4.0
*/
public abstract class AbstractClientConnAdapter
implements ManagedClientConnection, HttpContext {
/**
* The connection manager, if any.
* This attribute MUST NOT be final, so the adapter can be detached
* from the connection manager without keeping a hard reference there.
*/
private volatile ClientConnectionManager connManager;
/** The wrapped connection. */
private volatile OperatedClientConnection wrappedConnection;
/** The reusability marker. */
private volatile boolean markedReusable;
/** True if the connection has been shut down or released. */
private volatile boolean released;
/** The duration this is valid for while idle (in ms). */
private volatile long duration;
/**
* Creates a new connection adapter.
* The adapter is initially <i>not</i>
* {@link #isMarkedReusable marked} as reusable.
*
* @param mgr the connection manager, or <code>null</code>
* @param conn the connection to wrap, or <code>null</code>
*/
protected AbstractClientConnAdapter(ClientConnectionManager mgr,
OperatedClientConnection conn) {
super();
connManager = mgr;
wrappedConnection = conn;
markedReusable = false;
released = false;
duration = Long.MAX_VALUE;
}
/**
* Detaches this adapter from the wrapped connection.
* This adapter becomes useless.
*/
protected synchronized void detach() {
wrappedConnection = null;
connManager = null; // base class attribute
duration = Long.MAX_VALUE;
}
protected OperatedClientConnection getWrappedConnection() {
return wrappedConnection;
}
protected ClientConnectionManager getManager() {
return connManager;
}
/**
* @deprecated use {@link #assertValid(OperatedClientConnection)}
*/
@Deprecated
protected final void assertNotAborted() throws InterruptedIOException {
if (isReleased()) {
throw new InterruptedIOException("Connection has been shut down");
}
}
/**
* @since 4.1
* @return value of released flag
*/
protected boolean isReleased() {
return released;
}
/**
* Asserts that there is a valid wrapped connection to delegate to.
*
* @throws ConnectionShutdownException if there is no wrapped connection
* or connection has been aborted
*/
protected final void assertValid(
final OperatedClientConnection wrappedConn) throws ConnectionShutdownException {
if (isReleased() || wrappedConn == null) {
throw new ConnectionShutdownException();
}
}
public boolean isOpen() {
OperatedClientConnection conn = getWrappedConnection();
if (conn == null)
return false;
return conn.isOpen();
}
public boolean isStale() {
if (isReleased())
return true;
OperatedClientConnection conn = getWrappedConnection();
if (conn == null)
return true;
return conn.isStale();
}
public void setSocketTimeout(int timeout) {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
conn.setSocketTimeout(timeout);
}
public int getSocketTimeout() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.getSocketTimeout();
}
public HttpConnectionMetrics getMetrics() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.getMetrics();
}
public void flush() throws IOException {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
conn.flush();
}
public boolean isResponseAvailable(int timeout) throws IOException {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.isResponseAvailable(timeout);
}
public void receiveResponseEntity(HttpResponse response)
throws HttpException, IOException {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
unmarkReusable();
conn.receiveResponseEntity(response);
}
public HttpResponse receiveResponseHeader()
throws HttpException, IOException {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
unmarkReusable();
return conn.receiveResponseHeader();
}
public void sendRequestEntity(HttpEntityEnclosingRequest request)
throws HttpException, IOException {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
unmarkReusable();
conn.sendRequestEntity(request);
}
public void sendRequestHeader(HttpRequest request)
throws HttpException, IOException {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
unmarkReusable();
conn.sendRequestHeader(request);
}
public InetAddress getLocalAddress() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.getLocalAddress();
}
public int getLocalPort() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.getLocalPort();
}
public InetAddress getRemoteAddress() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.getRemoteAddress();
}
public int getRemotePort() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.getRemotePort();
}
public boolean isSecure() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.isSecure();
}
public SSLSession getSSLSession() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
if (!isOpen())
return null;
SSLSession result = null;
Socket sock = conn.getSocket();
if (sock instanceof SSLSocket) {
result = ((SSLSocket)sock).getSession();
}
return result;
}
public void markReusable() {
markedReusable = true;
}
public void unmarkReusable() {
markedReusable = false;
}
public boolean isMarkedReusable() {
return markedReusable;
}
public void setIdleDuration(long duration, TimeUnit unit) {
if(duration > 0) {
this.duration = unit.toMillis(duration);
} else {
this.duration = -1;
}
}
public synchronized void releaseConnection() {
if (released) {
return;
}
released = true;
if (connManager != null) {
connManager.releaseConnection(this, duration, TimeUnit.MILLISECONDS);
}
}
public synchronized void abortConnection() {
if (released) {
return;
}
released = true;
unmarkReusable();
try {
shutdown();
} catch (IOException ignore) {
}
if (connManager != null) {
connManager.releaseConnection(this, duration, TimeUnit.MILLISECONDS);
}
}
public synchronized Object getAttribute(final String id) {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
if (conn instanceof HttpContext) {
return ((HttpContext) conn).getAttribute(id);
} else {
return null;
}
}
public synchronized Object removeAttribute(final String id) {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
if (conn instanceof HttpContext) {
return ((HttpContext) conn).removeAttribute(id);
} else {
return null;
}
}
public synchronized void setAttribute(final String id, final Object obj) {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
if (conn instanceof HttpContext) {
((HttpContext) conn).setAttribute(id, obj);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.conn;
import java.net.InetAddress;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.annotation.ThreadSafe;
import org.apache.ogt.http.conn.params.ConnRouteParams;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.conn.routing.HttpRoutePlanner;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Default implementation of an {@link HttpRoutePlanner}. This implementation
* is based on {@link org.apache.ogt.http.conn.params.ConnRoutePNames parameters}.
* It will not make use of any Java system properties, nor of system or
* browser proxy settings.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#DEFAULT_PROXY}</li>
* <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#LOCAL_ADDRESS}</li>
* <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#FORCED_ROUTE}</li>
* </ul>
*
* @since 4.0
*/
@ThreadSafe
public class DefaultHttpRoutePlanner implements HttpRoutePlanner {
/** The scheme registry. */
protected final SchemeRegistry schemeRegistry; // class is @ThreadSafe
/**
* Creates a new default route planner.
*
* @param schreg the scheme registry
*/
public DefaultHttpRoutePlanner(SchemeRegistry schreg) {
if (schreg == null) {
throw new IllegalArgumentException
("SchemeRegistry must not be null.");
}
schemeRegistry = schreg;
}
public HttpRoute determineRoute(HttpHost target,
HttpRequest request,
HttpContext context)
throws HttpException {
if (request == null) {
throw new IllegalStateException
("Request must not be null.");
}
// If we have a forced route, we can do without a target.
HttpRoute route =
ConnRouteParams.getForcedRoute(request.getParams());
if (route != null)
return route;
// If we get here, there is no forced route.
// So we need a target to compute a route.
if (target == null) {
throw new IllegalStateException
("Target host must not be null.");
}
final InetAddress local =
ConnRouteParams.getLocalAddress(request.getParams());
final HttpHost proxy =
ConnRouteParams.getDefaultProxy(request.getParams());
final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
// as it is typically used for TLS/SSL, we assume that
// a layered scheme implies a secure connection
final boolean secure = schm.isLayered();
if (proxy == null) {
route = new HttpRoute(target, local, secure);
} else {
route = new HttpRoute(target, local, proxy, secure);
}
return route;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.conn;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.commons.logging.Log;
/**
* Logs data to the wire LOG.
*
*
* @since 4.0
*/
@Immutable
public class Wire {
private final Log log;
public Wire(Log log) {
this.log = log;
}
private void wire(String header, InputStream instream)
throws IOException {
StringBuilder buffer = new StringBuilder();
int ch;
while ((ch = instream.read()) != -1) {
if (ch == 13) {
buffer.append("[\\r]");
} else if (ch == 10) {
buffer.append("[\\n]\"");
buffer.insert(0, "\"");
buffer.insert(0, header);
log.debug(buffer.toString());
buffer.setLength(0);
} else if ((ch < 32) || (ch > 127)) {
buffer.append("[0x");
buffer.append(Integer.toHexString(ch));
buffer.append("]");
} else {
buffer.append((char) ch);
}
}
if (buffer.length() > 0) {
buffer.append('\"');
buffer.insert(0, '\"');
buffer.insert(0, header);
log.debug(buffer.toString());
}
}
public boolean enabled() {
return log.isDebugEnabled();
}
public void output(InputStream outstream)
throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output may not be null");
}
wire(">> ", outstream);
}
public void input(InputStream instream)
throws IOException {
if (instream == null) {
throw new IllegalArgumentException("Input may not be null");
}
wire("<< ", instream);
}
public void output(byte[] b, int off, int len)
throws IOException {
if (b == null) {
throw new IllegalArgumentException("Output may not be null");
}
wire(">> ", new ByteArrayInputStream(b, off, len));
}
public void input(byte[] b, int off, int len)
throws IOException {
if (b == null) {
throw new IllegalArgumentException("Input may not be null");
}
wire("<< ", new ByteArrayInputStream(b, off, len));
}
public void output(byte[] b)
throws IOException {
if (b == null) {
throw new IllegalArgumentException("Output may not be null");
}
wire(">> ", new ByteArrayInputStream(b));
}
public void input(byte[] b)
throws IOException {
if (b == null) {
throw new IllegalArgumentException("Input may not be null");
}
wire("<< ", new ByteArrayInputStream(b));
}
public void output(int b)
throws IOException {
output(new byte[] {(byte) b});
}
public void input(int b)
throws IOException {
input(new byte[] {(byte) b});
}
@Deprecated
public void output(final String s)
throws IOException {
if (s == null) {
throw new IllegalArgumentException("Output may not be null");
}
output(s.getBytes());
}
@Deprecated
public void input(final String s)
throws IOException {
if (s == null) {
throw new IllegalArgumentException("Input may not be null");
}
input(s.getBytes());
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.annotation.Immutable;
/**
* Signals that the tunnel request was rejected by the proxy host.
*
* @since 4.0
*/
@Immutable
public class TunnelRefusedException extends HttpException {
private static final long serialVersionUID = -8646722842745617323L;
private final HttpResponse response;
public TunnelRefusedException(final String message, final HttpResponse response) {
super(message);
this.response = response;
}
public HttpResponse getResponse() {
return this.response;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import java.util.HashMap;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.client.AuthCache;
/**
* Default implementation of {@link AuthCache}.
*
* @since 4.0
*/
@NotThreadSafe
public class BasicAuthCache implements AuthCache {
private final HashMap<HttpHost, AuthScheme> map;
/**
* Default constructor.
*/
public BasicAuthCache() {
super();
this.map = new HashMap<HttpHost, AuthScheme>();
}
public void put(final HttpHost host, final AuthScheme authScheme) {
if (host == null) {
throw new IllegalArgumentException("HTTP host may not be null");
}
this.map.put(host, authScheme);
}
public AuthScheme get(final HttpHost host) {
if (host == null) {
throw new IllegalArgumentException("HTTP host may not be null");
}
return this.map.get(host);
}
public void remove(final HttpHost host) {
if (host == null) {
throw new IllegalArgumentException("HTTP host may not be null");
}
this.map.remove(host);
}
public void clear() {
this.map.clear();
}
@Override
public String toString() {
return this.map.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.impl.client;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.ogt.http.annotation.ThreadSafe;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.client.CredentialsProvider;
/**
* Default implementation of {@link CredentialsProvider}.
*
* @since 4.0
*/
@ThreadSafe
public class BasicCredentialsProvider implements CredentialsProvider {
private final ConcurrentHashMap<AuthScope, Credentials> credMap;
/**
* Default constructor.
*/
public BasicCredentialsProvider() {
super();
this.credMap = new ConcurrentHashMap<AuthScope, Credentials>();
}
public void setCredentials(
final AuthScope authscope,
final Credentials credentials) {
if (authscope == null) {
throw new IllegalArgumentException("Authentication scope may not be null");
}
credMap.put(authscope, credentials);
}
/**
* Find matching {@link Credentials credentials} for the given authentication scope.
*
* @param map the credentials hash map
* @param authscope the {@link AuthScope authentication scope}
* @return the credentials
*
*/
private static Credentials matchCredentials(
final Map<AuthScope, Credentials> map,
final AuthScope authscope) {
// see if we get a direct hit
Credentials creds = map.get(authscope);
if (creds == null) {
// Nope.
// Do a full scan
int bestMatchFactor = -1;
AuthScope bestMatch = null;
for (AuthScope current: map.keySet()) {
int factor = authscope.match(current);
if (factor > bestMatchFactor) {
bestMatchFactor = factor;
bestMatch = current;
}
}
if (bestMatch != null) {
creds = map.get(bestMatch);
}
}
return creds;
}
public Credentials getCredentials(final AuthScope authscope) {
if (authscope == null) {
throw new IllegalArgumentException("Authentication scope may not be null");
}
return matchCredentials(this.credMap, authscope);
}
public void clear() {
this.credMap.clear();
}
@Override
public String toString() {
return credMap.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.impl.client;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.HttpStatus;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.client.CircularRedirectException;
import org.apache.ogt.http.client.RedirectHandler;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.methods.HttpHead;
import org.apache.ogt.http.client.params.ClientPNames;
import org.apache.ogt.http.client.utils.URIUtils;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Default implementation of {@link RedirectHandler}.
*
* @since 4.0
*
* @deprecated use {@link DefaultRedirectStrategy}.
*/
@Immutable
@Deprecated
public class DefaultRedirectHandler implements RedirectHandler {
private final Log log = LogFactory.getLog(getClass());
private static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations";
public DefaultRedirectHandler() {
super();
}
public boolean isRedirectRequested(
final HttpResponse response,
final HttpContext context) {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
int statusCode = response.getStatusLine().getStatusCode();
switch (statusCode) {
case HttpStatus.SC_MOVED_TEMPORARILY:
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_TEMPORARY_REDIRECT:
HttpRequest request = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
String method = request.getRequestLine().getMethod();
return method.equalsIgnoreCase(HttpGet.METHOD_NAME)
|| method.equalsIgnoreCase(HttpHead.METHOD_NAME);
case HttpStatus.SC_SEE_OTHER:
return true;
default:
return false;
} //end of switch
}
public URI getLocationURI(
final HttpResponse response,
final HttpContext context) throws ProtocolException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
//get the location header to find out where to redirect to
Header locationHeader = response.getFirstHeader("location");
if (locationHeader == null) {
// got a redirect response, but no location header
throw new ProtocolException(
"Received redirect response " + response.getStatusLine()
+ " but no location header");
}
String location = locationHeader.getValue();
if (this.log.isDebugEnabled()) {
this.log.debug("Redirect requested to location '" + location + "'");
}
URI uri;
try {
uri = new URI(location);
} catch (URISyntaxException ex) {
throw new ProtocolException("Invalid redirect URI: " + location, ex);
}
HttpParams params = response.getParams();
// rfc2616 demands the location value be a complete URI
// Location = "Location" ":" absoluteURI
if (!uri.isAbsolute()) {
if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
throw new ProtocolException("Relative redirect location '"
+ uri + "' not allowed");
}
// Adjust location URI
HttpHost target = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
if (target == null) {
throw new IllegalStateException("Target host not available " +
"in the HTTP context");
}
HttpRequest request = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
try {
URI requestURI = new URI(request.getRequestLine().getUri());
URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
uri = URIUtils.resolve(absoluteRequestURI, uri);
} catch (URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
}
if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {
RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(
REDIRECT_LOCATIONS);
if (redirectLocations == null) {
redirectLocations = new RedirectLocations();
context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
}
URI redirectURI;
if (uri.getFragment() != null) {
try {
HttpHost target = new HttpHost(
uri.getHost(),
uri.getPort(),
uri.getScheme());
redirectURI = URIUtils.rewriteURI(uri, target, true);
} catch (URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
} else {
redirectURI = uri;
}
if (redirectLocations.contains(redirectURI)) {
throw new CircularRedirectException("Circular redirect to '" +
redirectURI + "'");
} else {
redirectLocations.add(redirectURI);
}
}
return uri;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.impl.client;
import org.apache.ogt.http.annotation.ThreadSafe;
import org.apache.ogt.http.client.protocol.RequestAcceptEncoding;
import org.apache.ogt.http.client.protocol.ResponseContentEncoding;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.BasicHttpProcessor;
/**
* {@link DefaultHttpClient} sub-class which includes a {@link RequestAcceptEncoding}
* for the request and response.
*
* @since 4.1
*/
@ThreadSafe // since DefaultHttpClient is
public class ContentEncodingHttpClient extends DefaultHttpClient {
/**
* Creates a new HTTP client from parameters and a connection manager.
*
* @param params the parameters
* @param conman the connection manager
*/
public ContentEncodingHttpClient(ClientConnectionManager conman, HttpParams params) {
super(conman, params);
}
/**
* @param params
*/
public ContentEncodingHttpClient(HttpParams params) {
this(null, params);
}
/**
*
*/
public ContentEncodingHttpClient() {
this(null);
}
/**
* {@inheritDoc}
*/
@Override
protected BasicHttpProcessor createHttpProcessor() {
BasicHttpProcessor result = super.createHttpProcessor();
result.addRequestInterceptor(new RequestAcceptEncoding());
result.addResponseInterceptor(new ResponseContentEncoding());
return result;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import java.security.Principal;
import javax.net.ssl.SSLSession;
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.auth.Credentials;
import org.apache.ogt.http.client.UserTokenHandler;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.conn.HttpRoutedConnection;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Default implementation of {@link UserTokenHandler}. This class will use
* an instance of {@link Principal} as a state object for HTTP connections,
* if it can be obtained from the given execution context. This helps ensure
* persistent connections created with a particular user identity within
* a particular security context can be reused by the same user only.
* <p>
* DefaultUserTokenHandler will use the user principle of connection
* based authentication schemes such as NTLM or that of the SSL session
* with the client authentication turned on. If both are unavailable,
* <code>null</code> token will be returned.
*
* @since 4.0
*/
@Immutable
public class DefaultUserTokenHandler implements UserTokenHandler {
public Object getUserToken(final HttpContext context) {
Principal userPrincipal = null;
AuthState targetAuthState = (AuthState) context.getAttribute(
ClientContext.TARGET_AUTH_STATE);
if (targetAuthState != null) {
userPrincipal = getAuthPrincipal(targetAuthState);
if (userPrincipal == null) {
AuthState proxyAuthState = (AuthState) context.getAttribute(
ClientContext.PROXY_AUTH_STATE);
userPrincipal = getAuthPrincipal(proxyAuthState);
}
}
if (userPrincipal == null) {
HttpRoutedConnection conn = (HttpRoutedConnection) context.getAttribute(
ExecutionContext.HTTP_CONNECTION);
if (conn.isOpen()) {
SSLSession sslsession = conn.getSSLSession();
if (sslsession != null) {
userPrincipal = sslsession.getLocalPrincipal();
}
}
}
return userPrincipal;
}
private static Principal getAuthPrincipal(final AuthState authState) {
AuthScheme scheme = authState.getAuthScheme();
if (scheme != null && scheme.isComplete() && scheme.isConnectionBased()) {
Credentials creds = authState.getCredentials();
if (creds != null) {
return creds.getUserPrincipal();
}
}
return null;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLException;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.client.HttpRequestRetryHandler;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
/**
* The default {@link HttpRequestRetryHandler} used by request executors.
*
*
* @since 4.0
*/
@Immutable
public class DefaultHttpRequestRetryHandler implements HttpRequestRetryHandler {
/** the number of times a method will be retried */
private final int retryCount;
/** Whether or not methods that have successfully sent their request will be retried */
private final boolean requestSentRetryEnabled;
/**
* Default constructor
*/
public DefaultHttpRequestRetryHandler(int retryCount, boolean requestSentRetryEnabled) {
super();
this.retryCount = retryCount;
this.requestSentRetryEnabled = requestSentRetryEnabled;
}
/**
* Default constructor
*/
public DefaultHttpRequestRetryHandler() {
this(3, false);
}
/**
* Used <code>retryCount</code> and <code>requestSentRetryEnabled</code> to determine
* if the given method should be retried.
*/
public boolean retryRequest(
final IOException exception,
int executionCount,
final HttpContext context) {
if (exception == null) {
throw new IllegalArgumentException("Exception parameter may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
if (executionCount > this.retryCount) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof ConnectException) {
// Connection refused
return false;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest)
context.getAttribute(ExecutionContext.HTTP_REQUEST);
if (handleAsIdempotent(request)) {
// Retry if the request is considered idempotent
return true;
}
Boolean b = (Boolean)
context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
boolean sent = (b != null && b.booleanValue());
if (!sent || this.requestSentRetryEnabled) {
// Retry if the request has not been sent fully or
// if it's OK to retry methods that have been sent
return true;
}
// otherwise do not retry
return false;
}
/**
* @return <code>true</code> if this handler will retry methods that have
* successfully sent their request, <code>false</code> otherwise
*/
public boolean isRequestSentRetryEnabled() {
return requestSentRetryEnabled;
}
/**
* @return the maximum number of times a method will be retried
*/
public int getRetryCount() {
return retryCount;
}
private boolean handleAsIdempotent(final HttpRequest request) {
return !(request instanceof HttpEntityEnclosingRequest);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import java.io.IOException;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.StatusLine;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.client.HttpResponseException;
import org.apache.ogt.http.client.ResponseHandler;
import org.apache.ogt.http.util.EntityUtils;
/**
* A {@link ResponseHandler} that returns the response body as a String
* for successful (2xx) responses. If the response code was >= 300, the response
* body is consumed and an {@link HttpResponseException} is thrown.
*
* If this is used with
* {@link org.apache.ogt.http.client.HttpClient#execute(
* org.apache.ogt.http.client.methods.HttpUriRequest, ResponseHandler)},
* HttpClient may handle redirects (3xx responses) internally.
*
*
* @since 4.0
*/
@Immutable
public class BasicResponseHandler implements ResponseHandler<String> {
/**
* Returns the response body as a String if the response was successful (a
* 2xx status code). If no response body exists, this returns null. If the
* response was unsuccessful (>= 300 status code), throws an
* {@link HttpResponseException}.
*/
public String handleResponse(final HttpResponse response)
throws HttpResponseException, IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
return entity == null ? null : EntityUtils.toString(entity);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.annotation.ThreadSafe;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.protocol.RequestAddCookies;
import org.apache.ogt.http.client.protocol.RequestAuthCache;
import org.apache.ogt.http.client.protocol.RequestClientConnControl;
import org.apache.ogt.http.client.protocol.RequestDefaultHeaders;
import org.apache.ogt.http.client.protocol.RequestProxyAuthentication;
import org.apache.ogt.http.client.protocol.RequestTargetAuthentication;
import org.apache.ogt.http.client.protocol.ResponseAuthCache;
import org.apache.ogt.http.client.protocol.ResponseProcessCookies;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.HttpConnectionParams;
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.BasicHttpProcessor;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
import org.apache.ogt.http.util.VersionInfo;
/**
* Default implementation of {@link HttpClient} pre-configured for most common use scenarios.
* <p>
* This class creates the following chain of protocol interceptors per default:
* <ul>
* <li>{@link RequestDefaultHeaders}</li>
* <li>{@link RequestContent}</li>
* <li>{@link RequestTargetHost}</li>
* <li>{@link RequestClientConnControl}</li>
* <li>{@link RequestUserAgent}</li>
* <li>{@link RequestExpectContinue}</li>
* <li>{@link RequestAddCookies}</li>
* <li>{@link ResponseProcessCookies}</li>
* <li>{@link RequestTargetAuthentication}</li>
* <li>{@link RequestProxyAuthentication}</li>
* </ul>
* <p>
* This class sets up the following parameters if not explicitly set:
* <ul>
* <li>Version: HttpVersion.HTTP_1_1</li>
* <li>ContentCharset: HTTP.DEFAULT_CONTENT_CHARSET</li>
* <li>NoTcpDelay: true</li>
* <li>SocketBufferSize: 8192</li>
* <li>UserAgent: Apache-HttpClient/release (java 1.5)</li>
* </ul>
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#PROTOCOL_VERSION}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#USE_EXPECT_CONTINUE}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#USER_AGENT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_LINGER}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_REUSEADDR}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#STALE_CONNECTION_CHECK}</li>
* <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#FORCED_ROUTE}</li>
* <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#LOCAL_ADDRESS}</li>
* <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#DEFAULT_PROXY}</li>
* <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.auth.params.AuthPNames#CREDENTIAL_CHARSET}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#COOKIE_POLICY}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#HANDLE_AUTHENTICATION}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#HANDLE_REDIRECTS}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#MAX_REDIRECTS}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#ALLOW_CIRCULAR_REDIRECTS}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#VIRTUAL_HOST}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#DEFAULT_HOST}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#DEFAULT_HEADERS}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#CONNECTION_MANAGER_FACTORY_CLASS_NAME}</li>
* </ul>
*
* @since 4.0
*/
@ThreadSafe
public class DefaultHttpClient extends AbstractHttpClient {
/**
* Creates a new HTTP client from parameters and a connection manager.
*
* @param params the parameters
* @param conman the connection manager
*/
public DefaultHttpClient(
final ClientConnectionManager conman,
final HttpParams params) {
super(conman, params);
}
/**
* @since 4.1
*/
public DefaultHttpClient(
final ClientConnectionManager conman) {
super(conman, null);
}
public DefaultHttpClient(final HttpParams params) {
super(null, params);
}
public DefaultHttpClient() {
super(null, null);
}
/**
* Creates the default set of HttpParams by invoking {@link DefaultHttpClient#setDefaultHttpParams(HttpParams)}
*
* @return a new instance of {@link SyncBasicHttpParams} with the defaults applied to it.
*/
@Override
protected HttpParams createHttpParams() {
HttpParams params = new SyncBasicHttpParams();
setDefaultHttpParams(params);
return params;
}
/**
* Saves the default set of HttpParams in the provided parameter.
* These are:
* <ul>
* <li>{@link CoreProtocolPNames#PROTOCOL_VERSION}: 1.1</li>
* <li>{@link CoreProtocolPNames#HTTP_CONTENT_CHARSET}: ISO-8859-1</li>
* <li>{@link CoreConnectionPNames#TCP_NODELAY}: true</li>
* <li>{@link CoreConnectionPNames#SOCKET_BUFFER_SIZE}: 8192</li>
* <li>{@link CoreProtocolPNames#USER_AGENT}: Apache-HttpClient/<release> (java 1.5)</li>
* </ul>
*/
public static void setDefaultHttpParams(HttpParams params) {
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
HttpConnectionParams.setTcpNoDelay(params, true);
HttpConnectionParams.setSocketBufferSize(params, 8192);
// determine the release version from packaged version info
final VersionInfo vi = VersionInfo.loadVersionInfo
("org.apache.ogt.http.client", DefaultHttpClient.class.getClassLoader());
final String release = (vi != null) ?
vi.getRelease() : VersionInfo.UNAVAILABLE;
HttpProtocolParams.setUserAgent(params,
"Apache-HttpClient/" + release + " (java 1.5)");
}
@Override
protected BasicHttpProcessor createHttpProcessor() {
BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new RequestDefaultHeaders());
// Required protocol interceptors
httpproc.addInterceptor(new RequestContent());
httpproc.addInterceptor(new RequestTargetHost());
// Recommended protocol interceptors
httpproc.addInterceptor(new RequestClientConnControl());
httpproc.addInterceptor(new RequestUserAgent());
httpproc.addInterceptor(new RequestExpectContinue());
// HTTP state management interceptors
httpproc.addInterceptor(new RequestAddCookies());
httpproc.addInterceptor(new ResponseProcessCookies());
// HTTP authentication interceptors
httpproc.addInterceptor(new RequestAuthCache());
httpproc.addInterceptor(new ResponseAuthCache());
httpproc.addInterceptor(new RequestTargetAuthentication());
httpproc.addInterceptor(new RequestProxyAuthentication());
return httpproc;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.entity.HttpEntityWrapper;
import org.apache.ogt.http.protocol.HTTP;
/**
* A wrapper class for {@link HttpEntityEnclosingRequest}s that can
* be used to change properties of the current request without
* modifying the original object.
* </p>
* This class is also capable of resetting the request headers to
* the state of the original request.
*
*
* @since 4.0
*/
@NotThreadSafe // e.g. [gs]etEntity()
public class EntityEnclosingRequestWrapper extends RequestWrapper
implements HttpEntityEnclosingRequest {
private HttpEntity entity;
private boolean consumed;
public EntityEnclosingRequestWrapper(final HttpEntityEnclosingRequest request)
throws ProtocolException {
super(request);
setEntity(request.getEntity());
}
public HttpEntity getEntity() {
return this.entity;
}
public void setEntity(final HttpEntity entity) {
this.entity = entity != null ? new EntityWrapper(entity) : null;
this.consumed = false;
}
public boolean expectContinue() {
Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE);
return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue());
}
@Override
public boolean isRepeatable() {
return this.entity == null || this.entity.isRepeatable() || !this.consumed;
}
class EntityWrapper extends HttpEntityWrapper {
EntityWrapper(final HttpEntity entity) {
super(entity);
}
@Deprecated
@Override
public void consumeContent() throws IOException {
consumed = true;
super.consumeContent();
}
@Override
public InputStream getContent() throws IOException {
consumed = true;
return super.getContent();
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
consumed = true;
super.writeTo(outstream);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.conn.routing.HttpRoute;
/**
* A request with the route along which it should be sent.
*
* @since 4.0
*/
@NotThreadSafe // RequestWrapper is @NotThreadSafe
public class RoutedRequest {
protected final RequestWrapper request; // @NotThreadSafe
protected final HttpRoute route; // @Immutable
/**
* Creates a new routed request.
*
* @param req the request
* @param route the route
*/
public RoutedRequest(final RequestWrapper req, final HttpRoute route) {
super();
this.request = req;
this.route = route;
}
public final RequestWrapper getRequest() {
return request;
}
public final HttpRoute getRoute() {
return route;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.HeaderElementIterator;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.conn.ConnectionKeepAliveStrategy;
import org.apache.ogt.http.message.BasicHeaderElementIterator;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Default implementation of a strategy deciding duration
* that a connection can remain idle.
*
* The default implementation looks solely at the 'Keep-Alive'
* header's timeout token.
*
* @since 4.0
*/
@Immutable
public class DefaultConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy {
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch(NumberFormatException ignore) {
}
}
}
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.impl.client;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.HttpStatus;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.client.CircularRedirectException;
import org.apache.ogt.http.client.RedirectStrategy;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.methods.HttpHead;
import org.apache.ogt.http.client.methods.HttpUriRequest;
import org.apache.ogt.http.client.params.ClientPNames;
import org.apache.ogt.http.client.utils.URIUtils;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Default implementation of {@link RedirectStrategy}.
*
* @since 4.1
*/
@Immutable
public class DefaultRedirectStrategy implements RedirectStrategy {
private final Log log = LogFactory.getLog(getClass());
public static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations";
public DefaultRedirectStrategy() {
super();
}
public boolean isRedirected(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws ProtocolException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
int statusCode = response.getStatusLine().getStatusCode();
String method = request.getRequestLine().getMethod();
Header locationHeader = response.getFirstHeader("location");
switch (statusCode) {
case HttpStatus.SC_MOVED_TEMPORARILY:
return (method.equalsIgnoreCase(HttpGet.METHOD_NAME)
|| method.equalsIgnoreCase(HttpHead.METHOD_NAME)) && locationHeader != null;
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_TEMPORARY_REDIRECT:
return method.equalsIgnoreCase(HttpGet.METHOD_NAME)
|| method.equalsIgnoreCase(HttpHead.METHOD_NAME);
case HttpStatus.SC_SEE_OTHER:
return true;
default:
return false;
} //end of switch
}
public URI getLocationURI(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws ProtocolException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
//get the location header to find out where to redirect to
Header locationHeader = response.getFirstHeader("location");
if (locationHeader == null) {
// got a redirect response, but no location header
throw new ProtocolException(
"Received redirect response " + response.getStatusLine()
+ " but no location header");
}
String location = locationHeader.getValue();
if (this.log.isDebugEnabled()) {
this.log.debug("Redirect requested to location '" + location + "'");
}
URI uri = createLocationURI(location);
HttpParams params = response.getParams();
// rfc2616 demands the location value be a complete URI
// Location = "Location" ":" absoluteURI
if (!uri.isAbsolute()) {
if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
throw new ProtocolException("Relative redirect location '"
+ uri + "' not allowed");
}
// Adjust location URI
HttpHost target = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
if (target == null) {
throw new IllegalStateException("Target host not available " +
"in the HTTP context");
}
try {
URI requestURI = new URI(request.getRequestLine().getUri());
URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
uri = URIUtils.resolve(absoluteRequestURI, uri);
} catch (URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
}
if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {
RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(
REDIRECT_LOCATIONS);
if (redirectLocations == null) {
redirectLocations = new RedirectLocations();
context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
}
URI redirectURI;
if (uri.getFragment() != null) {
try {
HttpHost target = new HttpHost(
uri.getHost(),
uri.getPort(),
uri.getScheme());
redirectURI = URIUtils.rewriteURI(uri, target, true);
} catch (URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
} else {
redirectURI = uri;
}
if (redirectLocations.contains(redirectURI)) {
throw new CircularRedirectException("Circular redirect to '" +
redirectURI + "'");
} else {
redirectLocations.add(redirectURI);
}
}
return uri;
}
/**
* @since 4.1
*/
protected URI createLocationURI(final String location) throws ProtocolException {
try {
return new URI(location);
} catch (URISyntaxException ex) {
throw new ProtocolException("Invalid redirect URI: " + location, ex);
}
}
public HttpUriRequest getRedirect(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws ProtocolException {
URI uri = getLocationURI(request, response, context);
String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
return new HttpHead(uri);
} else {
return new HttpGet(uri);
}
}
} | Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.ProtocolException;
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.methods.HttpUriRequest;
import org.apache.ogt.http.message.AbstractHttpMessage;
import org.apache.ogt.http.message.BasicRequestLine;
import org.apache.ogt.http.params.HttpProtocolParams;
/**
* A wrapper class for {@link HttpRequest}s that can be used to change
* properties of the current request without modifying the original
* object.
* </p>
* This class is also capable of resetting the request headers to
* the state of the original request.
*
*
* @since 4.0
*/
@NotThreadSafe
public class RequestWrapper extends AbstractHttpMessage implements HttpUriRequest {
private final HttpRequest original;
private URI uri;
private String method;
private ProtocolVersion version;
private int execCount;
public RequestWrapper(final HttpRequest request) throws ProtocolException {
super();
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
this.original = request;
setParams(request.getParams());
setHeaders(request.getAllHeaders());
// Make a copy of the original URI
if (request instanceof HttpUriRequest) {
this.uri = ((HttpUriRequest) request).getURI();
this.method = ((HttpUriRequest) request).getMethod();
this.version = null;
} else {
RequestLine requestLine = request.getRequestLine();
try {
this.uri = new URI(requestLine.getUri());
} catch (URISyntaxException ex) {
throw new ProtocolException("Invalid request URI: "
+ requestLine.getUri(), ex);
}
this.method = requestLine.getMethod();
this.version = request.getProtocolVersion();
}
this.execCount = 0;
}
public void resetHeaders() {
// Make a copy of original headers
this.headergroup.clear();
setHeaders(this.original.getAllHeaders());
}
public String getMethod() {
return this.method;
}
public void setMethod(final String method) {
if (method == null) {
throw new IllegalArgumentException("Method name may not be null");
}
this.method = method;
}
public ProtocolVersion getProtocolVersion() {
if (this.version == null) {
this.version = HttpProtocolParams.getVersion(getParams());
}
return this.version;
}
public void setProtocolVersion(final ProtocolVersion version) {
this.version = version;
}
public URI getURI() {
return this.uri;
}
public void setURI(final URI uri) {
this.uri = uri;
}
public RequestLine getRequestLine() {
String method = getMethod();
ProtocolVersion ver = getProtocolVersion();
String uritext = null;
if (uri != null) {
uritext = uri.toASCIIString();
}
if (uritext == null || uritext.length() == 0) {
uritext = "/";
}
return new BasicRequestLine(method, uritext, ver);
}
public void abort() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
public boolean isAborted() {
return false;
}
public HttpRequest getOriginal() {
return this.original;
}
public boolean isRepeatable() {
return true;
}
public int getExecCount() {
return this.execCount;
}
public void incrementExecCount() {
this.execCount++;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import java.util.List;
import java.util.Map;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.auth.params.AuthPNames;
import org.apache.ogt.http.client.AuthenticationHandler;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Default {@link AuthenticationHandler} implementation for target host
* authentication.
*
* @since 4.0
*/
@Immutable
public class DefaultTargetAuthenticationHandler extends AbstractAuthenticationHandler {
public DefaultTargetAuthenticationHandler() {
super();
}
public boolean isAuthenticationRequested(
final HttpResponse response,
final HttpContext context) {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
int status = response.getStatusLine().getStatusCode();
return status == HttpStatus.SC_UNAUTHORIZED;
}
public Map<String, Header> getChallenges(
final HttpResponse response,
final HttpContext context) throws MalformedChallengeException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
Header[] headers = response.getHeaders(AUTH.WWW_AUTH);
return parseChallenges(headers);
}
@Override
protected List<String> getAuthPreferences(
final HttpResponse response,
final HttpContext context) {
@SuppressWarnings("unchecked")
List<String> authpref = (List<String>) response.getParams().getParameter(
AuthPNames.TARGET_AUTH_PREF);
if (authpref != null) {
return authpref;
} else {
return super.getAuthPreferences(response, context);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.params.AbstractHttpParams;
import org.apache.ogt.http.params.HttpParams;
/**
* Represents a stack of parameter collections.
* When retrieving a parameter, the stack is searched in a fixed order
* and the first match returned. Setting parameters via the stack is
* not supported. To minimize overhead, the stack has a fixed size and
* does not maintain an internal array.
* The supported stack entries, sorted by increasing priority, are:
* <ol>
* <li>Application parameters:
* expected to be the same for all clients used by an application.
* These provide "global", that is application-wide, defaults.
* </li>
* <li>Client parameters:
* specific to an instance of
* {@link org.apache.ogt.http.client.HttpClient HttpClient}.
* These provide client specific defaults.
* </li>
* <li>Request parameters:
* specific to a single request execution.
* For overriding client and global defaults.
* </li>
* <li>Override parameters:
* specific to an instance of
* {@link org.apache.ogt.http.client.HttpClient HttpClient}.
* These can be used to set parameters that cannot be overridden
* on a per-request basis.
* </li>
* </ol>
* Each stack entry may be <code>null</code>. That is preferable over
* an empty params collection, since it avoids searching the empty collection
* when looking up parameters.
*
*
*
* @since 4.0
*/
@NotThreadSafe
public class ClientParamsStack extends AbstractHttpParams {
/** The application parameter collection, or <code>null</code>. */
protected final HttpParams applicationParams;
/** The client parameter collection, or <code>null</code>. */
protected final HttpParams clientParams;
/** The request parameter collection, or <code>null</code>. */
protected final HttpParams requestParams;
/** The override parameter collection, or <code>null</code>. */
protected final HttpParams overrideParams;
/**
* Creates a new parameter stack from elements.
* The arguments will be stored as-is, there is no copying to
* prevent modification.
*
* @param aparams application parameters, or <code>null</code>
* @param cparams client parameters, or <code>null</code>
* @param rparams request parameters, or <code>null</code>
* @param oparams override parameters, or <code>null</code>
*/
public ClientParamsStack(HttpParams aparams, HttpParams cparams,
HttpParams rparams, HttpParams oparams) {
applicationParams = aparams;
clientParams = cparams;
requestParams = rparams;
overrideParams = oparams;
}
/**
* Creates a copy of a parameter stack.
* The new stack will have the exact same entries as the argument stack.
* There is no copying of parameters.
*
* @param stack the stack to copy
*/
public ClientParamsStack(ClientParamsStack stack) {
this(stack.getApplicationParams(),
stack.getClientParams(),
stack.getRequestParams(),
stack.getOverrideParams());
}
/**
* Creates a modified copy of a parameter stack.
* The new stack will contain the explicitly passed elements.
* For elements where the explicit argument is <code>null</code>,
* the corresponding element from the argument stack is used.
* There is no copying of parameters.
*
* @param stack the stack to modify
* @param aparams application parameters, or <code>null</code>
* @param cparams client parameters, or <code>null</code>
* @param rparams request parameters, or <code>null</code>
* @param oparams override parameters, or <code>null</code>
*/
public ClientParamsStack(ClientParamsStack stack,
HttpParams aparams, HttpParams cparams,
HttpParams rparams, HttpParams oparams) {
this((aparams != null) ? aparams : stack.getApplicationParams(),
(cparams != null) ? cparams : stack.getClientParams(),
(rparams != null) ? rparams : stack.getRequestParams(),
(oparams != null) ? oparams : stack.getOverrideParams());
}
/**
* Obtains the application parameters of this stack.
*
* @return the application parameters, or <code>null</code>
*/
public final HttpParams getApplicationParams() {
return applicationParams;
}
/**
* Obtains the client parameters of this stack.
*
* @return the client parameters, or <code>null</code>
*/
public final HttpParams getClientParams() {
return clientParams;
}
/**
* Obtains the request parameters of this stack.
*
* @return the request parameters, or <code>null</code>
*/
public final HttpParams getRequestParams() {
return requestParams;
}
/**
* Obtains the override parameters of this stack.
*
* @return the override parameters, or <code>null</code>
*/
public final HttpParams getOverrideParams() {
return overrideParams;
}
/**
* Obtains a parameter from this stack.
* See class comment for search order.
*
* @param name the name of the parameter to obtain
*
* @return the highest-priority value for that parameter, or
* <code>null</code> if it is not set anywhere in this stack
*/
public Object getParameter(String name) {
if (name == null) {
throw new IllegalArgumentException
("Parameter name must not be null.");
}
Object result = null;
if (overrideParams != null) {
result = overrideParams.getParameter(name);
}
if ((result == null) && (requestParams != null)) {
result = requestParams.getParameter(name);
}
if ((result == null) && (clientParams != null)) {
result = clientParams.getParameter(name);
}
if ((result == null) && (applicationParams != null)) {
result = applicationParams.getParameter(name);
}
return result;
}
/**
* Does <i>not</i> set a parameter.
* Parameter stacks are read-only. It is possible, though discouraged,
* to access and modify specific stack entries.
* Derived classes may change this behavior.
*
* @param name ignored
* @param value ignored
*
* @return nothing
*
* @throws UnsupportedOperationException always
*/
public HttpParams setParameter(String name, Object value)
throws UnsupportedOperationException {
throw new UnsupportedOperationException
("Setting parameters in a stack is not supported.");
}
/**
* Does <i>not</i> remove a parameter.
* Parameter stacks are read-only. It is possible, though discouraged,
* to access and modify specific stack entries.
* Derived classes may change this behavior.
*
* @param name ignored
*
* @return nothing
*
* @throws UnsupportedOperationException always
*/
public boolean removeParameter(String name) {
throw new UnsupportedOperationException
("Removing parameters in a stack is not supported.");
}
/**
* Does <i>not</i> copy parameters.
* Parameter stacks are lightweight objects, expected to be instantiated
* as needed and to be used only in a very specific context. On top of
* that, they are read-only. The typical copy operation to prevent
* accidental modification of parameters passed by the application to
* a framework object is therefore pointless and disabled.
* Create a new stack if you really need a copy.
* <br/>
* Derived classes may change this behavior.
*
* @return <code>this</code> parameter stack
*/
public HttpParams copy() {
return this;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import java.io.Serializable;
import java.util.*;
import org.apache.ogt.http.annotation.GuardedBy;
import org.apache.ogt.http.annotation.ThreadSafe;
import org.apache.ogt.http.client.CookieStore;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieIdentityComparator;
/**
* Default implementation of {@link CookieStore}
*
*
* @since 4.0
*/
@ThreadSafe
public class BasicCookieStore implements CookieStore, Serializable {
private static final long serialVersionUID = -7581093305228232025L;
@GuardedBy("this")
private final TreeSet<Cookie> cookies;
public BasicCookieStore() {
super();
this.cookies = new TreeSet<Cookie>(new CookieIdentityComparator());
}
/**
* Adds an {@link Cookie HTTP 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
*
* @see #addCookies(Cookie[])
*
*/
public synchronized void addCookie(Cookie cookie) {
if (cookie != null) {
// first remove any old cookie that is equivalent
cookies.remove(cookie);
if (!cookie.isExpired(new Date())) {
cookies.add(cookie);
}
}
}
/**
* Adds an array of {@link Cookie HTTP cookies}. Cookies are added individually and
* in the given array order. If any of the given cookies has already expired it will
* not be added, but existing values will still be removed.
*
* @param cookies the {@link Cookie cookies} to be added
*
* @see #addCookie(Cookie)
*
*/
public synchronized void addCookies(Cookie[] cookies) {
if (cookies != null) {
for (Cookie cooky : cookies) {
this.addCookie(cooky);
}
}
}
/**
* Returns an immutable array of {@link Cookie cookies} that this HTTP
* state currently contains.
*
* @return an array of {@link Cookie cookies}.
*/
public synchronized List<Cookie> getCookies() {
//create defensive copy so it won't be concurrently modified
return new ArrayList<Cookie>(cookies);
}
/**
* Removes all of {@link Cookie cookies} in this HTTP state
* that have expired by the specified {@link java.util.Date date}.
*
* @return true if any cookies were purged.
*
* @see Cookie#isExpired(Date)
*/
public synchronized boolean clearExpired(final Date date) {
if (date == null) {
return false;
}
boolean removed = false;
for (Iterator<Cookie> it = cookies.iterator(); it.hasNext();) {
if (it.next().isExpired(date)) {
it.remove();
removed = true;
}
}
return removed;
}
/**
* Clears all cookies.
*/
public synchronized void clear() {
cookies.clear();
}
@Override
public synchronized String toString() {
return cookies.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.impl.client;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
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.ProtocolException;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.annotation.NotThreadSafe;
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.AuthenticationException;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.client.AuthenticationHandler;
import org.apache.ogt.http.client.CredentialsProvider;
import org.apache.ogt.http.client.HttpRequestRetryHandler;
import org.apache.ogt.http.client.NonRepeatableRequestException;
import org.apache.ogt.http.client.RedirectException;
import org.apache.ogt.http.client.RedirectStrategy;
import org.apache.ogt.http.client.RequestDirector;
import org.apache.ogt.http.client.UserTokenHandler;
import org.apache.ogt.http.client.methods.AbortableHttpRequest;
import org.apache.ogt.http.client.methods.HttpUriRequest;
import org.apache.ogt.http.client.params.ClientPNames;
import org.apache.ogt.http.client.params.HttpClientParams;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.client.utils.URIUtils;
import org.apache.ogt.http.conn.BasicManagedEntity;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.ClientConnectionRequest;
import org.apache.ogt.http.conn.ConnectionKeepAliveStrategy;
import org.apache.ogt.http.conn.ManagedClientConnection;
import org.apache.ogt.http.conn.routing.BasicRouteDirector;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.conn.routing.HttpRouteDirector;
import org.apache.ogt.http.conn.routing.HttpRoutePlanner;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.entity.BufferedHttpEntity;
import org.apache.ogt.http.impl.conn.ConnectionShutdownException;
import org.apache.ogt.http.message.BasicHttpRequest;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.util.EntityUtils;
/**
* Default implementation of {@link RequestDirector}.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#PROTOCOL_VERSION}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#USE_EXPECT_CONTINUE}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#USER_AGENT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_LINGER}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_REUSEADDR}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#STALE_CONNECTION_CHECK}</li>
* <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#FORCED_ROUTE}</li>
* <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#LOCAL_ADDRESS}</li>
* <li>{@link org.apache.ogt.http.conn.params.ConnRoutePNames#DEFAULT_PROXY}</li>
* <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.auth.params.AuthPNames#CREDENTIAL_CHARSET}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#COOKIE_POLICY}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#HANDLE_AUTHENTICATION}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#HANDLE_REDIRECTS}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#MAX_REDIRECTS}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#ALLOW_CIRCULAR_REDIRECTS}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#VIRTUAL_HOST}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#DEFAULT_HOST}</li>
* <li>{@link org.apache.ogt.http.client.params.ClientPNames#DEFAULT_HEADERS}</li>
* </ul>
*
* @since 4.0
*/
@NotThreadSafe // e.g. managedConn
public class DefaultRequestDirector implements RequestDirector {
private final Log log;
/** The connection manager. */
protected final ClientConnectionManager connManager;
/** The route planner. */
protected final HttpRoutePlanner routePlanner;
/** The connection re-use strategy. */
protected final ConnectionReuseStrategy reuseStrategy;
/** The keep-alive duration strategy. */
protected final ConnectionKeepAliveStrategy keepAliveStrategy;
/** The request executor. */
protected final HttpRequestExecutor requestExec;
/** The HTTP protocol processor. */
protected final HttpProcessor httpProcessor;
/** The request retry handler. */
protected final HttpRequestRetryHandler retryHandler;
/** The redirect handler. */
@Deprecated
protected final org.apache.ogt.http.client.RedirectHandler redirectHandler = null;
/** The redirect strategy. */
protected final RedirectStrategy redirectStrategy;
/** The target authentication handler. */
protected final AuthenticationHandler targetAuthHandler;
/** The proxy authentication handler. */
protected final AuthenticationHandler proxyAuthHandler;
/** The user token handler. */
protected final UserTokenHandler userTokenHandler;
/** The HTTP parameters. */
protected final HttpParams params;
/** The currently allocated connection. */
protected ManagedClientConnection managedConn;
protected final AuthState targetAuthState;
protected final AuthState proxyAuthState;
private int execCount;
private int redirectCount;
private int maxRedirects;
private HttpHost virtualHost;
@Deprecated
public DefaultRequestDirector(
final HttpRequestExecutor requestExec,
final ClientConnectionManager conman,
final ConnectionReuseStrategy reustrat,
final ConnectionKeepAliveStrategy kastrat,
final HttpRoutePlanner rouplan,
final HttpProcessor httpProcessor,
final HttpRequestRetryHandler retryHandler,
final org.apache.ogt.http.client.RedirectHandler redirectHandler,
final AuthenticationHandler targetAuthHandler,
final AuthenticationHandler proxyAuthHandler,
final UserTokenHandler userTokenHandler,
final HttpParams params) {
this(LogFactory.getLog(DefaultRequestDirector.class),
requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler,
new DefaultRedirectStrategyAdaptor(redirectHandler),
targetAuthHandler, proxyAuthHandler, userTokenHandler, params);
}
/**
* @since 4.1
*/
public DefaultRequestDirector(
final Log log,
final HttpRequestExecutor requestExec,
final ClientConnectionManager conman,
final ConnectionReuseStrategy reustrat,
final ConnectionKeepAliveStrategy kastrat,
final HttpRoutePlanner rouplan,
final HttpProcessor httpProcessor,
final HttpRequestRetryHandler retryHandler,
final RedirectStrategy redirectStrategy,
final AuthenticationHandler targetAuthHandler,
final AuthenticationHandler proxyAuthHandler,
final UserTokenHandler userTokenHandler,
final HttpParams params) {
if (log == null) {
throw new IllegalArgumentException
("Log may not be null.");
}
if (requestExec == null) {
throw new IllegalArgumentException
("Request executor may not be null.");
}
if (conman == null) {
throw new IllegalArgumentException
("Client connection manager may not be null.");
}
if (reustrat == null) {
throw new IllegalArgumentException
("Connection reuse strategy may not be null.");
}
if (kastrat == null) {
throw new IllegalArgumentException
("Connection keep alive strategy may not be null.");
}
if (rouplan == null) {
throw new IllegalArgumentException
("Route planner may not be null.");
}
if (httpProcessor == null) {
throw new IllegalArgumentException
("HTTP protocol processor may not be null.");
}
if (retryHandler == null) {
throw new IllegalArgumentException
("HTTP request retry handler may not be null.");
}
if (redirectStrategy == null) {
throw new IllegalArgumentException
("Redirect strategy may not be null.");
}
if (targetAuthHandler == null) {
throw new IllegalArgumentException
("Target authentication handler may not be null.");
}
if (proxyAuthHandler == null) {
throw new IllegalArgumentException
("Proxy authentication handler may not be null.");
}
if (userTokenHandler == null) {
throw new IllegalArgumentException
("User token handler may not be null.");
}
if (params == null) {
throw new IllegalArgumentException
("HTTP parameters may not be null");
}
this.log = log;
this.requestExec = requestExec;
this.connManager = conman;
this.reuseStrategy = reustrat;
this.keepAliveStrategy = kastrat;
this.routePlanner = rouplan;
this.httpProcessor = httpProcessor;
this.retryHandler = retryHandler;
this.redirectStrategy = redirectStrategy;
this.targetAuthHandler = targetAuthHandler;
this.proxyAuthHandler = proxyAuthHandler;
this.userTokenHandler = userTokenHandler;
this.params = params;
this.managedConn = null;
this.execCount = 0;
this.redirectCount = 0;
this.maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100);
this.targetAuthState = new AuthState();
this.proxyAuthState = new AuthState();
} // constructor
private RequestWrapper wrapRequest(
final HttpRequest request) throws ProtocolException {
if (request instanceof HttpEntityEnclosingRequest) {
return new EntityEnclosingRequestWrapper(
(HttpEntityEnclosingRequest) request);
} else {
return new RequestWrapper(
request);
}
}
protected void rewriteRequestURI(
final RequestWrapper request,
final HttpRoute route) throws ProtocolException {
try {
URI uri = request.getURI();
if (route.getProxyHost() != null && !route.isTunnelled()) {
// Make sure the request URI is absolute
if (!uri.isAbsolute()) {
HttpHost target = route.getTargetHost();
uri = URIUtils.rewriteURI(uri, target);
request.setURI(uri);
}
} else {
// Make sure the request URI is relative
if (uri.isAbsolute()) {
uri = URIUtils.rewriteURI(uri, null);
request.setURI(uri);
}
}
} catch (URISyntaxException ex) {
throw new ProtocolException("Invalid URI: " +
request.getRequestLine().getUri(), ex);
}
}
// non-javadoc, see interface ClientRequestDirector
public HttpResponse execute(HttpHost target, HttpRequest request,
HttpContext context)
throws HttpException, IOException {
HttpRequest orig = request;
RequestWrapper origWrapper = wrapRequest(orig);
origWrapper.setParams(params);
HttpRoute origRoute = determineRoute(target, origWrapper, context);
virtualHost = (HttpHost) orig.getParams().getParameter(
ClientPNames.VIRTUAL_HOST);
RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);
long timeout = HttpConnectionParams.getConnectionTimeout(params);
boolean reuse = false;
boolean done = false;
try {
HttpResponse response = null;
while (!done) {
// In this loop, the RoutedRequest may be replaced by a
// followup request and route. The request and route passed
// in the method arguments will be replaced. The original
// request is still available in 'orig'.
RequestWrapper wrapper = roureq.getRequest();
HttpRoute route = roureq.getRoute();
response = null;
// See if we have a user token bound to the execution context
Object userToken = context.getAttribute(ClientContext.USER_TOKEN);
// Allocate connection if needed
if (managedConn == null) {
ClientConnectionRequest connRequest = connManager.requestConnection(
route, userToken);
if (orig instanceof AbortableHttpRequest) {
((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
}
try {
managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
} catch(InterruptedException interrupted) {
InterruptedIOException iox = new InterruptedIOException();
iox.initCause(interrupted);
throw iox;
}
if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
// validate connection
if (managedConn.isOpen()) {
this.log.debug("Stale connection check");
if (managedConn.isStale()) {
this.log.debug("Stale connection detected");
managedConn.close();
}
}
}
}
if (orig instanceof AbortableHttpRequest) {
((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
}
try {
tryConnect(roureq, context);
} catch (TunnelRefusedException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug(ex.getMessage());
}
response = ex.getResponse();
break;
}
// Reset headers on the request wrapper
wrapper.resetHeaders();
// Re-write request URI if needed
rewriteRequestURI(wrapper, route);
// Use virtual host if set
target = virtualHost;
if (target == null) {
target = route.getTargetHost();
}
HttpHost proxy = route.getProxyHost();
// Populate the execution context
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST,
target);
context.setAttribute(ExecutionContext.HTTP_PROXY_HOST,
proxy);
context.setAttribute(ExecutionContext.HTTP_CONNECTION,
managedConn);
context.setAttribute(ClientContext.TARGET_AUTH_STATE,
targetAuthState);
context.setAttribute(ClientContext.PROXY_AUTH_STATE,
proxyAuthState);
// Run request protocol interceptors
requestExec.preProcess(wrapper, httpProcessor, context);
response = tryExecute(roureq, context);
if (response == null) {
// Need to start over
continue;
}
// Run response protocol interceptors
response.setParams(params);
requestExec.postProcess(response, httpProcessor, context);
// The connection is in or can be brought to a re-usable state.
reuse = reuseStrategy.keepAlive(response, context);
if (reuse) {
// Set the idle duration of this connection
long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
if (this.log.isDebugEnabled()) {
String s;
if (duration > 0) {
s = "for " + duration + " " + TimeUnit.MILLISECONDS;
} else {
s = "indefinitely";
}
this.log.debug("Connection can be kept alive " + s);
}
managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);
}
RoutedRequest followup = handleResponse(roureq, response, context);
if (followup == null) {
done = true;
} else {
if (reuse) {
// Make sure the response body is fully consumed, if present
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
// entity consumed above is not an auto-release entity,
// need to mark the connection re-usable explicitly
managedConn.markReusable();
} else {
managedConn.close();
}
// check if we can use the same connection for the followup
if (!followup.getRoute().equals(roureq.getRoute())) {
releaseConnection();
}
roureq = followup;
}
if (managedConn != null && userToken == null) {
userToken = userTokenHandler.getUserToken(context);
context.setAttribute(ClientContext.USER_TOKEN, userToken);
if (userToken != null) {
managedConn.setState(userToken);
}
}
} // while not done
// check for entity, release connection if possible
if ((response == null) || (response.getEntity() == null) ||
!response.getEntity().isStreaming()) {
// connection not needed and (assumed to be) in re-usable state
if (reuse)
managedConn.markReusable();
releaseConnection();
} else {
// install an auto-release entity
HttpEntity entity = response.getEntity();
entity = new BasicManagedEntity(entity, managedConn, reuse);
response.setEntity(entity);
}
return response;
} catch (ConnectionShutdownException ex) {
InterruptedIOException ioex = new InterruptedIOException(
"Connection has been shut down");
ioex.initCause(ex);
throw ioex;
} catch (HttpException ex) {
abortConnection();
throw ex;
} catch (IOException ex) {
abortConnection();
throw ex;
} catch (RuntimeException ex) {
abortConnection();
throw ex;
}
} // execute
/**
* Establish connection either directly or through a tunnel and retry in case of
* a recoverable I/O failure
*/
private void tryConnect(
final RoutedRequest req, final HttpContext context) throws HttpException, IOException {
HttpRoute route = req.getRoute();
int connectCount = 0;
for (;;) {
// Increment connect count
connectCount++;
try {
if (!managedConn.isOpen()) {
managedConn.open(route, context, params);
} else {
managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
}
establishRoute(route, context);
break;
} catch (IOException ex) {
try {
managedConn.close();
} catch (IOException ignore) {
}
if (retryHandler.retryRequest(ex, connectCount, context)) {
if (this.log.isInfoEnabled()) {
this.log.info("I/O exception ("+ ex.getClass().getName() +
") caught when connecting to the target host: "
+ ex.getMessage());
}
if (this.log.isDebugEnabled()) {
this.log.debug(ex.getMessage(), ex);
}
this.log.info("Retrying connect");
} else {
throw ex;
}
}
}
}
/**
* Execute request and retry in case of a recoverable I/O failure
*/
private HttpResponse tryExecute(
final RoutedRequest req, final HttpContext context) throws HttpException, IOException {
RequestWrapper wrapper = req.getRequest();
HttpRoute route = req.getRoute();
HttpResponse response = null;
Exception retryReason = null;
for (;;) {
// Increment total exec count (with redirects)
execCount++;
// Increment exec count for this particular request
wrapper.incrementExecCount();
if (!wrapper.isRepeatable()) {
this.log.debug("Cannot retry non-repeatable request");
if (retryReason != null) {
throw new NonRepeatableRequestException("Cannot retry request " +
"with a non-repeatable request entity. The cause lists the " +
"reason the original request failed.", retryReason);
} else {
throw new NonRepeatableRequestException("Cannot retry request " +
"with a non-repeatable request entity.");
}
}
try {
if (!managedConn.isOpen()) {
// If we have a direct route to the target host
// just re-open connection and re-try the request
if (!route.isTunnelled()) {
this.log.debug("Reopening the direct connection.");
managedConn.open(route, context, params);
} else {
// otherwise give up
this.log.debug("Proxied connection. Need to start over.");
break;
}
}
if (this.log.isDebugEnabled()) {
this.log.debug("Attempt " + execCount + " to execute request");
}
response = requestExec.execute(wrapper, managedConn, context);
break;
} catch (IOException ex) {
this.log.debug("Closing the connection.");
try {
managedConn.close();
} catch (IOException ignore) {
}
if (retryHandler.retryRequest(ex, wrapper.getExecCount(), context)) {
if (this.log.isInfoEnabled()) {
this.log.info("I/O exception ("+ ex.getClass().getName() +
") caught when processing request: "
+ ex.getMessage());
}
if (this.log.isDebugEnabled()) {
this.log.debug(ex.getMessage(), ex);
}
this.log.info("Retrying request");
retryReason = ex;
} else {
throw ex;
}
}
}
return response;
}
/**
* Returns the connection back to the connection manager
* and prepares for retrieving a new connection during
* the next request.
*/
protected void releaseConnection() {
// Release the connection through the ManagedConnection instead of the
// ConnectionManager directly. This lets the connection control how
// it is released.
try {
managedConn.releaseConnection();
} catch(IOException ignored) {
this.log.debug("IOException releasing connection", ignored);
}
managedConn = null;
}
/**
* Determines the route for a request.
* Called by {@link #execute}
* to determine the route for either the original or a followup request.
*
* @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,
* never <code>null</code>
*
* @return the route the request should take
*
* @throws HttpException in case of a problem
*/
protected HttpRoute determineRoute(HttpHost target,
HttpRequest request,
HttpContext context)
throws HttpException {
if (target == null) {
target = (HttpHost) request.getParams().getParameter(
ClientPNames.DEFAULT_HOST);
}
if (target == null) {
throw new IllegalStateException
("Target host must not be null, or set in parameters.");
}
return this.routePlanner.determineRoute(target, request, context);
}
/**
* Establishes the target route.
*
* @param route the route to establish
* @param context the context for the request execution
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
protected void establishRoute(HttpRoute route, HttpContext context)
throws HttpException, IOException {
HttpRouteDirector rowdy = new BasicRouteDirector();
int step;
do {
HttpRoute fact = managedConn.getRoute();
step = rowdy.nextStep(route, fact);
switch (step) {
case HttpRouteDirector.CONNECT_TARGET:
case HttpRouteDirector.CONNECT_PROXY:
managedConn.open(route, context, this.params);
break;
case HttpRouteDirector.TUNNEL_TARGET: {
boolean secure = createTunnelToTarget(route, context);
this.log.debug("Tunnel to target created.");
managedConn.tunnelTarget(secure, this.params);
} break;
case HttpRouteDirector.TUNNEL_PROXY: {
// The most simple example for this case is a proxy chain
// of two proxies, where P1 must be tunnelled to P2.
// route: Source -> P1 -> P2 -> Target (3 hops)
// fact: Source -> P1 -> Target (2 hops)
final int hop = fact.getHopCount()-1; // the hop to establish
boolean secure = createTunnelToProxy(route, hop, context);
this.log.debug("Tunnel to proxy created.");
managedConn.tunnelProxy(route.getHopTarget(hop),
secure, this.params);
} break;
case HttpRouteDirector.LAYER_PROTOCOL:
managedConn.layerProtocol(context, this.params);
break;
case HttpRouteDirector.UNREACHABLE:
throw new HttpException("Unable to establish route: " +
"planned = " + route + "; current = " + fact);
case HttpRouteDirector.COMPLETE:
// do nothing
break;
default:
throw new IllegalStateException("Unknown step indicator "
+ step + " from RouteDirector.");
}
} while (step > HttpRouteDirector.COMPLETE);
} // establishConnection
/**
* Creates a tunnel to the target server.
* The connection must be established to the (last) proxy.
* A CONNECT request for tunnelling through the proxy will
* be created and sent, the response received and checked.
* This method does <i>not</i> update the connection with
* information about the tunnel, that is left to the caller.
*
* @param route the route to establish
* @param context the context for request execution
*
* @return <code>true</code> if the tunnelled route is secure,
* <code>false</code> otherwise.
* The implementation here always returns <code>false</code>,
* but derived classes may override.
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
protected boolean createTunnelToTarget(HttpRoute route,
HttpContext context)
throws HttpException, IOException {
HttpHost proxy = route.getProxyHost();
HttpHost target = route.getTargetHost();
HttpResponse response = null;
boolean done = false;
while (!done) {
done = true;
if (!this.managedConn.isOpen()) {
this.managedConn.open(route, context, this.params);
}
HttpRequest connect = createConnectRequest(route, context);
connect.setParams(this.params);
// Populate the execution context
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST,
target);
context.setAttribute(ExecutionContext.HTTP_PROXY_HOST,
proxy);
context.setAttribute(ExecutionContext.HTTP_CONNECTION,
managedConn);
context.setAttribute(ClientContext.TARGET_AUTH_STATE,
targetAuthState);
context.setAttribute(ClientContext.PROXY_AUTH_STATE,
proxyAuthState);
context.setAttribute(ExecutionContext.HTTP_REQUEST,
connect);
this.requestExec.preProcess(connect, this.httpProcessor, context);
response = this.requestExec.execute(connect, this.managedConn, context);
response.setParams(this.params);
this.requestExec.postProcess(response, this.httpProcessor, context);
int status = response.getStatusLine().getStatusCode();
if (status < 200) {
throw new HttpException("Unexpected response to CONNECT request: " +
response.getStatusLine());
}
CredentialsProvider credsProvider = (CredentialsProvider)
context.getAttribute(ClientContext.CREDS_PROVIDER);
if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
this.log.debug("Proxy requested authentication");
Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(
response, context);
try {
processChallenges(
challenges, this.proxyAuthState, this.proxyAuthHandler,
response, context);
} catch (AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication error: " + ex.getMessage());
break;
}
}
updateAuthState(this.proxyAuthState, proxy, credsProvider);
if (this.proxyAuthState.getCredentials() != null) {
done = false;
// Retry request
if (this.reuseStrategy.keepAlive(response, context)) {
this.log.debug("Connection kept alive");
// Consume response content
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
} else {
this.managedConn.close();
}
}
} else {
// Reset proxy auth scope
this.proxyAuthState.setAuthScope(null);
}
}
}
int status = response.getStatusLine().getStatusCode(); // can't be null
if (status > 299) {
// Buffer response content
HttpEntity entity = response.getEntity();
if (entity != null) {
response.setEntity(new BufferedHttpEntity(entity));
}
this.managedConn.close();
throw new TunnelRefusedException("CONNECT refused by proxy: " +
response.getStatusLine(), response);
}
this.managedConn.markReusable();
// How to decide on security of the tunnelled connection?
// The socket factory knows only about the segment to the proxy.
// Even if that is secure, the hop to the target may be insecure.
// Leave it to derived classes, consider insecure by default here.
return false;
} // createTunnelToTarget
/**
* Creates a tunnel to an intermediate proxy.
* This method is <i>not</i> implemented in this class.
* It just throws an exception here.
*
* @param route the route to establish
* @param hop the hop in the route to establish now.
* <code>route.getHopTarget(hop)</code>
* will return the proxy to tunnel to.
* @param context the context for request execution
*
* @return <code>true</code> if the partially tunnelled connection
* is secure, <code>false</code> otherwise.
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
protected boolean createTunnelToProxy(HttpRoute route, int hop,
HttpContext context)
throws HttpException, IOException {
// Have a look at createTunnelToTarget and replicate the parts
// you need in a custom derived class. If your proxies don't require
// authentication, it is not too hard. But for the stock version of
// HttpClient, we cannot make such simplifying assumptions and would
// have to include proxy authentication code. The HttpComponents team
// is currently not in a position to support rarely used code of this
// complexity. Feel free to submit patches that refactor the code in
// createTunnelToTarget to facilitate re-use for proxy tunnelling.
throw new HttpException("Proxy chains are not supported.");
}
/**
* Creates the CONNECT request for tunnelling.
* Called by {@link #createTunnelToTarget createTunnelToTarget}.
*
* @param route the route to establish
* @param context the context for request execution
*
* @return the CONNECT request for tunnelling
*/
protected HttpRequest createConnectRequest(HttpRoute route,
HttpContext context) {
// see RFC 2817, section 5.2 and
// INTERNET-DRAFT: Tunneling TCP based protocols through
// Web proxy servers
HttpHost target = route.getTargetHost();
String host = target.getHostName();
int port = target.getPort();
if (port < 0) {
Scheme scheme = connManager.getSchemeRegistry().
getScheme(target.getSchemeName());
port = scheme.getDefaultPort();
}
StringBuilder buffer = new StringBuilder(host.length() + 6);
buffer.append(host);
buffer.append(':');
buffer.append(Integer.toString(port));
String authority = buffer.toString();
ProtocolVersion ver = HttpProtocolParams.getVersion(params);
HttpRequest req = new BasicHttpRequest
("CONNECT", authority, ver);
return req;
}
/**
* Analyzes a response to check need for a followup.
*
* @param roureq the request and route.
* @param response the response to analayze
* @param context the context used for the current request execution
*
* @return the followup request and route if there is a followup, or
* <code>null</code> if the response should be returned as is
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
protected RoutedRequest handleResponse(RoutedRequest roureq,
HttpResponse response,
HttpContext context)
throws HttpException, IOException {
HttpRoute route = roureq.getRoute();
RequestWrapper request = roureq.getRequest();
HttpParams params = request.getParams();
if (HttpClientParams.isRedirecting(params) &&
this.redirectStrategy.isRedirected(request, response, context)) {
if (redirectCount >= maxRedirects) {
throw new RedirectException("Maximum redirects ("
+ maxRedirects + ") exceeded");
}
redirectCount++;
// Virtual host cannot be used any longer
virtualHost = null;
HttpUriRequest redirect = redirectStrategy.getRedirect(request, response, context);
HttpRequest orig = request.getOriginal();
redirect.setHeaders(orig.getAllHeaders());
URI uri = redirect.getURI();
if (uri.getHost() == null) {
throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
}
HttpHost newTarget = new HttpHost(
uri.getHost(),
uri.getPort(),
uri.getScheme());
// Unset auth scope
targetAuthState.setAuthScope(null);
proxyAuthState.setAuthScope(null);
// Invalidate auth states if redirecting to another host
if (!route.getTargetHost().equals(newTarget)) {
targetAuthState.invalidate();
AuthScheme authScheme = proxyAuthState.getAuthScheme();
if (authScheme != null && authScheme.isConnectionBased()) {
proxyAuthState.invalidate();
}
}
RequestWrapper wrapper = wrapRequest(redirect);
wrapper.setParams(params);
HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);
if (this.log.isDebugEnabled()) {
this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
}
return newRequest;
}
CredentialsProvider credsProvider = (CredentialsProvider)
context.getAttribute(ClientContext.CREDS_PROVIDER);
if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
if (this.targetAuthHandler.isAuthenticationRequested(response, context)) {
HttpHost target = (HttpHost)
context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (target == null) {
target = route.getTargetHost();
}
this.log.debug("Target requested authentication");
Map<String, Header> challenges = this.targetAuthHandler.getChallenges(
response, context);
try {
processChallenges(challenges,
this.targetAuthState, this.targetAuthHandler,
response, context);
} catch (AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication error: " + ex.getMessage());
return null;
}
}
updateAuthState(this.targetAuthState, target, credsProvider);
if (this.targetAuthState.getCredentials() != null) {
// Re-try the same request via the same route
return roureq;
} else {
return null;
}
} else {
// Reset target auth scope
this.targetAuthState.setAuthScope(null);
}
if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
HttpHost proxy = route.getProxyHost();
this.log.debug("Proxy requested authentication");
Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(
response, context);
try {
processChallenges(challenges,
this.proxyAuthState, this.proxyAuthHandler,
response, context);
} catch (AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication error: " + ex.getMessage());
return null;
}
}
updateAuthState(this.proxyAuthState, proxy, credsProvider);
if (this.proxyAuthState.getCredentials() != null) {
// Re-try the same request via the same route
return roureq;
} else {
return null;
}
} else {
// Reset proxy auth scope
this.proxyAuthState.setAuthScope(null);
}
}
return null;
} // handleResponse
/**
* Shuts down the connection.
* This method is called from a <code>catch</code> block in
* {@link #execute execute} during exception handling.
*/
private void abortConnection() {
ManagedClientConnection mcc = managedConn;
if (mcc != null) {
// we got here as the result of an exception
// no response will be returned, release the connection
managedConn = null;
try {
mcc.abortConnection();
} catch (IOException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug(ex.getMessage(), ex);
}
}
// ensure the connection manager properly releases this connection
try {
mcc.releaseConnection();
} catch(IOException ignored) {
this.log.debug("Error releasing connection", ignored);
}
}
} // abortConnection
private void processChallenges(
final Map<String, Header> challenges,
final AuthState authState,
final AuthenticationHandler authHandler,
final HttpResponse response,
final HttpContext context)
throws MalformedChallengeException, AuthenticationException {
AuthScheme authScheme = authState.getAuthScheme();
if (authScheme == null) {
// Authentication not attempted before
authScheme = authHandler.selectScheme(challenges, response, context);
authState.setAuthScheme(authScheme);
}
String id = authScheme.getSchemeName();
Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
if (challenge == null) {
throw new AuthenticationException(id +
" authorization challenge expected, but not found");
}
authScheme.processChallenge(challenge);
this.log.debug("Authorization challenge processed");
}
private void updateAuthState(
final AuthState authState,
final HttpHost host,
final CredentialsProvider credsProvider) {
if (!authState.isValid()) {
return;
}
String hostname = host.getHostName();
int port = host.getPort();
if (port < 0) {
Scheme scheme = connManager.getSchemeRegistry().getScheme(host);
port = scheme.getDefaultPort();
}
AuthScheme authScheme = authState.getAuthScheme();
AuthScope authScope = new AuthScope(
hostname,
port,
authScheme.getRealm(),
authScheme.getSchemeName());
if (this.log.isDebugEnabled()) {
this.log.debug("Authentication scope: " + authScope);
}
Credentials creds = authState.getCredentials();
if (creds == null) {
creds = credsProvider.getCredentials(authScope);
if (this.log.isDebugEnabled()) {
if (creds != null) {
this.log.debug("Found credentials");
} else {
this.log.debug("Credentials not found");
}
}
} else {
if (authScheme.isComplete()) {
this.log.debug("Authentication failed");
creds = null;
}
}
authState.setAuthScope(authScope);
authState.setCredentials(creds);
}
} // class DefaultClientRequestDirector
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import java.net.URI;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.client.RedirectStrategy;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.methods.HttpHead;
import org.apache.ogt.http.client.methods.HttpUriRequest;
import org.apache.ogt.http.protocol.HttpContext;
/**
* @since 4.1
*/
@Immutable
@Deprecated
class DefaultRedirectStrategyAdaptor implements RedirectStrategy {
private final org.apache.ogt.http.client.RedirectHandler handler;
@Deprecated
public DefaultRedirectStrategyAdaptor(final org.apache.ogt.http.client.RedirectHandler handler) {
super();
this.handler = handler;
}
public boolean isRedirected(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws ProtocolException {
return this.handler.isRedirectRequested(response, context);
}
public HttpUriRequest getRedirect(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws ProtocolException {
URI uri = this.handler.getLocationURI(response, context);
String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
return new HttpHead(uri);
} else {
return new HttpGet(uri);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.ogt.http.annotation.NotThreadSafe;
/**
* This class represents a collection of {@link URI}s used as redirect locations.
*
* @since 4.0
*/
@NotThreadSafe // HashSet is not synch.
public class RedirectLocations {
private final Set<URI> unique;
private final List<URI> all;
public RedirectLocations() {
super();
this.unique = new HashSet<URI>();
this.all = new ArrayList<URI>();
}
/**
* Test if the URI is present in the collection.
*/
public boolean contains(final URI uri) {
return this.unique.contains(uri);
}
/**
* Adds a new URI to the collection.
*/
public void add(final URI uri) {
this.unique.add(uri);
this.all.add(uri);
}
/**
* Removes a URI from the collection.
*/
public boolean remove(final URI uri) {
boolean removed = this.unique.remove(uri);
if (removed) {
Iterator<URI> it = this.all.iterator();
while (it.hasNext()) {
URI current = it.next();
if (current.equals(uri)) {
it.remove();
}
}
}
return removed;
}
/**
* Returns all redirect {@link URI}s in the order they were added to the collection.
*
* @return list of all URIs
*
* @since 4.1
*/
public List<URI> getAll() {
return new ArrayList<URI>(this.all);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import java.util.List;
import java.util.Map;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.auth.params.AuthPNames;
import org.apache.ogt.http.client.AuthenticationHandler;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Default {@link AuthenticationHandler} implementation for proxy host
* authentication.
*
* @since 4.0
*/
@Immutable
public class DefaultProxyAuthenticationHandler extends AbstractAuthenticationHandler {
public DefaultProxyAuthenticationHandler() {
super();
}
public boolean isAuthenticationRequested(
final HttpResponse response,
final HttpContext context) {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
int status = response.getStatusLine().getStatusCode();
return status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED;
}
public Map<String, Header> getChallenges(
final HttpResponse response,
final HttpContext context) throws MalformedChallengeException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
Header[] headers = response.getHeaders(AUTH.PROXY_AUTH);
return parseChallenges(headers);
}
@Override
protected List<String> getAuthPreferences(
final HttpResponse response,
final HttpContext context) {
@SuppressWarnings("unchecked")
List<String> authpref = (List<String>) response.getParams().getParameter(
AuthPNames.PROXY_AUTH_PREF);
if (authpref != null) {
return authpref;
} else {
return super.getAuthPreferences(response, context);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.URI;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.annotation.GuardedBy;
import org.apache.ogt.http.annotation.ThreadSafe;
import org.apache.ogt.http.auth.AuthSchemeRegistry;
import org.apache.ogt.http.client.AuthenticationHandler;
import org.apache.ogt.http.client.ClientProtocolException;
import org.apache.ogt.http.client.CookieStore;
import org.apache.ogt.http.client.CredentialsProvider;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.HttpRequestRetryHandler;
import org.apache.ogt.http.client.RedirectHandler;
import org.apache.ogt.http.client.RedirectStrategy;
import org.apache.ogt.http.client.RequestDirector;
import org.apache.ogt.http.client.ResponseHandler;
import org.apache.ogt.http.client.UserTokenHandler;
import org.apache.ogt.http.client.methods.HttpUriRequest;
import org.apache.ogt.http.client.params.AuthPolicy;
import org.apache.ogt.http.client.params.ClientPNames;
import org.apache.ogt.http.client.params.CookiePolicy;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.client.utils.URIUtils;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.ClientConnectionManagerFactory;
import org.apache.ogt.http.conn.ConnectionKeepAliveStrategy;
import org.apache.ogt.http.conn.routing.HttpRoutePlanner;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.cookie.CookieSpecRegistry;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.auth.BasicSchemeFactory;
import org.apache.ogt.http.impl.auth.DigestSchemeFactory;
import org.apache.ogt.http.impl.auth.NTLMSchemeFactory;
import org.apache.ogt.http.impl.auth.NegotiateSchemeFactory;
import org.apache.ogt.http.impl.conn.DefaultHttpRoutePlanner;
import org.apache.ogt.http.impl.conn.SchemeRegistryFactory;
import org.apache.ogt.http.impl.conn.SingleClientConnManager;
import org.apache.ogt.http.impl.cookie.BestMatchSpecFactory;
import org.apache.ogt.http.impl.cookie.BrowserCompatSpecFactory;
import org.apache.ogt.http.impl.cookie.IgnoreSpecFactory;
import org.apache.ogt.http.impl.cookie.NetscapeDraftSpecFactory;
import org.apache.ogt.http.impl.cookie.RFC2109SpecFactory;
import org.apache.ogt.http.impl.cookie.RFC2965SpecFactory;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.BasicHttpProcessor;
import org.apache.ogt.http.protocol.DefaultedHttpContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.util.EntityUtils;
/**
* Base class for {@link HttpClient} implementations. This class acts as
* a facade to a number of special purpose handler or strategy
* implementations responsible for handling of a particular aspect of
* the HTTP protocol such as redirect or authentication handling or
* making decision about connection persistence and keep alive duration.
* This enables the users to selectively replace default implementation
* of those aspects with custom, application specific ones. This class
* also provides factory methods to instantiate those objects:
* <ul>
* <li>{@link HttpRequestExecutor}</li> object used to transmit messages
* over HTTP connections. The {@link #createRequestExecutor()} must be
* implemented by concrete super classes to instantiate this object.
* <li>{@link BasicHttpProcessor}</li> object to manage a list of protocol
* interceptors and apply cross-cutting protocol logic to all incoming
* and outgoing HTTP messages. The {@link #createHttpProcessor()} must be
* implemented by concrete super classes to instantiate this object.
* <li>{@link HttpRequestRetryHandler}</li> object used to decide whether
* or not a failed HTTP request is safe to retry automatically.
* The {@link #createHttpRequestRetryHandler()} must be
* implemented by concrete super classes to instantiate this object.
* <li>{@link ClientConnectionManager}</li> object used to manage
* persistent HTTP connections.
* <li>{@link ConnectionReuseStrategy}</li> object used to decide whether
* or not a HTTP connection can be kept alive and re-used for subsequent
* HTTP requests. The {@link #createConnectionReuseStrategy()} must be
* implemented by concrete super classes to instantiate this object.
* <li>{@link ConnectionKeepAliveStrategy}</li> object used to decide how
* long a persistent HTTP connection can be kept alive.
* The {@link #createConnectionKeepAliveStrategy()} must be
* implemented by concrete super classes to instantiate this object.
* <li>{@link CookieSpecRegistry}</li> object used to maintain a list of
* supported cookie specifications.
* The {@link #createCookieSpecRegistry()} must be implemented by concrete
* super classes to instantiate this object.
* <li>{@link CookieStore}</li> object used to maintain a collection of
* cookies. The {@link #createCookieStore()} must be implemented by
* concrete super classes to instantiate this object.
* <li>{@link AuthSchemeRegistry}</li> object used to maintain a list of
* supported authentication schemes.
* The {@link #createAuthSchemeRegistry()} must be implemented by concrete
* super classes to instantiate this object.
* <li>{@link CredentialsProvider}</li> object used to maintain
* a collection user credentials. The {@link #createCredentialsProvider()}
* must be implemented by concrete super classes to instantiate
* this object.
* <li>{@link AuthenticationHandler}</li> object used to authenticate
* against the target host.
* The {@link #createTargetAuthenticationHandler()} must be implemented
* by concrete super classes to instantiate this object.
* <li>{@link AuthenticationHandler}</li> object used to authenticate
* against the proxy host.
* The {@link #createProxyAuthenticationHandler()} must be implemented
* by concrete super classes to instantiate this object.
* <li>{@link HttpRoutePlanner}</li> object used to calculate a route
* for establishing a connection to the target host. The route
* may involve multiple intermediate hops.
* The {@link #createHttpRoutePlanner()} must be implemented
* by concrete super classes to instantiate this object.
* <li>{@link RedirectStrategy}</li> object used to determine if an HTTP
* request should be redirected to a new location in response to an HTTP
* response received from the target server.
* <li>{@link UserTokenHandler}</li> object used to determine if the
* execution context is user identity specific.
* The {@link #createUserTokenHandler()} must be implemented by
* concrete super classes to instantiate this object.
* </ul>
* <p>
* This class also maintains a list of protocol interceptors intended
* for processing outgoing requests and incoming responses and provides
* methods for managing those interceptors. New protocol interceptors can be
* introduced to the protocol processor chain or removed from it if needed.
* Internally protocol interceptors are stored in a simple
* {@link java.util.ArrayList}. They are executed in the same natural order
* as they are added to the list.
* <p>
* AbstractHttpClient is thread safe. It is recommended that the same
* instance of this class is reused for multiple request executions.
* When an instance of DefaultHttpClient is no longer needed and is about
* to go out of scope the connection manager associated with it must be
* shut down by calling {@link ClientConnectionManager#shutdown()}!
*
* @since 4.0
*/
@ThreadSafe
@SuppressWarnings("deprecation")
public abstract class AbstractHttpClient implements HttpClient {
private final Log log = LogFactory.getLog(getClass());
/** The parameters. */
@GuardedBy("this")
private HttpParams defaultParams;
/** The request executor. */
@GuardedBy("this")
private HttpRequestExecutor requestExec;
/** The connection manager. */
@GuardedBy("this")
private ClientConnectionManager connManager;
/** The connection re-use strategy. */
@GuardedBy("this")
private ConnectionReuseStrategy reuseStrategy;
/** The connection keep-alive strategy. */
@GuardedBy("this")
private ConnectionKeepAliveStrategy keepAliveStrategy;
/** The cookie spec registry. */
@GuardedBy("this")
private CookieSpecRegistry supportedCookieSpecs;
/** The authentication scheme registry. */
@GuardedBy("this")
private AuthSchemeRegistry supportedAuthSchemes;
/** The HTTP protocol processor and its immutable copy. */
@GuardedBy("this")
private BasicHttpProcessor mutableProcessor;
@GuardedBy("this")
private ImmutableHttpProcessor protocolProcessor;
/** The request retry handler. */
@GuardedBy("this")
private HttpRequestRetryHandler retryHandler;
/** The redirect handler. */
@GuardedBy("this")
private RedirectStrategy redirectStrategy;
/** The target authentication handler. */
@GuardedBy("this")
private AuthenticationHandler targetAuthHandler;
/** The proxy authentication handler. */
@GuardedBy("this")
private AuthenticationHandler proxyAuthHandler;
/** The cookie store. */
@GuardedBy("this")
private CookieStore cookieStore;
/** The credentials provider. */
@GuardedBy("this")
private CredentialsProvider credsProvider;
/** The route planner. */
@GuardedBy("this")
private HttpRoutePlanner routePlanner;
/** The user token handler. */
@GuardedBy("this")
private UserTokenHandler userTokenHandler;
/**
* Creates a new HTTP client.
*
* @param conman the connection manager
* @param params the parameters
*/
protected AbstractHttpClient(
final ClientConnectionManager conman,
final HttpParams params) {
defaultParams = params;
connManager = conman;
} // constructor
protected abstract HttpParams createHttpParams();
protected abstract BasicHttpProcessor createHttpProcessor();
protected HttpContext createHttpContext() {
HttpContext context = new BasicHttpContext();
context.setAttribute(
ClientContext.SCHEME_REGISTRY,
getConnectionManager().getSchemeRegistry());
context.setAttribute(
ClientContext.AUTHSCHEME_REGISTRY,
getAuthSchemes());
context.setAttribute(
ClientContext.COOKIESPEC_REGISTRY,
getCookieSpecs());
context.setAttribute(
ClientContext.COOKIE_STORE,
getCookieStore());
context.setAttribute(
ClientContext.CREDS_PROVIDER,
getCredentialsProvider());
return context;
}
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = SchemeRegistryFactory.createDefault();
ClientConnectionManager connManager = null;
HttpParams params = getParams();
ClientConnectionManagerFactory factory = null;
String className = (String) params.getParameter(
ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME);
if (className != null) {
try {
Class<?> clazz = Class.forName(className);
factory = (ClientConnectionManagerFactory) clazz.newInstance();
} catch (ClassNotFoundException ex) {
throw new IllegalStateException("Invalid class name: " + className);
} catch (IllegalAccessException ex) {
throw new IllegalAccessError(ex.getMessage());
} catch (InstantiationException ex) {
throw new InstantiationError(ex.getMessage());
}
}
if (factory != null) {
connManager = factory.newInstance(params, registry);
} else {
connManager = new SingleClientConnManager(registry);
}
return connManager;
}
protected AuthSchemeRegistry createAuthSchemeRegistry() {
AuthSchemeRegistry registry = new AuthSchemeRegistry();
registry.register(
AuthPolicy.BASIC,
new BasicSchemeFactory());
registry.register(
AuthPolicy.DIGEST,
new DigestSchemeFactory());
registry.register(
AuthPolicy.NTLM,
new NTLMSchemeFactory());
registry.register(
AuthPolicy.SPNEGO,
new NegotiateSchemeFactory());
return registry;
}
protected CookieSpecRegistry createCookieSpecRegistry() {
CookieSpecRegistry registry = new CookieSpecRegistry();
registry.register(
CookiePolicy.BEST_MATCH,
new BestMatchSpecFactory());
registry.register(
CookiePolicy.BROWSER_COMPATIBILITY,
new BrowserCompatSpecFactory());
registry.register(
CookiePolicy.NETSCAPE,
new NetscapeDraftSpecFactory());
registry.register(
CookiePolicy.RFC_2109,
new RFC2109SpecFactory());
registry.register(
CookiePolicy.RFC_2965,
new RFC2965SpecFactory());
registry.register(
CookiePolicy.IGNORE_COOKIES,
new IgnoreSpecFactory());
return registry;
}
protected HttpRequestExecutor createRequestExecutor() {
return new HttpRequestExecutor();
}
protected ConnectionReuseStrategy createConnectionReuseStrategy() {
return new DefaultConnectionReuseStrategy();
}
protected ConnectionKeepAliveStrategy createConnectionKeepAliveStrategy() {
return new DefaultConnectionKeepAliveStrategy();
}
protected HttpRequestRetryHandler createHttpRequestRetryHandler() {
return new DefaultHttpRequestRetryHandler();
}
@Deprecated
protected RedirectHandler createRedirectHandler() {
return new DefaultRedirectHandler();
}
protected AuthenticationHandler createTargetAuthenticationHandler() {
return new DefaultTargetAuthenticationHandler();
}
protected AuthenticationHandler createProxyAuthenticationHandler() {
return new DefaultProxyAuthenticationHandler();
}
protected CookieStore createCookieStore() {
return new BasicCookieStore();
}
protected CredentialsProvider createCredentialsProvider() {
return new BasicCredentialsProvider();
}
protected HttpRoutePlanner createHttpRoutePlanner() {
return new DefaultHttpRoutePlanner(getConnectionManager().getSchemeRegistry());
}
protected UserTokenHandler createUserTokenHandler() {
return new DefaultUserTokenHandler();
}
// non-javadoc, see interface HttpClient
public synchronized final HttpParams getParams() {
if (defaultParams == null) {
defaultParams = createHttpParams();
}
return defaultParams;
}
/**
* Replaces the parameters.
* The implementation here does not update parameters of dependent objects.
*
* @param params the new default parameters
*/
public synchronized void setParams(HttpParams params) {
defaultParams = params;
}
public synchronized final ClientConnectionManager getConnectionManager() {
if (connManager == null) {
connManager = createClientConnectionManager();
}
return connManager;
}
public synchronized final HttpRequestExecutor getRequestExecutor() {
if (requestExec == null) {
requestExec = createRequestExecutor();
}
return requestExec;
}
public synchronized final AuthSchemeRegistry getAuthSchemes() {
if (supportedAuthSchemes == null) {
supportedAuthSchemes = createAuthSchemeRegistry();
}
return supportedAuthSchemes;
}
public synchronized void setAuthSchemes(final AuthSchemeRegistry authSchemeRegistry) {
supportedAuthSchemes = authSchemeRegistry;
}
public synchronized final CookieSpecRegistry getCookieSpecs() {
if (supportedCookieSpecs == null) {
supportedCookieSpecs = createCookieSpecRegistry();
}
return supportedCookieSpecs;
}
public synchronized void setCookieSpecs(final CookieSpecRegistry cookieSpecRegistry) {
supportedCookieSpecs = cookieSpecRegistry;
}
public synchronized final ConnectionReuseStrategy getConnectionReuseStrategy() {
if (reuseStrategy == null) {
reuseStrategy = createConnectionReuseStrategy();
}
return reuseStrategy;
}
public synchronized void setReuseStrategy(final ConnectionReuseStrategy reuseStrategy) {
this.reuseStrategy = reuseStrategy;
}
public synchronized final ConnectionKeepAliveStrategy getConnectionKeepAliveStrategy() {
if (keepAliveStrategy == null) {
keepAliveStrategy = createConnectionKeepAliveStrategy();
}
return keepAliveStrategy;
}
public synchronized void setKeepAliveStrategy(final ConnectionKeepAliveStrategy keepAliveStrategy) {
this.keepAliveStrategy = keepAliveStrategy;
}
public synchronized final HttpRequestRetryHandler getHttpRequestRetryHandler() {
if (retryHandler == null) {
retryHandler = createHttpRequestRetryHandler();
}
return retryHandler;
}
public synchronized void setHttpRequestRetryHandler(final HttpRequestRetryHandler retryHandler) {
this.retryHandler = retryHandler;
}
@Deprecated
public synchronized final RedirectHandler getRedirectHandler() {
return createRedirectHandler();
}
@Deprecated
public synchronized void setRedirectHandler(final RedirectHandler redirectHandler) {
this.redirectStrategy = new DefaultRedirectStrategyAdaptor(redirectHandler);
}
/**
* @since 4.1
*/
public synchronized final RedirectStrategy getRedirectStrategy() {
if (redirectStrategy == null) {
redirectStrategy = new DefaultRedirectStrategy();
}
return redirectStrategy;
}
/**
* @since 4.1
*/
public synchronized void setRedirectStrategy(final RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
public synchronized final AuthenticationHandler getTargetAuthenticationHandler() {
if (targetAuthHandler == null) {
targetAuthHandler = createTargetAuthenticationHandler();
}
return targetAuthHandler;
}
public synchronized void setTargetAuthenticationHandler(
final AuthenticationHandler targetAuthHandler) {
this.targetAuthHandler = targetAuthHandler;
}
public synchronized final AuthenticationHandler getProxyAuthenticationHandler() {
if (proxyAuthHandler == null) {
proxyAuthHandler = createProxyAuthenticationHandler();
}
return proxyAuthHandler;
}
public synchronized void setProxyAuthenticationHandler(
final AuthenticationHandler proxyAuthHandler) {
this.proxyAuthHandler = proxyAuthHandler;
}
public synchronized final CookieStore getCookieStore() {
if (cookieStore == null) {
cookieStore = createCookieStore();
}
return cookieStore;
}
public synchronized void setCookieStore(final CookieStore cookieStore) {
this.cookieStore = cookieStore;
}
public synchronized final CredentialsProvider getCredentialsProvider() {
if (credsProvider == null) {
credsProvider = createCredentialsProvider();
}
return credsProvider;
}
public synchronized void setCredentialsProvider(final CredentialsProvider credsProvider) {
this.credsProvider = credsProvider;
}
public synchronized final HttpRoutePlanner getRoutePlanner() {
if (this.routePlanner == null) {
this.routePlanner = createHttpRoutePlanner();
}
return this.routePlanner;
}
public synchronized void setRoutePlanner(final HttpRoutePlanner routePlanner) {
this.routePlanner = routePlanner;
}
public synchronized final UserTokenHandler getUserTokenHandler() {
if (this.userTokenHandler == null) {
this.userTokenHandler = createUserTokenHandler();
}
return this.userTokenHandler;
}
public synchronized void setUserTokenHandler(final UserTokenHandler userTokenHandler) {
this.userTokenHandler = userTokenHandler;
}
protected synchronized final BasicHttpProcessor getHttpProcessor() {
if (mutableProcessor == null) {
mutableProcessor = createHttpProcessor();
}
return mutableProcessor;
}
private synchronized final HttpProcessor getProtocolProcessor() {
if (protocolProcessor == null) {
// Get mutable HTTP processor
BasicHttpProcessor proc = getHttpProcessor();
// and create an immutable copy of it
int reqc = proc.getRequestInterceptorCount();
HttpRequestInterceptor[] reqinterceptors = new HttpRequestInterceptor[reqc];
for (int i = 0; i < reqc; i++) {
reqinterceptors[i] = proc.getRequestInterceptor(i);
}
int resc = proc.getResponseInterceptorCount();
HttpResponseInterceptor[] resinterceptors = new HttpResponseInterceptor[resc];
for (int i = 0; i < resc; i++) {
resinterceptors[i] = proc.getResponseInterceptor(i);
}
protocolProcessor = new ImmutableHttpProcessor(reqinterceptors, resinterceptors);
}
return protocolProcessor;
}
public synchronized int getResponseInterceptorCount() {
return getHttpProcessor().getResponseInterceptorCount();
}
public synchronized HttpResponseInterceptor getResponseInterceptor(int index) {
return getHttpProcessor().getResponseInterceptor(index);
}
public synchronized HttpRequestInterceptor getRequestInterceptor(int index) {
return getHttpProcessor().getRequestInterceptor(index);
}
public synchronized int getRequestInterceptorCount() {
return getHttpProcessor().getRequestInterceptorCount();
}
public synchronized void addResponseInterceptor(final HttpResponseInterceptor itcp) {
getHttpProcessor().addInterceptor(itcp);
protocolProcessor = null;
}
public synchronized void addResponseInterceptor(final HttpResponseInterceptor itcp, int index) {
getHttpProcessor().addInterceptor(itcp, index);
protocolProcessor = null;
}
public synchronized void clearResponseInterceptors() {
getHttpProcessor().clearResponseInterceptors();
protocolProcessor = null;
}
public synchronized void removeResponseInterceptorByClass(Class<? extends HttpResponseInterceptor> clazz) {
getHttpProcessor().removeResponseInterceptorByClass(clazz);
protocolProcessor = null;
}
public synchronized void addRequestInterceptor(final HttpRequestInterceptor itcp) {
getHttpProcessor().addInterceptor(itcp);
protocolProcessor = null;
}
public synchronized void addRequestInterceptor(final HttpRequestInterceptor itcp, int index) {
getHttpProcessor().addInterceptor(itcp, index);
protocolProcessor = null;
}
public synchronized void clearRequestInterceptors() {
getHttpProcessor().clearRequestInterceptors();
protocolProcessor = null;
}
public synchronized void removeRequestInterceptorByClass(Class<? extends HttpRequestInterceptor> clazz) {
getHttpProcessor().removeRequestInterceptorByClass(clazz);
protocolProcessor = null;
}
public final HttpResponse execute(HttpUriRequest request)
throws IOException, ClientProtocolException {
return execute(request, (HttpContext) null);
}
/**
* Maps to {@link HttpClient#execute(HttpHost,HttpRequest,HttpContext)
* execute(target, request, context)}.
* The target is determined from the URI of the request.
*
* @param request the request to execute
* @param context the request-specific execution context,
* or <code>null</code> to use a default context
*/
public final HttpResponse execute(HttpUriRequest request,
HttpContext context)
throws IOException, ClientProtocolException {
if (request == null) {
throw new IllegalArgumentException
("Request must not be null.");
}
return execute(determineTarget(request), request, context);
}
private static HttpHost determineTarget(HttpUriRequest request) throws ClientProtocolException {
// A null target may be acceptable if there is a default target.
// Otherwise, the null target is detected in the director.
HttpHost target = null;
URI requestURI = request.getURI();
if (requestURI.isAbsolute()) {
target = URIUtils.extractHost(requestURI);
if (target == null) {
throw new ClientProtocolException(
"URI does not specify a valid host name: " + requestURI);
}
}
return target;
}
public final HttpResponse execute(HttpHost target, HttpRequest request)
throws IOException, ClientProtocolException {
return execute(target, request, (HttpContext) null);
}
public final HttpResponse execute(HttpHost target, HttpRequest request,
HttpContext context)
throws IOException, ClientProtocolException {
if (request == null) {
throw new IllegalArgumentException
("Request must not be null.");
}
// a null target may be acceptable, this depends on the route planner
// a null context is acceptable, default context created below
HttpContext execContext = null;
RequestDirector director = null;
// Initialize the request execution context making copies of
// all shared objects that are potentially threading unsafe.
synchronized (this) {
HttpContext defaultContext = createHttpContext();
if (context == null) {
execContext = defaultContext;
} else {
execContext = new DefaultedHttpContext(context, defaultContext);
}
// Create a director for this request
director = createClientRequestDirector(
getRequestExecutor(),
getConnectionManager(),
getConnectionReuseStrategy(),
getConnectionKeepAliveStrategy(),
getRoutePlanner(),
getProtocolProcessor(),
getHttpRequestRetryHandler(),
getRedirectStrategy(),
getTargetAuthenticationHandler(),
getProxyAuthenticationHandler(),
getUserTokenHandler(),
determineParams(request));
}
try {
return director.execute(target, request, execContext);
} catch(HttpException httpException) {
throw new ClientProtocolException(httpException);
}
}
@Deprecated
protected RequestDirector createClientRequestDirector(
final HttpRequestExecutor requestExec,
final ClientConnectionManager conman,
final ConnectionReuseStrategy reustrat,
final ConnectionKeepAliveStrategy kastrat,
final HttpRoutePlanner rouplan,
final HttpProcessor httpProcessor,
final HttpRequestRetryHandler retryHandler,
final org.apache.ogt.http.client.RedirectHandler redirectHandler,
final AuthenticationHandler targetAuthHandler,
final AuthenticationHandler proxyAuthHandler,
final UserTokenHandler stateHandler,
final HttpParams params) {
return new DefaultRequestDirector(
requestExec,
conman,
reustrat,
kastrat,
rouplan,
httpProcessor,
retryHandler,
redirectHandler,
targetAuthHandler,
proxyAuthHandler,
stateHandler,
params);
}
/**
* @since 4.1
*/
protected RequestDirector createClientRequestDirector(
final HttpRequestExecutor requestExec,
final ClientConnectionManager conman,
final ConnectionReuseStrategy reustrat,
final ConnectionKeepAliveStrategy kastrat,
final HttpRoutePlanner rouplan,
final HttpProcessor httpProcessor,
final HttpRequestRetryHandler retryHandler,
final RedirectStrategy redirectStrategy,
final AuthenticationHandler targetAuthHandler,
final AuthenticationHandler proxyAuthHandler,
final UserTokenHandler stateHandler,
final HttpParams params) {
return new DefaultRequestDirector(
log,
requestExec,
conman,
reustrat,
kastrat,
rouplan,
httpProcessor,
retryHandler,
redirectStrategy,
targetAuthHandler,
proxyAuthHandler,
stateHandler,
params);
}
/**
* Obtains parameters for executing a request.
* The default implementation in this class creates a new
* {@link ClientParamsStack} from the request parameters
* and the client parameters.
* <br/>
* This method is called by the default implementation of
* {@link #execute(HttpHost,HttpRequest,HttpContext)}
* to obtain the parameters for the
* {@link DefaultRequestDirector}.
*
* @param req the request that will be executed
*
* @return the parameters to use
*/
protected HttpParams determineParams(HttpRequest req) {
return new ClientParamsStack
(null, getParams(), req.getParams(), null);
}
public <T> T execute(
final HttpUriRequest request,
final ResponseHandler<? extends T> responseHandler)
throws IOException, ClientProtocolException {
return execute(request, responseHandler, null);
}
public <T> T execute(
final HttpUriRequest request,
final ResponseHandler<? extends T> responseHandler,
final HttpContext context)
throws IOException, ClientProtocolException {
HttpHost target = determineTarget(request);
return execute(target, request, responseHandler, context);
}
public <T> T execute(
final HttpHost target,
final HttpRequest request,
final ResponseHandler<? extends T> responseHandler)
throws IOException, ClientProtocolException {
return execute(target, request, responseHandler, null);
}
public <T> T execute(
final HttpHost target,
final HttpRequest request,
final ResponseHandler<? extends T> responseHandler,
final HttpContext context)
throws IOException, ClientProtocolException {
if (responseHandler == null) {
throw new IllegalArgumentException
("Response handler must not be null.");
}
HttpResponse response = execute(target, request, context);
T result;
try {
result = responseHandler.handleResponse(response);
} catch (Throwable t) {
HttpEntity entity = response.getEntity();
try {
EntityUtils.consume(entity);
} catch (Exception t2) {
// Log this exception. The original exception is more
// important and will be thrown to the caller.
this.log.warn("Error consuming content after an exception.", t2);
}
if (t instanceof Error) {
throw (Error) t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
if (t instanceof IOException) {
throw (IOException) t;
}
throw new UndeclaredThrowableException(t);
}
// Handling the response was successful. Ensure that the content has
// been fully consumed.
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
return result;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.client;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.FormattedHeader;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthSchemeRegistry;
import org.apache.ogt.http.auth.AuthenticationException;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.client.AuthenticationHandler;
import org.apache.ogt.http.client.params.AuthPolicy;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Base class for {@link AuthenticationHandler} implementations.
*
* @since 4.0
*/
@Immutable
public abstract class AbstractAuthenticationHandler implements AuthenticationHandler {
private final Log log = LogFactory.getLog(getClass());
private static final List<String> DEFAULT_SCHEME_PRIORITY =
Collections.unmodifiableList(Arrays.asList(new String[] {
AuthPolicy.SPNEGO,
AuthPolicy.NTLM,
AuthPolicy.DIGEST,
AuthPolicy.BASIC
}));
public AbstractAuthenticationHandler() {
super();
}
protected Map<String, Header> parseChallenges(
final Header[] headers) throws MalformedChallengeException {
Map<String, Header> map = new HashMap<String, Header>(headers.length);
for (Header header : headers) {
CharArrayBuffer buffer;
int pos;
if (header instanceof FormattedHeader) {
buffer = ((FormattedHeader) header).getBuffer();
pos = ((FormattedHeader) header).getValuePos();
} else {
String s = header.getValue();
if (s == null) {
throw new MalformedChallengeException("Header value is null");
}
buffer = new CharArrayBuffer(s.length());
buffer.append(s);
pos = 0;
}
while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) {
pos++;
}
int beginIndex = pos;
while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) {
pos++;
}
int endIndex = pos;
String s = buffer.substring(beginIndex, endIndex);
map.put(s.toLowerCase(Locale.ENGLISH), header);
}
return map;
}
/**
* Returns default list of auth scheme names in their order of preference.
*
* @return list of auth scheme names
*/
protected List<String> getAuthPreferences() {
return DEFAULT_SCHEME_PRIORITY;
}
/**
* Returns default list of auth scheme names in their order of preference
* based on the HTTP response and the current execution context.
*
* @param response HTTP response.
* @param context HTTP execution context.
*
* @since 4.1
*/
protected List<String> getAuthPreferences(
final HttpResponse response,
final HttpContext context) {
return getAuthPreferences();
}
public AuthScheme selectScheme(
final Map<String, Header> challenges,
final HttpResponse response,
final HttpContext context) throws AuthenticationException {
AuthSchemeRegistry registry = (AuthSchemeRegistry) context.getAttribute(
ClientContext.AUTHSCHEME_REGISTRY);
if (registry == null) {
throw new IllegalStateException("AuthScheme registry not set in HTTP context");
}
Collection<String> authPrefs = getAuthPreferences(response, context);
if (authPrefs == null) {
authPrefs = DEFAULT_SCHEME_PRIORITY;
}
if (this.log.isDebugEnabled()) {
this.log.debug("Authentication schemes in the order of preference: "
+ authPrefs);
}
AuthScheme authScheme = null;
for (String id: authPrefs) {
Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
if (challenge != null) {
if (this.log.isDebugEnabled()) {
this.log.debug(id + " authentication scheme selected");
}
try {
authScheme = registry.getAuthScheme(id, response.getParams());
break;
} catch (IllegalStateException e) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication scheme " + id + " not supported");
// Try again
}
}
} else {
if (this.log.isDebugEnabled()) {
this.log.debug("Challenge for " + id + " authentication scheme not available");
// Try again
}
}
}
if (authScheme == null) {
// If none selected, something is wrong
throw new AuthenticationException(
"Unable to respond to any of these challenges: "
+ challenges);
}
return authScheme;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Collection;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.CookieSpecFactory;
import org.apache.ogt.http.cookie.params.CookieSpecPNames;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link CookieSpecFactory} implementation that creates and initializes
* {@link BestMatchSpec} instances.
* <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>
* </ul>
*
* @since 4.0
*/
@Immutable
public class BestMatchSpecFactory implements CookieSpecFactory {
public CookieSpec newInstance(final HttpParams params) {
if (params != null) {
String[] patterns = null;
Collection<?> param = (Collection<?>) params.getParameter(
CookieSpecPNames.DATE_PATTERNS);
if (param != null) {
patterns = new String[param.size()];
patterns = param.toArray(patterns);
}
boolean singleHeader = params.getBooleanParameter(
CookieSpecPNames.SINGLE_COOKIE_HEADER, false);
return new BestMatchSpec(patterns, singleHeader);
} else {
return new BestMatchSpec();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookieRestrictionViolationException;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
/**
*
* @since 4.0
*/
@Immutable
public class BasicPathHandler implements CookieAttributeHandler {
public BasicPathHandler() {
super();
}
public void parse(final SetCookie cookie, String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (value == null || value.trim().length() == 0) {
value = "/";
}
cookie.setPath(value);
}
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
if (!match(cookie, origin)) {
throw new CookieRestrictionViolationException(
"Illegal path attribute \"" + cookie.getPath()
+ "\". Path of origin: \"" + origin.getPath() + "\"");
}
}
public boolean match(final Cookie cookie, final CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
String targetpath = origin.getPath();
String topmostPath = cookie.getPath();
if (topmostPath == null) {
topmostPath = "/";
}
if (topmostPath.length() > 1 && topmostPath.endsWith("/")) {
topmostPath = topmostPath.substring(0, topmostPath.length() - 1);
}
boolean match = targetpath.startsWith (topmostPath);
// if there is a match and these values are not exactly the same we have
// to make sure we're not matcing "/foobar" and "/foo"
if (match && targetpath.length() != topmostPath.length()) {
if (!topmostPath.endsWith("/")) {
match = (targetpath.charAt(topmostPath.length()) == '/');
}
}
return match;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Locale;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookieRestrictionViolationException;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
/**
*
* @since 4.0
*/
@Immutable
public class RFC2109DomainHandler implements CookieAttributeHandler {
public RFC2109DomainHandler() {
super();
}
public void parse(final SetCookie cookie, final String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (value == null) {
throw new MalformedCookieException("Missing value for domain attribute");
}
if (value.trim().length() == 0) {
throw new MalformedCookieException("Blank value for domain attribute");
}
cookie.setDomain(value);
}
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
String host = origin.getHost();
String domain = cookie.getDomain();
if (domain == null) {
throw new CookieRestrictionViolationException("Cookie domain may not be null");
}
if (!domain.equals(host)) {
int dotIndex = domain.indexOf('.');
if (dotIndex == -1) {
throw new CookieRestrictionViolationException("Domain attribute \""
+ domain
+ "\" does not match the host \""
+ host + "\"");
}
// domain must start with dot
if (!domain.startsWith(".")) {
throw new CookieRestrictionViolationException("Domain attribute \""
+ domain
+ "\" violates RFC 2109: domain must start with a dot");
}
// domain must have at least one embedded dot
dotIndex = domain.indexOf('.', 1);
if (dotIndex < 0 || dotIndex == domain.length() - 1) {
throw new CookieRestrictionViolationException("Domain attribute \""
+ domain
+ "\" violates RFC 2109: domain must contain an embedded dot");
}
host = host.toLowerCase(Locale.ENGLISH);
if (!host.endsWith(domain)) {
throw new CookieRestrictionViolationException(
"Illegal domain attribute \"" + domain
+ "\". Domain of origin: \"" + host + "\"");
}
// host minus domain may not contain any dots
String hostWithoutDomain = host.substring(0, host.length() - domain.length());
if (hostWithoutDomain.indexOf('.') != -1) {
throw new CookieRestrictionViolationException("Domain attribute \""
+ domain
+ "\" violates RFC 2109: host minus domain may not contain any dots");
}
}
}
public boolean match(final Cookie cookie, final CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
String host = origin.getHost();
String domain = cookie.getDomain();
if (domain == null) {
return false;
}
return host.equals(domain) || (domain.startsWith(".") && host.endsWith(domain));
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.MalformedCookieException;
/**
*
* @since 4.0
*/
@Immutable
public abstract class AbstractCookieAttributeHandler implements CookieAttributeHandler {
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
// Do nothing
}
public boolean match(final Cookie cookie, final CookieOrigin origin) {
// Always match
return true;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Locale;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.ClientCookie;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookieRestrictionViolationException;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
/**
* <tt>"Domain"</tt> cookie attribute handler for RFC 2965 cookie spec.
*
*
* @since 3.1
*/
@Immutable
public class RFC2965DomainAttributeHandler implements CookieAttributeHandler {
public RFC2965DomainAttributeHandler() {
super();
}
/**
* Parse cookie domain attribute.
*/
public void parse(final SetCookie cookie, String domain)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (domain == null) {
throw new MalformedCookieException(
"Missing value for domain attribute");
}
if (domain.trim().length() == 0) {
throw new MalformedCookieException(
"Blank value for domain attribute");
}
domain = domain.toLowerCase(Locale.ENGLISH);
if (!domain.startsWith(".")) {
// Per RFC 2965 section 3.2.2
// "... If an explicitly specified value does not start with
// a dot, the user agent supplies a leading dot ..."
// That effectively implies that the domain attribute
// MAY NOT be an IP address of a host name
domain = '.' + domain;
}
cookie.setDomain(domain);
}
/**
* Performs domain-match as defined by the RFC2965.
* <p>
* Host A's name domain-matches host B's if
* <ol>
* <ul>their host name strings string-compare equal; or</ul>
* <ul>A is a HDN string and has the form NB, where N is a non-empty
* name string, B has the form .B', and B' is a HDN string. (So,
* x.y.com domain-matches .Y.com but not Y.com.)</ul>
* </ol>
*
* @param host host name where cookie is received from or being sent to.
* @param domain The cookie domain attribute.
* @return true if the specified host matches the given domain.
*/
public boolean domainMatch(String host, String domain) {
boolean match = host.equals(domain)
|| (domain.startsWith(".") && host.endsWith(domain));
return match;
}
/**
* Validate cookie domain attribute.
*/
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
String host = origin.getHost().toLowerCase(Locale.ENGLISH);
if (cookie.getDomain() == null) {
throw new CookieRestrictionViolationException("Invalid cookie state: " +
"domain not specified");
}
String cookieDomain = cookie.getDomain().toLowerCase(Locale.ENGLISH);
if (cookie instanceof ClientCookie
&& ((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) {
// Domain attribute must start with a dot
if (!cookieDomain.startsWith(".")) {
throw new CookieRestrictionViolationException("Domain attribute \"" +
cookie.getDomain() + "\" violates RFC 2109: domain must start with a dot");
}
// Domain attribute must contain at least one embedded dot,
// or the value must be equal to .local.
int dotIndex = cookieDomain.indexOf('.', 1);
if (((dotIndex < 0) || (dotIndex == cookieDomain.length() - 1))
&& (!cookieDomain.equals(".local"))) {
throw new CookieRestrictionViolationException(
"Domain attribute \"" + cookie.getDomain()
+ "\" violates RFC 2965: the value contains no embedded dots "
+ "and the value is not .local");
}
// The effective host name must domain-match domain attribute.
if (!domainMatch(host, cookieDomain)) {
throw new CookieRestrictionViolationException(
"Domain attribute \"" + cookie.getDomain()
+ "\" violates RFC 2965: effective host name does not "
+ "domain-match domain attribute.");
}
// effective host name minus domain must not contain any dots
String effectiveHostWithoutDomain = host.substring(
0, host.length() - cookieDomain.length());
if (effectiveHostWithoutDomain.indexOf('.') != -1) {
throw new CookieRestrictionViolationException("Domain attribute \""
+ cookie.getDomain() + "\" violates RFC 2965: "
+ "effective host minus domain may not contain any dots");
}
} else {
// Domain was not specified in header. In this case, domain must
// string match request host (case-insensitive).
if (!cookie.getDomain().equals(host)) {
throw new CookieRestrictionViolationException("Illegal domain attribute: \""
+ cookie.getDomain() + "\"."
+ "Domain of origin: \""
+ host + "\"");
}
}
}
/**
* Match cookie domain attribute.
*/
public boolean match(final Cookie cookie, final CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
String host = origin.getHost().toLowerCase(Locale.ENGLISH);
String cookieDomain = cookie.getDomain();
// The effective host name MUST domain-match the Domain
// attribute of the cookie.
if (!domainMatch(host, cookieDomain)) {
return false;
}
// effective host name minus domain must not contain any dots
String effectiveHostWithoutDomain = host.substring(
0, host.length() - cookieDomain.length());
return effectiveHostWithoutDomain.indexOf('.') == -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.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
import org.apache.ogt.http.cookie.SetCookie2;
/**
* <tt>"Discard"</tt> cookie attribute handler for RFC 2965 cookie spec.
*
* @since 4.0
*/
@Immutable
public class RFC2965DiscardAttributeHandler implements CookieAttributeHandler {
public RFC2965DiscardAttributeHandler() {
super();
}
public void parse(final SetCookie cookie, final String commenturl)
throws MalformedCookieException {
if (cookie instanceof SetCookie2) {
SetCookie2 cookie2 = (SetCookie2) cookie;
cookie2.setDiscard(true);
}
}
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
}
public boolean match(final Cookie cookie, final CookieOrigin origin) {
return true;
}
} | Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
/**
* An exception to indicate an error parsing a date string.
*
* @see DateUtils
*
*
* @since 4.0
*/
@Immutable
public class DateParseException extends Exception {
private static final long serialVersionUID = 4417696455000643370L;
/**
*
*/
public DateParseException() {
super();
}
/**
* @param message the exception message
*/
public DateParseException(String message) {
super(message);
}
}
| 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.impl.cookie;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.ogt.http.annotation.Immutable;
/**
* Parses the list from <a href="http://publicsuffix.org/">publicsuffix.org</a>
* and configures a PublicSuffixFilter.
*
* @since 4.0
*/
@Immutable
public class PublicSuffixListParser {
private static final int MAX_LINE_LEN = 256;
private final PublicSuffixFilter filter;
PublicSuffixListParser(PublicSuffixFilter filter) {
this.filter = filter;
}
/**
* Parses the public suffix list format.
* When creating the reader from the file, make sure to
* use the correct encoding (the original list is in UTF-8).
*
* @param list the suffix list. The caller is responsible for closing the reader.
* @throws IOException on error while reading from list
*/
public void parse(Reader list) throws IOException {
Collection<String> rules = new ArrayList<String>();
Collection<String> exceptions = new ArrayList<String>();
BufferedReader r = new BufferedReader(list);
StringBuilder sb = new StringBuilder(256);
boolean more = true;
while (more) {
more = readLine(r, sb);
String line = sb.toString();
if (line.length() == 0) continue;
if (line.startsWith("//")) continue; //entire lines can also be commented using //
if (line.startsWith(".")) line = line.substring(1); // A leading dot is optional
// An exclamation mark (!) at the start of a rule marks an exception to a previous wildcard rule
boolean isException = line.startsWith("!");
if (isException) line = line.substring(1);
if (isException) {
exceptions.add(line);
} else {
rules.add(line);
}
}
filter.setPublicSuffixes(rules);
filter.setExceptions(exceptions);
}
/**
*
* @param r
* @param sb
* @return false when the end of the stream is reached
* @throws IOException
*/
private boolean readLine(Reader r, StringBuilder sb) throws IOException {
sb.setLength(0);
int b;
boolean hitWhitespace = false;
while ((b = r.read()) != -1) {
char c = (char) b;
if (c == '\n') break;
// Each line is only read up to the first whitespace
if (Character.isWhitespace(c)) hitWhitespace = true;
if (!hitWhitespace) sb.append(c);
if (sb.length() > MAX_LINE_LEN) throw new IOException("Line too long"); // prevent excess memory usage
}
return (b != -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.impl.cookie;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieSpec;
/**
* Abstract cookie specification which can delegate the job of parsing,
* validation or matching cookie attributes to a number of arbitrary
* {@link CookieAttributeHandler}s.
*
*
* @since 4.0
*/
@NotThreadSafe // HashMap is not thread-safe
public abstract class AbstractCookieSpec implements CookieSpec {
/**
* Stores attribute name -> attribute handler mappings
*/
private final Map<String, CookieAttributeHandler> attribHandlerMap;
/**
* Default constructor
* */
public AbstractCookieSpec() {
super();
this.attribHandlerMap = new HashMap<String, CookieAttributeHandler>(10);
}
public void registerAttribHandler(
final String name, final CookieAttributeHandler handler) {
if (name == null) {
throw new IllegalArgumentException("Attribute name may not be null");
}
if (handler == null) {
throw new IllegalArgumentException("Attribute handler may not be null");
}
this.attribHandlerMap.put(name, handler);
}
/**
* Finds an attribute handler {@link CookieAttributeHandler} for the
* given attribute. Returns <tt>null</tt> if no attribute handler is
* found for the specified attribute.
*
* @param name attribute name. e.g. Domain, Path, etc.
* @return an attribute handler or <tt>null</tt>
*/
protected CookieAttributeHandler findAttribHandler(final String name) {
return this.attribHandlerMap.get(name);
}
/**
* Gets attribute handler {@link CookieAttributeHandler} for the
* given attribute.
*
* @param name attribute name. e.g. Domain, Path, etc.
* @throws IllegalStateException if handler not found for the
* specified attribute.
*/
protected CookieAttributeHandler getAttribHandler(final String name) {
CookieAttributeHandler handler = findAttribHandler(name);
if (handler == null) {
throw new IllegalStateException("Handler not registered for " +
name + " attribute.");
} else {
return handler;
}
}
protected Collection<CookieAttributeHandler> getAttribHandlers() {
return this.attribHandlerMap.values();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.List;
import org.apache.ogt.http.FormattedHeader;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.annotation.NotThreadSafe;
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.cookie.SetCookie2;
import org.apache.ogt.http.message.ParserCursor;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* 'Meta' cookie specification that picks up a cookie policy based on
* the format of cookies sent with the HTTP response.
*
* @since 4.0
*/
@NotThreadSafe // CookieSpec fields are @NotThreadSafe
public class BestMatchSpec implements CookieSpec {
private final String[] datepatterns;
private final boolean oneHeader;
// Cached values of CookieSpec instances
private RFC2965Spec strict; // @NotThreadSafe
private RFC2109Spec obsoleteStrict; // @NotThreadSafe
private BrowserCompatSpec compat; // @NotThreadSafe
public BestMatchSpec(final String[] datepatterns, boolean oneHeader) {
super();
this.datepatterns = datepatterns == null ? null : datepatterns.clone();
this.oneHeader = oneHeader;
}
public BestMatchSpec() {
this(null, false);
}
private RFC2965Spec getStrict() {
if (this.strict == null) {
this.strict = new RFC2965Spec(this.datepatterns, this.oneHeader);
}
return strict;
}
private RFC2109Spec getObsoleteStrict() {
if (this.obsoleteStrict == null) {
this.obsoleteStrict = new RFC2109Spec(this.datepatterns, this.oneHeader);
}
return obsoleteStrict;
}
private BrowserCompatSpec getCompat() {
if (this.compat == null) {
this.compat = new BrowserCompatSpec(this.datepatterns);
}
return compat;
}
public List<Cookie> parse(
final Header header,
final CookieOrigin origin) throws MalformedCookieException {
if (header == null) {
throw new IllegalArgumentException("Header may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
HeaderElement[] helems = header.getElements();
boolean versioned = false;
boolean netscape = false;
for (HeaderElement helem: helems) {
if (helem.getParameterByName("version") != null) {
versioned = true;
}
if (helem.getParameterByName("expires") != null) {
netscape = true;
}
}
if (netscape || !versioned) {
// Need to parse the header again, because Netscape style cookies do not correctly
// support multiple header elements (comma cannot be treated as an element separator)
NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT;
CharArrayBuffer buffer;
ParserCursor cursor;
if (header instanceof FormattedHeader) {
buffer = ((FormattedHeader) header).getBuffer();
cursor = new ParserCursor(
((FormattedHeader) header).getValuePos(),
buffer.length());
} else {
String s = header.getValue();
if (s == null) {
throw new MalformedCookieException("Header value is null");
}
buffer = new CharArrayBuffer(s.length());
buffer.append(s);
cursor = new ParserCursor(0, buffer.length());
}
helems = new HeaderElement[] { parser.parseHeader(buffer, cursor) };
return getCompat().parse(helems, origin);
} else {
if (SM.SET_COOKIE2.equals(header.getName())) {
return getStrict().parse(helems, origin);
} else {
return getObsoleteStrict().parse(helems, origin);
}
}
}
public void validate(
final Cookie cookie,
final CookieOrigin origin) throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
if (cookie.getVersion() > 0) {
if (cookie instanceof SetCookie2) {
getStrict().validate(cookie, origin);
} else {
getObsoleteStrict().validate(cookie, origin);
}
} else {
getCompat().validate(cookie, origin);
}
}
public boolean match(final Cookie cookie, final CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
if (cookie.getVersion() > 0) {
if (cookie instanceof SetCookie2) {
return getStrict().match(cookie, origin);
} else {
return getObsoleteStrict().match(cookie, origin);
}
} else {
return getCompat().match(cookie, origin);
}
}
public List<Header> formatCookies(final List<Cookie> cookies) {
if (cookies == null) {
throw new IllegalArgumentException("List of cookie may not be null");
}
int version = Integer.MAX_VALUE;
boolean isSetCookie2 = true;
for (Cookie cookie: cookies) {
if (!(cookie instanceof SetCookie2)) {
isSetCookie2 = false;
}
if (cookie.getVersion() < version) {
version = cookie.getVersion();
}
}
if (version > 0) {
if (isSetCookie2) {
return getStrict().formatCookies(cookies);
} else {
return getObsoleteStrict().formatCookies(cookies);
}
} else {
return getCompat().formatCookies(cookies);
}
}
public int getVersion() {
return getStrict().getVersion();
}
public Header getVersionHeader() {
return getStrict().getVersionHeader();
}
@Override
public String toString() {
return "best-match";
}
} | Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookieRestrictionViolationException;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
/**
*
* @since 4.0
*/
@Immutable
public class RFC2109VersionHandler extends AbstractCookieAttributeHandler {
public RFC2109VersionHandler() {
super();
}
public void parse(final SetCookie cookie, final String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (value == null) {
throw new MalformedCookieException("Missing value for version attribute");
}
if (value.trim().length() == 0) {
throw new MalformedCookieException("Blank value for version attribute");
}
try {
cookie.setVersion(Integer.parseInt(value));
} catch (NumberFormatException e) {
throw new MalformedCookieException("Invalid version: "
+ e.getMessage());
}
}
@Override
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (cookie.getVersion() < 0) {
throw new CookieRestrictionViolationException("Cookie version may not be negative");
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookieRestrictionViolationException;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
/**
*
* @since 4.0
*/
@Immutable
public class BasicDomainHandler implements CookieAttributeHandler {
public BasicDomainHandler() {
super();
}
public void parse(final SetCookie cookie, final String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (value == null) {
throw new MalformedCookieException("Missing value for domain attribute");
}
if (value.trim().length() == 0) {
throw new MalformedCookieException("Blank value for domain attribute");
}
cookie.setDomain(value);
}
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
// Validate the cookies domain attribute. NOTE: Domains without
// any dots are allowed to support hosts on private LANs that don't
// have DNS names. Since they have no dots, to domain-match the
// request-host and domain must be identical for the cookie to sent
// back to the origin-server.
String host = origin.getHost();
String domain = cookie.getDomain();
if (domain == null) {
throw new CookieRestrictionViolationException("Cookie domain may not be null");
}
if (host.contains(".")) {
// Not required to have at least two dots. RFC 2965.
// A Set-Cookie2 with Domain=ajax.com will be accepted.
// domain must match host
if (!host.endsWith(domain)) {
if (domain.startsWith(".")) {
domain = domain.substring(1, domain.length());
}
if (!host.equals(domain)) {
throw new CookieRestrictionViolationException(
"Illegal domain attribute \"" + domain
+ "\". Domain of origin: \"" + host + "\"");
}
}
} else {
if (!host.equals(domain)) {
throw new CookieRestrictionViolationException(
"Illegal domain attribute \"" + domain
+ "\". Domain of origin: \"" + host + "\"");
}
}
}
public boolean match(final Cookie cookie, final CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
String host = origin.getHost();
String domain = cookie.getDomain();
if (domain == null) {
return false;
}
if (host.equals(domain)) {
return true;
}
if (!domain.startsWith(".")) {
domain = '.' + domain;
}
return host.endsWith(domain) || host.equals(domain.substring(1));
}
}
| 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.impl.cookie;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.apache.ogt.http.client.utils.Punycode;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
/**
* Wraps a CookieAttributeHandler and leverages its match method
* to never match a suffix from a black list. May be used to provide
* additional security for cross-site attack types by preventing
* cookies from apparent domains that are not publicly available.
* An uptodate list of suffixes can be obtained from
* <a href="http://publicsuffix.org/">publicsuffix.org</a>
*
* @since 4.0
*/
public class PublicSuffixFilter implements CookieAttributeHandler {
private final CookieAttributeHandler wrapped;
private Set<String> exceptions;
private Set<String> suffixes;
public PublicSuffixFilter(CookieAttributeHandler wrapped) {
this.wrapped = wrapped;
}
/**
* Sets the suffix blacklist patterns.
* A pattern can be "com", "*.jp"
* TODO add support for patterns like "lib.*.us"
* @param suffixes
*/
public void setPublicSuffixes(Collection<String> suffixes) {
this.suffixes = new HashSet<String>(suffixes);
}
/**
* Sets the exceptions from the blacklist. Exceptions can not be patterns.
* TODO add support for patterns
* @param exceptions
*/
public void setExceptions(Collection<String> exceptions) {
this.exceptions = new HashSet<String>(exceptions);
}
/**
* Never matches if the cookie's domain is from the blacklist.
*/
public boolean match(Cookie cookie, CookieOrigin origin) {
if (isForPublicSuffix(cookie)) return false;
return wrapped.match(cookie, origin);
}
public void parse(SetCookie cookie, String value) throws MalformedCookieException {
wrapped.parse(cookie, value);
}
public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
wrapped.validate(cookie, origin);
}
private boolean isForPublicSuffix(Cookie cookie) {
String domain = cookie.getDomain();
if (domain.startsWith(".")) domain = domain.substring(1);
domain = Punycode.toUnicode(domain);
// An exception rule takes priority over any other matching rule.
if (this.exceptions != null) {
if (this.exceptions.contains(domain)) return false;
}
if (this.suffixes == null) return false;
do {
if (this.suffixes.contains(domain)) return true;
// patterns
if (domain.startsWith("*.")) domain = domain.substring(2);
int nextdot = domain.indexOf('.');
if (nextdot == -1) break;
domain = "*" + domain.substring(nextdot);
} while (domain.length() > 0);
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.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.ClientCookie;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookieRestrictionViolationException;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
import org.apache.ogt.http.cookie.SetCookie2;
/**
* <tt>"Version"</tt> cookie attribute handler for RFC 2965 cookie spec.
*
* @since 4.0
*/
@Immutable
public class RFC2965VersionAttributeHandler implements CookieAttributeHandler {
public RFC2965VersionAttributeHandler() {
super();
}
/**
* Parse cookie version attribute.
*/
public void parse(final SetCookie cookie, final String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (value == null) {
throw new MalformedCookieException(
"Missing value for version attribute");
}
int version = -1;
try {
version = Integer.parseInt(value);
} catch (NumberFormatException e) {
version = -1;
}
if (version < 0) {
throw new MalformedCookieException("Invalid cookie version.");
}
cookie.setVersion(version);
}
/**
* validate cookie version attribute. Version attribute is REQUIRED.
*/
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (cookie instanceof SetCookie2) {
if (cookie instanceof ClientCookie
&& !((ClientCookie) cookie).containsAttribute(ClientCookie.VERSION_ATTR)) {
throw new CookieRestrictionViolationException(
"Violates RFC 2965. Version attribute is required.");
}
}
}
public boolean match(final Cookie cookie, final CookieOrigin origin) {
return true;
}
} | Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Date;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
/**
*
* @since 4.0
*/
@Immutable
public class BasicMaxAgeHandler extends AbstractCookieAttributeHandler {
public BasicMaxAgeHandler() {
super();
}
public void parse(final SetCookie cookie, final String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (value == null) {
throw new MalformedCookieException("Missing value for max-age attribute");
}
int age;
try {
age = Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new MalformedCookieException ("Invalid max-age attribute: "
+ value);
}
if (age < 0) {
throw new MalformedCookieException ("Negative max-age attribute: "
+ value);
}
cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L));
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.ClientCookie;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
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.message.BufferedHeader;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* RFC 2965 compliant {@link CookieSpec} implementation.
*
* @since 4.0
*/
@NotThreadSafe // superclass is @NotThreadSafe
public class RFC2965Spec extends RFC2109Spec {
/**
* Default constructor
*
*/
public RFC2965Spec() {
this(null, false);
}
public RFC2965Spec(final String[] datepatterns, boolean oneHeader) {
super(datepatterns, oneHeader);
registerAttribHandler(ClientCookie.DOMAIN_ATTR, new RFC2965DomainAttributeHandler());
registerAttribHandler(ClientCookie.PORT_ATTR, new RFC2965PortAttributeHandler());
registerAttribHandler(ClientCookie.COMMENTURL_ATTR, new RFC2965CommentUrlAttributeHandler());
registerAttribHandler(ClientCookie.DISCARD_ATTR, new RFC2965DiscardAttributeHandler());
registerAttribHandler(ClientCookie.VERSION_ATTR, new RFC2965VersionAttributeHandler());
}
@Override
public List<Cookie> parse(
final Header header,
CookieOrigin origin) throws MalformedCookieException {
if (header == null) {
throw new IllegalArgumentException("Header may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE2)) {
throw new MalformedCookieException("Unrecognized cookie header '"
+ header.toString() + "'");
}
origin = adjustEffectiveHost(origin);
HeaderElement[] elems = header.getElements();
return createCookies(elems, origin);
}
@Override
protected List<Cookie> parse(
final HeaderElement[] elems,
CookieOrigin origin) throws MalformedCookieException {
origin = adjustEffectiveHost(origin);
return createCookies(elems, origin);
}
private List<Cookie> createCookies(
final HeaderElement[] elems,
final CookieOrigin origin) throws MalformedCookieException {
List<Cookie> cookies = new ArrayList<Cookie>(elems.length);
for (HeaderElement headerelement : elems) {
String name = headerelement.getName();
String value = headerelement.getValue();
if (name == null || name.length() == 0) {
throw new MalformedCookieException("Cookie name may not be empty");
}
BasicClientCookie2 cookie = new BasicClientCookie2(name, value);
cookie.setPath(getDefaultPath(origin));
cookie.setDomain(getDefaultDomain(origin));
cookie.setPorts(new int [] { origin.getPort() });
// cycle through the parameters
NameValuePair[] attribs = headerelement.getParameters();
// Eliminate duplicate attributes. The first occurrence takes precedence
// See RFC2965: 3.2 Origin Server Role
Map<String, NameValuePair> attribmap =
new HashMap<String, NameValuePair>(attribs.length);
for (int j = attribs.length - 1; j >= 0; j--) {
NameValuePair param = attribs[j];
attribmap.put(param.getName().toLowerCase(Locale.ENGLISH), param);
}
for (Map.Entry<String, NameValuePair> entry : attribmap.entrySet()) {
NameValuePair attrib = entry.getValue();
String s = attrib.getName().toLowerCase(Locale.ENGLISH);
cookie.setAttribute(s, attrib.getValue());
CookieAttributeHandler handler = findAttribHandler(s);
if (handler != null) {
handler.parse(cookie, attrib.getValue());
}
}
cookies.add(cookie);
}
return cookies;
}
@Override
public void validate(final Cookie cookie, CookieOrigin origin)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
origin = adjustEffectiveHost(origin);
super.validate(cookie, origin);
}
@Override
public boolean match(final Cookie cookie, CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
origin = adjustEffectiveHost(origin);
return super.match(cookie, origin);
}
/**
* Adds valid Port attribute value, e.g. "8000,8001,8002"
*/
@Override
protected void formatCookieAsVer(final CharArrayBuffer buffer,
final Cookie cookie, int version) {
super.formatCookieAsVer(buffer, cookie, version);
// format port attribute
if (cookie instanceof ClientCookie) {
// Test if the port attribute as set by the origin server is not blank
String s = ((ClientCookie) cookie).getAttribute(ClientCookie.PORT_ATTR);
if (s != null) {
buffer.append("; $Port");
buffer.append("=\"");
if (s.trim().length() > 0) {
int[] ports = cookie.getPorts();
if (ports != null) {
for (int i = 0, len = ports.length; i < len; i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(Integer.toString(ports[i]));
}
}
}
buffer.append("\"");
}
}
}
/**
* Set 'effective host name' as defined in RFC 2965.
* <p>
* If a host name contains no dots, the effective host name is
* that name with the string .local appended to it. Otherwise
* the effective host name is the same as the host name. Note
* that all effective host names contain at least one dot.
*
* @param origin origin where cookie is received from or being sent to.
* @return
*/
private static CookieOrigin adjustEffectiveHost(final CookieOrigin origin) {
String host = origin.getHost();
// Test if the host name appears to be a fully qualified DNS name,
// IPv4 address or IPv6 address
boolean isLocalHost = true;
for (int i = 0; i < host.length(); i++) {
char ch = host.charAt(i);
if (ch == '.' || ch == ':') {
isLocalHost = false;
break;
}
}
if (isLocalHost) {
host += ".local";
return new CookieOrigin(
host,
origin.getPort(),
origin.getPath(),
origin.isSecure());
} else {
return origin;
}
}
@Override
public int getVersion() {
return 1;
}
@Override
public Header getVersionHeader() {
CharArrayBuffer buffer = new CharArrayBuffer(40);
buffer.append(SM.COOKIE2);
buffer.append(": ");
buffer.append("$Version=");
buffer.append(Integer.toString(getVersion()));
return new BufferedHeader(buffer);
}
@Override
public String toString() {
return "rfc2965";
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Collection;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.CookieSpecFactory;
import org.apache.ogt.http.cookie.params.CookieSpecPNames;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link CookieSpecFactory} implementation that creates and initializes
* {@link NetscapeDraftSpec} instances.
* <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>
* </ul>
*
* @since 4.0
*/
@Immutable
public class NetscapeDraftSpecFactory implements CookieSpecFactory {
public CookieSpec newInstance(final HttpParams params) {
if (params != null) {
String[] patterns = null;
Collection<?> param = (Collection<?>) params.getParameter(
CookieSpecPNames.DATE_PATTERNS);
if (param != null) {
patterns = new String[param.size()];
patterns = param.toArray(patterns);
}
return new NetscapeDraftSpec(patterns);
} else {
return new NetscapeDraftSpec();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.lang.ref.SoftReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.apache.ogt.http.annotation.Immutable;
/**
* A utility class for parsing and formatting HTTP dates as used in cookies and
* other headers. This class handles dates as defined by RFC 2616 section
* 3.3.1 as well as some other common non-standard formats.
*
*
* @since 4.0
*/
@Immutable
public final class DateUtils {
/**
* Date format pattern used to parse HTTP date headers in RFC 1123 format.
*/
public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
/**
* Date format pattern used to parse HTTP date headers in RFC 1036 format.
*/
public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";
/**
* Date format pattern used to parse HTTP date headers in ANSI C
* <code>asctime()</code> format.
*/
public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
private static final String[] DEFAULT_PATTERNS = new String[] {
PATTERN_RFC1036,
PATTERN_RFC1123,
PATTERN_ASCTIME
};
private static final Date DEFAULT_TWO_DIGIT_YEAR_START;
public static final TimeZone GMT = TimeZone.getTimeZone("GMT");
static {
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(GMT);
calendar.set(2000, Calendar.JANUARY, 1, 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
DEFAULT_TWO_DIGIT_YEAR_START = calendar.getTime();
}
/**
* Parses a date value. The formats used for parsing the date value are retrieved from
* the default http params.
*
* @param dateValue the date value to parse
*
* @return the parsed date
*
* @throws DateParseException if the value could not be parsed using any of the
* supported date formats
*/
public static Date parseDate(String dateValue) throws DateParseException {
return parseDate(dateValue, null, null);
}
/**
* Parses the date value using the given date formats.
*
* @param dateValue the date value to parse
* @param dateFormats the date formats to use
*
* @return the parsed date
*
* @throws DateParseException if none of the dataFormats could parse the dateValue
*/
public static Date parseDate(final String dateValue, String[] dateFormats)
throws DateParseException {
return parseDate(dateValue, dateFormats, null);
}
/**
* Parses the date value using the given date formats.
*
* @param dateValue the date value to parse
* @param dateFormats the date formats to use
* @param startDate During parsing, two digit years will be placed in the range
* <code>startDate</code> to <code>startDate + 100 years</code>. This value may
* be <code>null</code>. When <code>null</code> is given as a parameter, year
* <code>2000</code> will be used.
*
* @return the parsed date
*
* @throws DateParseException if none of the dataFormats could parse the dateValue
*/
public static Date parseDate(
String dateValue,
String[] dateFormats,
Date startDate
) throws DateParseException {
if (dateValue == null) {
throw new IllegalArgumentException("dateValue is null");
}
if (dateFormats == null) {
dateFormats = DEFAULT_PATTERNS;
}
if (startDate == null) {
startDate = DEFAULT_TWO_DIGIT_YEAR_START;
}
// trim single quotes around date if present
// see issue #5279
if (dateValue.length() > 1
&& dateValue.startsWith("'")
&& dateValue.endsWith("'")
) {
dateValue = dateValue.substring (1, dateValue.length() - 1);
}
for (String dateFormat : dateFormats) {
SimpleDateFormat dateParser = DateFormatHolder.formatFor(dateFormat);
dateParser.set2DigitYearStart(startDate);
try {
return dateParser.parse(dateValue);
} catch (ParseException pe) {
// ignore this exception, we will try the next format
}
}
// we were unable to parse the date
throw new DateParseException("Unable to parse the date " + dateValue);
}
/**
* Formats the given date according to the RFC 1123 pattern.
*
* @param date The date to format.
* @return An RFC 1123 formatted date string.
*
* @see #PATTERN_RFC1123
*/
public static String formatDate(Date date) {
return formatDate(date, PATTERN_RFC1123);
}
/**
* Formats the given date according to the specified pattern. The pattern
* must conform to that used by the {@link SimpleDateFormat simple date
* format} class.
*
* @param date The date to format.
* @param pattern The pattern to use for formatting the date.
* @return A formatted date string.
*
* @throws IllegalArgumentException If the given date pattern is invalid.
*
* @see SimpleDateFormat
*/
public static String formatDate(Date date, String pattern) {
if (date == null) throw new IllegalArgumentException("date is null");
if (pattern == null) throw new IllegalArgumentException("pattern is null");
SimpleDateFormat formatter = DateFormatHolder.formatFor(pattern);
return formatter.format(date);
}
/** This class should not be instantiated. */
private DateUtils() {
}
/**
* A factory for {@link SimpleDateFormat}s. The instances are stored in a
* threadlocal way because SimpleDateFormat is not threadsafe as noted in
* {@link SimpleDateFormat its javadoc}.
*
*/
final static class DateFormatHolder {
private static final ThreadLocal<SoftReference<Map<String, SimpleDateFormat>>>
THREADLOCAL_FORMATS = new ThreadLocal<SoftReference<Map<String, SimpleDateFormat>>>() {
@Override
protected SoftReference<Map<String, SimpleDateFormat>> initialValue() {
return new SoftReference<Map<String, SimpleDateFormat>>(
new HashMap<String, SimpleDateFormat>());
}
};
/**
* creates a {@link SimpleDateFormat} for the requested format string.
*
* @param pattern
* a non-<code>null</code> format String according to
* {@link SimpleDateFormat}. The format is not checked against
* <code>null</code> since all paths go through
* {@link DateUtils}.
* @return the requested format. This simple dateformat should not be used
* to {@link SimpleDateFormat#applyPattern(String) apply} to a
* different pattern.
*/
public static SimpleDateFormat formatFor(String pattern) {
SoftReference<Map<String, SimpleDateFormat>> ref = THREADLOCAL_FORMATS.get();
Map<String, SimpleDateFormat> formats = ref.get();
if (formats == null) {
formats = new HashMap<String, SimpleDateFormat>();
THREADLOCAL_FORMATS.set(
new SoftReference<Map<String, SimpleDateFormat>>(formats));
}
SimpleDateFormat format = formats.get(pattern);
if (format == null) {
format = new SimpleDateFormat(pattern, Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
formats.put(pattern, format);
}
return format;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.ClientCookie;
import org.apache.ogt.http.cookie.SetCookie;
/**
* Default implementation of {@link SetCookie}.
*
* @since 4.0
*/
@NotThreadSafe
public class BasicClientCookie implements SetCookie, ClientCookie, Cloneable, Serializable {
private static final long serialVersionUID = -3869795591041535538L;
/**
* Default Constructor taking a name and a value. The value may be null.
*
* @param name The name.
* @param value The value.
*/
public BasicClientCookie(final String name, final String value) {
super();
if (name == null) {
throw new IllegalArgumentException("Name may not be null");
}
this.name = name;
this.attribs = new HashMap<String, String>();
this.value = value;
}
/**
* Returns the name.
*
* @return String name The name
*/
public String getName() {
return this.name;
}
/**
* Returns the value.
*
* @return String value The current value.
*/
public String getValue() {
return this.value;
}
/**
* Sets the value
*
* @param value
*/
public void setValue(final String value) {
this.value = value;
}
/**
* Returns the comment describing the purpose of this cookie, or
* <tt>null</tt> if no such comment has been defined.
*
* @return comment
*
* @see #setComment(String)
*/
public String getComment() {
return cookieComment;
}
/**
* 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()
*/
public void setComment(String comment) {
cookieComment = comment;
}
/**
* Returns null. Cookies prior to RFC2965 do not set this attribute
*/
public String getCommentURL() {
return null;
}
/**
* 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>.
*
* @see #setExpiryDate(java.util.Date)
*
*/
public Date getExpiryDate() {
return cookieExpiryDate;
}
/**
* 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 #getExpiryDate
*
*/
public void setExpiryDate (Date expiryDate) {
cookieExpiryDate = expiryDate;
}
/**
* 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
*/
public boolean isPersistent() {
return (null != cookieExpiryDate);
}
/**
* Returns domain attribute of the cookie.
*
* @return the value of the domain attribute
*
* @see #setDomain(java.lang.String)
*/
public String getDomain() {
return cookieDomain;
}
/**
* Sets the domain attribute.
*
* @param domain The value of the domain attribute
*
* @see #getDomain
*/
public void setDomain(String domain) {
if (domain != null) {
cookieDomain = domain.toLowerCase(Locale.ENGLISH);
} else {
cookieDomain = null;
}
}
/**
* Returns the path attribute of the cookie
*
* @return The value of the path attribute.
*
* @see #setPath(java.lang.String)
*/
public String getPath() {
return cookiePath;
}
/**
* Sets the path attribute.
*
* @param path The value of the path attribute
*
* @see #getPath
*
*/
public void setPath(String path) {
cookiePath = path;
}
/**
* @return <code>true</code> if this cookie should only be sent over secure connections.
* @see #setSecure(boolean)
*/
public boolean isSecure() {
return isSecure;
}
/**
* 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()
*/
public void setSecure (boolean secure) {
isSecure = secure;
}
/**
* Returns null. Cookies prior to RFC2965 do not set this attribute
*/
public int[] getPorts() {
return null;
}
/**
* Returns the version of the cookie specification to which this
* cookie conforms.
*
* @return the version of the cookie.
*
* @see #setVersion(int)
*
*/
public int getVersion() {
return cookieVersion;
}
/**
* Sets the version of the cookie specification to which this
* cookie conforms.
*
* @param version the version of the cookie.
*
* @see #getVersion
*/
public void setVersion(int version) {
cookieVersion = version;
}
/**
* Returns true if this cookie has expired.
* @param date Current time
*
* @return <tt>true</tt> if the cookie has expired.
*/
public boolean isExpired(final Date date) {
if (date == null) {
throw new IllegalArgumentException("Date may not be null");
}
return (cookieExpiryDate != null
&& cookieExpiryDate.getTime() <= date.getTime());
}
public void setAttribute(final String name, final String value) {
this.attribs.put(name, value);
}
public String getAttribute(final String name) {
return this.attribs.get(name);
}
public boolean containsAttribute(final String name) {
return this.attribs.get(name) != null;
}
@Override
public Object clone() throws CloneNotSupportedException {
BasicClientCookie clone = (BasicClientCookie) super.clone();
clone.attribs = new HashMap<String, String>(this.attribs);
return clone;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append("[version: ");
buffer.append(Integer.toString(this.cookieVersion));
buffer.append("]");
buffer.append("[name: ");
buffer.append(this.name);
buffer.append("]");
buffer.append("[value: ");
buffer.append(this.value);
buffer.append("]");
buffer.append("[domain: ");
buffer.append(this.cookieDomain);
buffer.append("]");
buffer.append("[path: ");
buffer.append(this.cookiePath);
buffer.append("]");
buffer.append("[expiry: ");
buffer.append(this.cookieExpiryDate);
buffer.append("]");
return buffer.toString();
}
// ----------------------------------------------------- Instance Variables
/** Cookie name */
private final String name;
/** Cookie attributes as specified by the origin server */
private Map<String, String> attribs;
/** Cookie value */
private String value;
/** Comment attribute. */
private String cookieComment;
/** Domain attribute. */
private String cookieDomain;
/** Expiration {@link Date}. */
private Date cookieExpiryDate;
/** Path attribute. */
private String cookiePath;
/** My secure flag. */
private boolean isSecure;
/** The version of the cookie specification I was created from. */
private int cookieVersion;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Collection;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.CookieSpecFactory;
import org.apache.ogt.http.cookie.params.CookieSpecPNames;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link CookieSpecFactory} implementation that creates and initializes
* {@link RFC2965Spec} instances.
* <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>
* </ul>
*
* @since 4.0
*/
@Immutable
public class RFC2965SpecFactory implements CookieSpecFactory {
public CookieSpec newInstance(final HttpParams params) {
if (params != null) {
String[] patterns = null;
Collection<?> param = (Collection<?>) params.getParameter(
CookieSpecPNames.DATE_PATTERNS);
if (param != null) {
patterns = new String[param.size()];
patterns = param.toArray(patterns);
}
boolean singleHeader = params.getBooleanParameter(
CookieSpecPNames.SINGLE_COOKIE_HEADER, false);
return new RFC2965Spec(patterns, singleHeader);
} else {
return new RFC2965Spec();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
import org.apache.ogt.http.cookie.SetCookie2;
/**
* <tt>"CommentURL"</tt> cookie attribute handler for RFC 2965 cookie spec.
*
* @since 4.0
*/
@Immutable
public class RFC2965CommentUrlAttributeHandler implements CookieAttributeHandler {
public RFC2965CommentUrlAttributeHandler() {
super();
}
public void parse(final SetCookie cookie, final String commenturl)
throws MalformedCookieException {
if (cookie instanceof SetCookie2) {
SetCookie2 cookie2 = (SetCookie2) cookie;
cookie2.setCommentURL(commenturl);
}
}
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
}
public boolean match(final Cookie cookie, final CookieOrigin origin) {
return true;
}
} | Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.CookieSpecFactory;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link CookieSpecFactory} implementation that ignores all cookies.
*
* @since 4.1
*/
@Immutable
public class IgnoreSpecFactory implements CookieSpecFactory {
public CookieSpec newInstance(final HttpParams params) {
return new IgnoreSpec();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Locale;
import java.util.StringTokenizer;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookieRestrictionViolationException;
import org.apache.ogt.http.cookie.MalformedCookieException;
/**
*
* @since 4.0
*/
@Immutable
public class NetscapeDomainHandler extends BasicDomainHandler {
public NetscapeDomainHandler() {
super();
}
@Override
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
super.validate(cookie, origin);
// Perform Netscape Cookie draft specific validation
String host = origin.getHost();
String domain = cookie.getDomain();
if (host.contains(".")) {
int domainParts = new StringTokenizer(domain, ".").countTokens();
if (isSpecialDomain(domain)) {
if (domainParts < 2) {
throw new CookieRestrictionViolationException("Domain attribute \""
+ domain
+ "\" violates the Netscape cookie specification for "
+ "special domains");
}
} else {
if (domainParts < 3) {
throw new CookieRestrictionViolationException("Domain attribute \""
+ domain
+ "\" violates the Netscape cookie specification");
}
}
}
}
/**
* Checks if the given domain is in one of the seven special
* top level domains defined by the Netscape cookie specification.
* @param domain The domain.
* @return True if the specified domain is "special"
*/
private static boolean isSpecialDomain(final String domain) {
final String ucDomain = domain.toUpperCase(Locale.ENGLISH);
return ucDomain.endsWith(".COM")
|| ucDomain.endsWith(".EDU")
|| ucDomain.endsWith(".NET")
|| ucDomain.endsWith(".GOV")
|| ucDomain.endsWith(".MIL")
|| ucDomain.endsWith(".ORG")
|| ucDomain.endsWith(".INT");
}
@Override
public boolean match(Cookie cookie, CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
String host = origin.getHost();
String domain = cookie.getDomain();
if (domain == null) {
return false;
}
return host.endsWith(domain);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.io.Serializable;
import java.util.Date;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.SetCookie2;
/**
* Default implementation of {@link SetCookie2}.
*
* @since 4.0
*/
@NotThreadSafe
public class BasicClientCookie2 extends BasicClientCookie implements SetCookie2, Serializable {
private static final long serialVersionUID = -7744598295706617057L;
private String commentURL;
private int[] ports;
private boolean discard;
/**
* Default Constructor taking a name and a value. The value may be null.
*
* @param name The name.
* @param value The value.
*/
public BasicClientCookie2(final String name, final String value) {
super(name, value);
}
@Override
public int[] getPorts() {
return this.ports;
}
public void setPorts(final int[] ports) {
this.ports = ports;
}
@Override
public String getCommentURL() {
return this.commentURL;
}
public void setCommentURL(final String commentURL) {
this.commentURL = commentURL;
}
public void setDiscard(boolean discard) {
this.discard = discard;
}
@Override
public boolean isPersistent() {
return !this.discard && super.isPersistent();
}
@Override
public boolean isExpired(final Date date) {
return this.discard || super.isExpired(date);
}
@Override
public Object clone() throws CloneNotSupportedException {
BasicClientCookie2 clone = (BasicClientCookie2) super.clone();
if (this.ports != null) {
clone.ports = this.ports.clone();
}
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.impl.cookie;
import java.util.Collection;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.CookieSpecFactory;
import org.apache.ogt.http.cookie.params.CookieSpecPNames;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link CookieSpecFactory} implementation that creates and initializes
* {@link BrowserCompatSpec} instances.
* <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>
* </ul>
*
* @since 4.0
*/
@Immutable
public class BrowserCompatSpecFactory implements CookieSpecFactory {
public CookieSpec newInstance(final HttpParams params) {
if (params != null) {
String[] patterns = null;
Collection<?> param = (Collection<?>) params.getParameter(
CookieSpecPNames.DATE_PATTERNS);
if (param != null) {
patterns = new String[param.size()];
patterns = param.toArray(patterns);
}
return new BrowserCompatSpec(patterns);
} else {
return new BrowserCompatSpec();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.ArrayList;
import java.util.List;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.message.BasicHeaderElement;
import org.apache.ogt.http.message.BasicNameValuePair;
import org.apache.ogt.http.message.ParserCursor;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
*
* @since 4.0
*/
@Immutable
public class NetscapeDraftHeaderParser {
public final static NetscapeDraftHeaderParser DEFAULT = new NetscapeDraftHeaderParser();
public NetscapeDraftHeaderParser() {
super();
}
public HeaderElement parseHeader(
final CharArrayBuffer buffer,
final ParserCursor cursor) throws ParseException {
if (buffer == null) {
throw new IllegalArgumentException("Char array buffer may not be null");
}
if (cursor == null) {
throw new IllegalArgumentException("Parser cursor may not be null");
}
NameValuePair nvp = parseNameValuePair(buffer, cursor);
List<NameValuePair> params = new ArrayList<NameValuePair>();
while (!cursor.atEnd()) {
NameValuePair param = parseNameValuePair(buffer, cursor);
params.add(param);
}
return new BasicHeaderElement(
nvp.getName(),
nvp.getValue(), params.toArray(new NameValuePair[params.size()]));
}
private NameValuePair parseNameValuePair(
final CharArrayBuffer buffer, final ParserCursor cursor) {
boolean terminated = false;
int pos = cursor.getPos();
int indexFrom = cursor.getPos();
int indexTo = cursor.getUpperBound();
// Find name
String name = null;
while (pos < indexTo) {
char ch = buffer.charAt(pos);
if (ch == '=') {
break;
}
if (ch == ';') {
terminated = true;
break;
}
pos++;
}
if (pos == indexTo) {
terminated = true;
name = buffer.substringTrimmed(indexFrom, indexTo);
} else {
name = buffer.substringTrimmed(indexFrom, pos);
pos++;
}
if (terminated) {
cursor.updatePos(pos);
return new BasicNameValuePair(name, null);
}
// Find value
String value = null;
int i1 = pos;
while (pos < indexTo) {
char ch = buffer.charAt(pos);
if (ch == ';') {
terminated = true;
break;
}
pos++;
}
int i2 = pos;
// Trim leading white spaces
while (i1 < i2 && (HTTP.isWhitespace(buffer.charAt(i1)))) {
i1++;
}
// Trim trailing white spaces
while ((i2 > i1) && (HTTP.isWhitespace(buffer.charAt(i2 - 1)))) {
i2--;
}
value = buffer.substring(i1, i2);
if (terminated) {
pos++;
}
cursor.updatePos(pos);
return new BasicNameValuePair(name, value);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Collection;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.CookieSpecFactory;
import org.apache.ogt.http.cookie.params.CookieSpecPNames;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link CookieSpecFactory} implementation that creates and initializes
* {@link RFC2109Spec} instances.
* <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>
* </ul>
*
* @since 4.0
*/
@Immutable
public class RFC2109SpecFactory implements CookieSpecFactory {
public CookieSpec newInstance(final HttpParams params) {
if (params != null) {
String[] patterns = null;
Collection<?> param = (Collection<?>) params.getParameter(
CookieSpecPNames.DATE_PATTERNS);
if (param != null) {
patterns = new String[param.size()];
patterns = param.toArray(patterns);
}
boolean singleHeader = params.getBooleanParameter(
CookieSpecPNames.SINGLE_COOKIE_HEADER, false);
return new RFC2109Spec(patterns, singleHeader);
} else {
return new RFC2109Spec();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.MalformedCookieException;
/**
* Cookie management functions shared by all specification.
*
*
* @since 4.0
*/
@NotThreadSafe // AbstractCookieSpec is not thread-safe
public abstract class CookieSpecBase extends AbstractCookieSpec {
protected static String getDefaultPath(final CookieOrigin origin) {
String defaultPath = origin.getPath();
int lastSlashIndex = defaultPath.lastIndexOf('/');
if (lastSlashIndex >= 0) {
if (lastSlashIndex == 0) {
//Do not remove the very first slash
lastSlashIndex = 1;
}
defaultPath = defaultPath.substring(0, lastSlashIndex);
}
return defaultPath;
}
protected static String getDefaultDomain(final CookieOrigin origin) {
return origin.getHost();
}
protected List<Cookie> parse(final HeaderElement[] elems, final CookieOrigin origin)
throws MalformedCookieException {
List<Cookie> cookies = new ArrayList<Cookie>(elems.length);
for (HeaderElement headerelement : elems) {
String name = headerelement.getName();
String value = headerelement.getValue();
if (name == null || name.length() == 0) {
throw new MalformedCookieException("Cookie name may not be empty");
}
BasicClientCookie cookie = new BasicClientCookie(name, value);
cookie.setPath(getDefaultPath(origin));
cookie.setDomain(getDefaultDomain(origin));
// cycle through the parameters
NameValuePair[] attribs = headerelement.getParameters();
for (int j = attribs.length - 1; j >= 0; j--) {
NameValuePair attrib = attribs[j];
String s = attrib.getName().toLowerCase(Locale.ENGLISH);
cookie.setAttribute(s, attrib.getValue());
CookieAttributeHandler handler = findAttribHandler(s);
if (handler != null) {
handler.parse(cookie, attrib.getValue());
}
}
cookies.add(cookie);
}
return cookies;
}
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
for (CookieAttributeHandler handler: getAttribHandlers()) {
handler.validate(cookie, origin);
}
}
public boolean match(final Cookie cookie, final CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
for (CookieAttributeHandler handler: getAttribHandlers()) {
if (!handler.match(cookie, origin)) {
return false;
}
}
return true;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
/**
*
* @since 4.0
*/
@Immutable
public class BasicSecureHandler extends AbstractCookieAttributeHandler {
public BasicSecureHandler() {
super();
}
public void parse(final SetCookie cookie, final String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
cookie.setSecure(true);
}
@Override
public boolean match(final Cookie cookie, final CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
return !cookie.isSecure() || origin.isSecure();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Collections;
import java.util.List;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.MalformedCookieException;
/**
* CookieSpec that ignores all cookies
*
* @since 4.1
*/
@NotThreadSafe // superclass is @NotThreadSafe
public class IgnoreSpec extends CookieSpecBase {
public int getVersion() {
return 0;
}
public List<Cookie> parse(Header header, CookieOrigin origin)
throws MalformedCookieException {
return Collections.emptyList();
}
public List<Header> formatCookies(List<Cookie> cookies) {
return Collections.emptyList();
}
public Header getVersionHeader() {
return null;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.ArrayList;
import java.util.List;
import org.apache.ogt.http.FormattedHeader;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.ClientCookie;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SM;
import org.apache.ogt.http.message.BufferedHeader;
import org.apache.ogt.http.message.ParserCursor;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Cookie specification that strives to closely mimic (mis)behavior of
* common web browser applications such as Microsoft Internet Explorer
* and Mozilla FireFox.
*
*
* @since 4.0
*/
@NotThreadSafe // superclass is @NotThreadSafe
public class BrowserCompatSpec extends CookieSpecBase {
@Deprecated
protected static final String[] DATE_PATTERNS = new String[] {
DateUtils.PATTERN_RFC1123,
DateUtils.PATTERN_RFC1036,
DateUtils.PATTERN_ASCTIME,
"EEE, dd-MMM-yyyy HH:mm:ss z",
"EEE, dd-MMM-yyyy HH-mm-ss z",
"EEE, dd MMM yy HH:mm:ss z",
"EEE dd-MMM-yyyy HH:mm:ss z",
"EEE dd MMM yyyy HH:mm:ss z",
"EEE dd-MMM-yyyy HH-mm-ss z",
"EEE dd-MMM-yy HH:mm:ss z",
"EEE dd MMM yy HH:mm:ss z",
"EEE,dd-MMM-yy HH:mm:ss z",
"EEE,dd-MMM-yyyy HH:mm:ss z",
"EEE, dd-MM-yyyy HH:mm:ss z",
};
private static final String[] DEFAULT_DATE_PATTERNS = new String[] {
DateUtils.PATTERN_RFC1123,
DateUtils.PATTERN_RFC1036,
DateUtils.PATTERN_ASCTIME,
"EEE, dd-MMM-yyyy HH:mm:ss z",
"EEE, dd-MMM-yyyy HH-mm-ss z",
"EEE, dd MMM yy HH:mm:ss z",
"EEE dd-MMM-yyyy HH:mm:ss z",
"EEE dd MMM yyyy HH:mm:ss z",
"EEE dd-MMM-yyyy HH-mm-ss z",
"EEE dd-MMM-yy HH:mm:ss z",
"EEE dd MMM yy HH:mm:ss z",
"EEE,dd-MMM-yy HH:mm:ss z",
"EEE,dd-MMM-yyyy HH:mm:ss z",
"EEE, dd-MM-yyyy HH:mm:ss z",
};
private final String[] datepatterns;
/** Default constructor */
public BrowserCompatSpec(final String[] datepatterns) {
super();
if (datepatterns != null) {
this.datepatterns = datepatterns.clone();
} else {
this.datepatterns = DEFAULT_DATE_PATTERNS;
}
registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandler());
registerAttribHandler(ClientCookie.DOMAIN_ATTR, new BasicDomainHandler());
registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandler());
registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandler());
registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandler());
registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler(
this.datepatterns));
}
/** Default constructor */
public BrowserCompatSpec() {
this(null);
}
public List<Cookie> parse(final Header header, final CookieOrigin origin)
throws MalformedCookieException {
if (header == null) {
throw new IllegalArgumentException("Header may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
String headername = header.getName();
if (!headername.equalsIgnoreCase(SM.SET_COOKIE)) {
throw new MalformedCookieException("Unrecognized cookie header '"
+ header.toString() + "'");
}
HeaderElement[] helems = header.getElements();
boolean versioned = false;
boolean netscape = false;
for (HeaderElement helem: helems) {
if (helem.getParameterByName("version") != null) {
versioned = true;
}
if (helem.getParameterByName("expires") != null) {
netscape = true;
}
}
if (netscape || !versioned) {
// Need to parse the header again, because Netscape style cookies do not correctly
// support multiple header elements (comma cannot be treated as an element separator)
NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT;
CharArrayBuffer buffer;
ParserCursor cursor;
if (header instanceof FormattedHeader) {
buffer = ((FormattedHeader) header).getBuffer();
cursor = new ParserCursor(
((FormattedHeader) header).getValuePos(),
buffer.length());
} else {
String s = header.getValue();
if (s == null) {
throw new MalformedCookieException("Header value is null");
}
buffer = new CharArrayBuffer(s.length());
buffer.append(s);
cursor = new ParserCursor(0, buffer.length());
}
helems = new HeaderElement[] { parser.parseHeader(buffer, cursor) };
}
return parse(helems, origin);
}
public List<Header> formatCookies(final List<Cookie> cookies) {
if (cookies == null) {
throw new IllegalArgumentException("List of cookies may not be null");
}
if (cookies.isEmpty()) {
throw new IllegalArgumentException("List of cookies may not be empty");
}
CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size());
buffer.append(SM.COOKIE);
buffer.append(": ");
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
if (i > 0) {
buffer.append("; ");
}
buffer.append(cookie.getName());
buffer.append("=");
String s = cookie.getValue();
if (s != null) {
buffer.append(s);
}
}
List<Header> headers = new ArrayList<Header>(1);
headers.add(new BufferedHeader(buffer));
return headers;
}
public int getVersion() {
return 0;
}
public Header getVersionHeader() {
return null;
}
@Override
public String toString() {
return "compatibility";
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
/**
*
* @since 4.0
*/
@Immutable
public class BasicCommentHandler extends AbstractCookieAttributeHandler {
public BasicCommentHandler() {
super();
}
public void parse(final SetCookie cookie, final String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
cookie.setComment(value);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.ArrayList;
import java.util.List;
import org.apache.ogt.http.FormattedHeader;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.ClientCookie;
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.message.BufferedHeader;
import org.apache.ogt.http.message.ParserCursor;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* This {@link CookieSpec} implementation conforms to the original draft
* specification published by Netscape Communications. It should be avoided
* unless absolutely necessary for compatibility with legacy code.
*
* @since 4.0
*/
@NotThreadSafe // superclass is @NotThreadSafe
public class NetscapeDraftSpec extends CookieSpecBase {
protected static final String EXPIRES_PATTERN = "EEE, dd-MMM-yy HH:mm:ss z";
private final String[] datepatterns;
/** Default constructor */
public NetscapeDraftSpec(final String[] datepatterns) {
super();
if (datepatterns != null) {
this.datepatterns = datepatterns.clone();
} else {
this.datepatterns = new String[] { EXPIRES_PATTERN };
}
registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandler());
registerAttribHandler(ClientCookie.DOMAIN_ATTR, new NetscapeDomainHandler());
registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandler());
registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandler());
registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandler());
registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler(
this.datepatterns));
}
/** Default constructor */
public NetscapeDraftSpec() {
this(null);
}
/**
* Parses the Set-Cookie value into an array of <tt>Cookie</tt>s.
*
* <p>Syntax of the Set-Cookie HTTP Response Header:</p>
*
* <p>This is the format a CGI script would use to add to
* the HTTP headers a new piece of data which is to be stored by
* the client for later retrieval.</p>
*
* <PRE>
* Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
* </PRE>
*
* <p>Please note that the Netscape draft specification does not fully conform to the HTTP
* header format. Comma character if present in <code>Set-Cookie</code> will not be treated
* as a header element separator</p>
*
* @see <a href="http://web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html">
* The Cookie Spec.</a>
*
* @param header the <tt>Set-Cookie</tt> received from the server
* @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie value
* @throws MalformedCookieException if an exception occurs during parsing
*/
public List<Cookie> parse(final Header header, final CookieOrigin origin)
throws MalformedCookieException {
if (header == null) {
throw new IllegalArgumentException("Header may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE)) {
throw new MalformedCookieException("Unrecognized cookie header '"
+ header.toString() + "'");
}
NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT;
CharArrayBuffer buffer;
ParserCursor cursor;
if (header instanceof FormattedHeader) {
buffer = ((FormattedHeader) header).getBuffer();
cursor = new ParserCursor(
((FormattedHeader) header).getValuePos(),
buffer.length());
} else {
String s = header.getValue();
if (s == null) {
throw new MalformedCookieException("Header value is null");
}
buffer = new CharArrayBuffer(s.length());
buffer.append(s);
cursor = new ParserCursor(0, buffer.length());
}
return parse(new HeaderElement[] { parser.parseHeader(buffer, cursor) }, origin);
}
public List<Header> formatCookies(final List<Cookie> cookies) {
if (cookies == null) {
throw new IllegalArgumentException("List of cookies may not be null");
}
if (cookies.isEmpty()) {
throw new IllegalArgumentException("List of cookies may not be empty");
}
CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size());
buffer.append(SM.COOKIE);
buffer.append(": ");
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
if (i > 0) {
buffer.append("; ");
}
buffer.append(cookie.getName());
String s = cookie.getValue();
if (s != null) {
buffer.append("=");
buffer.append(s);
}
}
List<Header> headers = new ArrayList<Header>(1);
headers.add(new BufferedHeader(buffer));
return headers;
}
public int getVersion() {
return 0;
}
public Header getVersionHeader() {
return null;
}
@Override
public String toString() {
return "netscape";
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
/**
*
* @since 4.0
*/
@Immutable
public class BasicExpiresHandler extends AbstractCookieAttributeHandler {
/** Valid date patterns */
private final String[] datepatterns;
public BasicExpiresHandler(final String[] datepatterns) {
if (datepatterns == null) {
throw new IllegalArgumentException("Array of date patterns may not be null");
}
this.datepatterns = datepatterns;
}
public void parse(final SetCookie cookie, final String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (value == null) {
throw new MalformedCookieException("Missing value for expires attribute");
}
try {
cookie.setExpiryDate(DateUtils.parseDate(value, this.datepatterns));
} catch (DateParseException dpe) {
throw new MalformedCookieException("Unable to parse expires attribute: "
+ value);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.ClientCookie;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookiePathComparator;
import org.apache.ogt.http.cookie.CookieRestrictionViolationException;
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.message.BufferedHeader;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* RFC 2109 compliant {@link CookieSpec} implementation. This is an older
* version of the official HTTP state management specification superseded
* by RFC 2965.
*
* @see RFC2965Spec
*
* @since 4.0
*/
@NotThreadSafe // superclass is @NotThreadSafe
public class RFC2109Spec extends CookieSpecBase {
private final static CookiePathComparator PATH_COMPARATOR = new CookiePathComparator();
private final static String[] DATE_PATTERNS = {
DateUtils.PATTERN_RFC1123,
DateUtils.PATTERN_RFC1036,
DateUtils.PATTERN_ASCTIME
};
private final String[] datepatterns;
private final boolean oneHeader;
/** Default constructor */
public RFC2109Spec(final String[] datepatterns, boolean oneHeader) {
super();
if (datepatterns != null) {
this.datepatterns = datepatterns.clone();
} else {
this.datepatterns = DATE_PATTERNS;
}
this.oneHeader = oneHeader;
registerAttribHandler(ClientCookie.VERSION_ATTR, new RFC2109VersionHandler());
registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandler());
registerAttribHandler(ClientCookie.DOMAIN_ATTR, new RFC2109DomainHandler());
registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandler());
registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandler());
registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandler());
registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler(
this.datepatterns));
}
/** Default constructor */
public RFC2109Spec() {
this(null, false);
}
public List<Cookie> parse(final Header header, final CookieOrigin origin)
throws MalformedCookieException {
if (header == null) {
throw new IllegalArgumentException("Header may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE)) {
throw new MalformedCookieException("Unrecognized cookie header '"
+ header.toString() + "'");
}
HeaderElement[] elems = header.getElements();
return parse(elems, origin);
}
@Override
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
String name = cookie.getName();
if (name.indexOf(' ') != -1) {
throw new CookieRestrictionViolationException("Cookie name may not contain blanks");
}
if (name.startsWith("$")) {
throw new CookieRestrictionViolationException("Cookie name may not start with $");
}
super.validate(cookie, origin);
}
public List<Header> formatCookies(List<Cookie> cookies) {
if (cookies == null) {
throw new IllegalArgumentException("List of cookies may not be null");
}
if (cookies.isEmpty()) {
throw new IllegalArgumentException("List of cookies may not be empty");
}
if (cookies.size() > 1) {
// Create a mutable copy and sort the copy.
cookies = new ArrayList<Cookie>(cookies);
Collections.sort(cookies, PATH_COMPARATOR);
}
if (this.oneHeader) {
return doFormatOneHeader(cookies);
} else {
return doFormatManyHeaders(cookies);
}
}
private List<Header> doFormatOneHeader(final List<Cookie> cookies) {
int version = Integer.MAX_VALUE;
// Pick the lowest common denominator
for (Cookie cookie : cookies) {
if (cookie.getVersion() < version) {
version = cookie.getVersion();
}
}
CharArrayBuffer buffer = new CharArrayBuffer(40 * cookies.size());
buffer.append(SM.COOKIE);
buffer.append(": ");
buffer.append("$Version=");
buffer.append(Integer.toString(version));
for (Cookie cooky : cookies) {
buffer.append("; ");
Cookie cookie = cooky;
formatCookieAsVer(buffer, cookie, version);
}
List<Header> headers = new ArrayList<Header>(1);
headers.add(new BufferedHeader(buffer));
return headers;
}
private List<Header> doFormatManyHeaders(final List<Cookie> cookies) {
List<Header> headers = new ArrayList<Header>(cookies.size());
for (Cookie cookie : cookies) {
int version = cookie.getVersion();
CharArrayBuffer buffer = new CharArrayBuffer(40);
buffer.append("Cookie: ");
buffer.append("$Version=");
buffer.append(Integer.toString(version));
buffer.append("; ");
formatCookieAsVer(buffer, cookie, version);
headers.add(new BufferedHeader(buffer));
}
return headers;
}
/**
* Return a name/value string suitable for sending in a <tt>"Cookie"</tt>
* header as defined in RFC 2109 for backward compatibility with cookie
* version 0
* @param buffer The char array buffer to use for output
* @param name The cookie name
* @param value The cookie value
* @param version The cookie version
*/
protected void formatParamAsVer(final CharArrayBuffer buffer,
final String name, final String value, int version) {
buffer.append(name);
buffer.append("=");
if (value != null) {
if (version > 0) {
buffer.append('\"');
buffer.append(value);
buffer.append('\"');
} else {
buffer.append(value);
}
}
}
/**
* Return a string suitable for sending in a <tt>"Cookie"</tt> header
* as defined in RFC 2109 for backward compatibility with cookie version 0
* @param buffer The char array buffer to use for output
* @param cookie The {@link Cookie} to be formatted as string
* @param version The version to use.
*/
protected void formatCookieAsVer(final CharArrayBuffer buffer,
final Cookie cookie, int version) {
formatParamAsVer(buffer, cookie.getName(), cookie.getValue(), version);
if (cookie.getPath() != null) {
if (cookie instanceof ClientCookie
&& ((ClientCookie) cookie).containsAttribute(ClientCookie.PATH_ATTR)) {
buffer.append("; ");
formatParamAsVer(buffer, "$Path", cookie.getPath(), version);
}
}
if (cookie.getDomain() != null) {
if (cookie instanceof ClientCookie
&& ((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) {
buffer.append("; ");
formatParamAsVer(buffer, "$Domain", cookie.getDomain(), version);
}
}
}
public int getVersion() {
return 1;
}
public Header getVersionHeader() {
return null;
}
@Override
public String toString() {
return "rfc2109";
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.StringTokenizer;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.ClientCookie;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookieRestrictionViolationException;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
import org.apache.ogt.http.cookie.SetCookie2;
/**
* <tt>"Port"</tt> cookie attribute handler for RFC 2965 cookie spec.
*
* @since 4.0
*/
@Immutable
public class RFC2965PortAttributeHandler implements CookieAttributeHandler {
public RFC2965PortAttributeHandler() {
super();
}
/**
* Parses the given Port attribute value (e.g. "8000,8001,8002")
* into an array of ports.
*
* @param portValue port attribute value
* @return parsed array of ports
* @throws MalformedCookieException if there is a problem in
* parsing due to invalid portValue.
*/
private static int[] parsePortAttribute(final String portValue)
throws MalformedCookieException {
StringTokenizer st = new StringTokenizer(portValue, ",");
int[] ports = new int[st.countTokens()];
try {
int i = 0;
while(st.hasMoreTokens()) {
ports[i] = Integer.parseInt(st.nextToken().trim());
if (ports[i] < 0) {
throw new MalformedCookieException ("Invalid Port attribute.");
}
++i;
}
} catch (NumberFormatException e) {
throw new MalformedCookieException ("Invalid Port "
+ "attribute: " + e.getMessage());
}
return ports;
}
/**
* Returns <tt>true</tt> if the given port exists in the given
* ports list.
*
* @param port port of host where cookie was received from or being sent to.
* @param ports port list
* @return true returns <tt>true</tt> if the given port exists in
* the given ports list; <tt>false</tt> otherwise.
*/
private static boolean portMatch(int port, int[] ports) {
boolean portInList = false;
for (int i = 0, len = ports.length; i < len; i++) {
if (port == ports[i]) {
portInList = true;
break;
}
}
return portInList;
}
/**
* Parse cookie port attribute.
*/
public void parse(final SetCookie cookie, final String portValue)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (cookie instanceof SetCookie2) {
SetCookie2 cookie2 = (SetCookie2) cookie;
if (portValue != null && portValue.trim().length() > 0) {
int[] ports = parsePortAttribute(portValue);
cookie2.setPorts(ports);
}
}
}
/**
* Validate cookie port attribute. If the Port attribute was specified
* in header, the request port must be in cookie's port list.
*/
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
int port = origin.getPort();
if (cookie instanceof ClientCookie
&& ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) {
if (!portMatch(port, cookie.getPorts())) {
throw new CookieRestrictionViolationException(
"Port attribute violates RFC 2965: "
+ "Request port not found in cookie's port list.");
}
}
}
/**
* Match cookie port attribute. If the Port attribute is not specified
* in header, the cookie can be sent to any port. Otherwise, the request port
* must be in the cookie's port list.
*/
public boolean match(final Cookie cookie, final CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
int port = origin.getPort();
if (cookie instanceof ClientCookie
&& ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) {
if (cookie.getPorts() == null) {
// Invalid cookie state: port not specified
return false;
}
if (!portMatch(port, cookie.getPorts())) {
return false;
}
}
return true;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
/**
* Abstract NTLM authentication engine. The engine can be used to
* generate Type1 messages and Type3 messages in response to a
* Type2 challenge.
*
* @since 4.0
*/
public interface NTLMEngine {
/**
* Generates a Type1 message given the domain and workstation.
*
* @param domain Optional Windows domain name. Can be <code>null</code>.
* @param workstation Optional Windows workstation name. Can be
* <code>null</code>.
* @return Type1 message
* @throws NTLMEngineException
*/
String generateType1Msg(
String domain,
String workstation) throws NTLMEngineException;
/**
* Generates a Type3 message given the user credentials and the
* authentication challenge.
*
* @param username Windows user name
* @param password Password
* @param domain Windows domain name
* @param workstation Windows workstation name
* @param challenge Type2 challenge.
* @return Type3 response.
* @throws NTLMEngineException
*/
String generateType3Msg(
String username,
String password,
String domain,
String workstation,
String challenge) throws NTLMEngineException;
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import java.security.Key;
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.ogt.http.util.EncodingUtils;
/**
* Provides an implementation for NTLMv1, NTLMv2, and NTLM2 Session forms of the NTLM
* authentication protocol.
*
* @since 4.1
*/
final class NTLMEngineImpl implements NTLMEngine {
// Flags we use
protected final static int FLAG_UNICODE_ENCODING = 0x00000001;
protected final static int FLAG_TARGET_DESIRED = 0x00000004;
protected final static int FLAG_NEGOTIATE_SIGN = 0x00000010;
protected final static int FLAG_NEGOTIATE_SEAL = 0x00000020;
protected final static int FLAG_NEGOTIATE_NTLM = 0x00000200;
protected final static int FLAG_NEGOTIATE_ALWAYS_SIGN = 0x00008000;
protected final static int FLAG_NEGOTIATE_NTLM2 = 0x00080000;
protected final static int FLAG_NEGOTIATE_128 = 0x20000000;
protected final static int FLAG_NEGOTIATE_KEY_EXCH = 0x40000000;
/** Secure random generator */
private static final java.security.SecureRandom RND_GEN;
static {
java.security.SecureRandom rnd = null;
try {
rnd = java.security.SecureRandom.getInstance("SHA1PRNG");
} catch (Exception e) {
}
RND_GEN = rnd;
}
/** Character encoding */
static final String DEFAULT_CHARSET = "ASCII";
/** The character set to use for encoding the credentials */
private String credentialCharset = DEFAULT_CHARSET;
/** The signature string as bytes in the default encoding */
private static byte[] SIGNATURE;
static {
byte[] bytesWithoutNull = EncodingUtils.getBytes("NTLMSSP", "ASCII");
SIGNATURE = new byte[bytesWithoutNull.length + 1];
System.arraycopy(bytesWithoutNull, 0, SIGNATURE, 0, bytesWithoutNull.length);
SIGNATURE[bytesWithoutNull.length] = (byte) 0x00;
}
/**
* Returns the response for the given message.
*
* @param message
* the message that was received from the server.
* @param username
* the username to authenticate with.
* @param password
* the password to authenticate with.
* @param host
* The host.
* @param domain
* the NT domain to authenticate in.
* @return The response.
* @throws HttpException
* If the messages cannot be retrieved.
*/
final String getResponseFor(String message, String username, String password,
String host, String domain) throws NTLMEngineException {
final String response;
if (message == null || message.trim().equals("")) {
response = getType1Message(host, domain);
} else {
Type2Message t2m = new Type2Message(message);
response = getType3Message(username, password, host, domain, t2m.getChallenge(), t2m
.getFlags(), t2m.getTarget(), t2m.getTargetInfo());
}
return response;
}
/**
* Creates the first message (type 1 message) in the NTLM authentication
* sequence. This message includes the user name, domain and host for the
* authentication session.
*
* @param host
* the computer name of the host requesting authentication.
* @param domain
* The domain to authenticate with.
* @return String the message to add to the HTTP request header.
*/
String getType1Message(String host, String domain) throws NTLMEngineException {
return new Type1Message(domain, host).getResponse();
}
/**
* Creates the type 3 message using the given server nonce. The type 3
* message includes all the information for authentication, host, domain,
* username and the result of encrypting the nonce sent by the server using
* the user's password as the key.
*
* @param user
* The user name. This should not include the domain name.
* @param password
* The password.
* @param host
* The host that is originating the authentication request.
* @param domain
* The domain to authenticate within.
* @param nonce
* the 8 byte array the server sent.
* @return The type 3 message.
* @throws NTLMEngineException
* If {@encrypt(byte[],byte[])} fails.
*/
String getType3Message(String user, String password, String host, String domain,
byte[] nonce, int type2Flags, String target, byte[] targetInformation)
throws NTLMEngineException {
return new Type3Message(domain, host, user, password, nonce, type2Flags, target,
targetInformation).getResponse();
}
/**
* @return Returns the credentialCharset.
*/
String getCredentialCharset() {
return credentialCharset;
}
/**
* @param credentialCharset
* The credentialCharset to set.
*/
void setCredentialCharset(String credentialCharset) {
this.credentialCharset = credentialCharset;
}
/** Strip dot suffix from a name */
private static String stripDotSuffix(String value) {
int index = value.indexOf(".");
if (index != -1)
return value.substring(0, index);
return value;
}
/** Convert host to standard form */
private static String convertHost(String host) {
return stripDotSuffix(host);
}
/** Convert domain to standard form */
private static String convertDomain(String domain) {
return stripDotSuffix(domain);
}
private static int readULong(byte[] src, int index) throws NTLMEngineException {
if (src.length < index + 4)
throw new NTLMEngineException("NTLM authentication - buffer too small for DWORD");
return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8)
| ((src[index + 2] & 0xff) << 16) | ((src[index + 3] & 0xff) << 24);
}
private static int readUShort(byte[] src, int index) throws NTLMEngineException {
if (src.length < index + 2)
throw new NTLMEngineException("NTLM authentication - buffer too small for WORD");
return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8);
}
private static byte[] readSecurityBuffer(byte[] src, int index) throws NTLMEngineException {
int length = readUShort(src, index);
int offset = readULong(src, index + 4);
if (src.length < offset + length)
throw new NTLMEngineException(
"NTLM authentication - buffer too small for data item");
byte[] buffer = new byte[length];
System.arraycopy(src, offset, buffer, 0, length);
return buffer;
}
/** Calculate a challenge block */
private static byte[] makeRandomChallenge() throws NTLMEngineException {
if (RND_GEN == null) {
throw new NTLMEngineException("Random generator not available");
}
byte[] rval = new byte[8];
synchronized (RND_GEN) {
RND_GEN.nextBytes(rval);
}
return rval;
}
/** Calculate an NTLM2 challenge block */
private static byte[] makeNTLM2RandomChallenge() throws NTLMEngineException {
if (RND_GEN == null) {
throw new NTLMEngineException("Random generator not available");
}
byte[] rval = new byte[24];
synchronized (RND_GEN) {
RND_GEN.nextBytes(rval);
}
// 8-byte challenge, padded with zeros to 24 bytes.
Arrays.fill(rval, 8, 24, (byte) 0x00);
return rval;
}
/**
* Calculates the LM Response for the given challenge, using the specified
* password.
*
* @param password
* The user's password.
* @param challenge
* The Type 2 challenge from the server.
*
* @return The LM Response.
*/
static byte[] getLMResponse(String password, byte[] challenge)
throws NTLMEngineException {
byte[] lmHash = lmHash(password);
return lmResponse(lmHash, challenge);
}
/**
* Calculates the NTLM Response for the given challenge, using the specified
* password.
*
* @param password
* The user's password.
* @param challenge
* The Type 2 challenge from the server.
*
* @return The NTLM Response.
*/
static byte[] getNTLMResponse(String password, byte[] challenge)
throws NTLMEngineException {
byte[] ntlmHash = ntlmHash(password);
return lmResponse(ntlmHash, challenge);
}
/**
* Calculates the NTLMv2 Response for the given challenge, using the
* specified authentication target, username, password, target information
* block, and client challenge.
*
* @param target
* The authentication target (i.e., domain).
* @param user
* The username.
* @param password
* The user's password.
* @param targetInformation
* The target information block from the Type 2 message.
* @param challenge
* The Type 2 challenge from the server.
* @param clientChallenge
* The random 8-byte client challenge.
*
* @return The NTLMv2 Response.
*/
static byte[] getNTLMv2Response(String target, String user, String password,
byte[] challenge, byte[] clientChallenge, byte[] targetInformation)
throws NTLMEngineException {
byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
byte[] blob = createBlob(clientChallenge, targetInformation);
return lmv2Response(ntlmv2Hash, challenge, blob);
}
/**
* Calculates the LMv2 Response for the given challenge, using the specified
* authentication target, username, password, and client challenge.
*
* @param target
* The authentication target (i.e., domain).
* @param user
* The username.
* @param password
* The user's password.
* @param challenge
* The Type 2 challenge from the server.
* @param clientChallenge
* The random 8-byte client challenge.
*
* @return The LMv2 Response.
*/
static byte[] getLMv2Response(String target, String user, String password,
byte[] challenge, byte[] clientChallenge) throws NTLMEngineException {
byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
return lmv2Response(ntlmv2Hash, challenge, clientChallenge);
}
/**
* Calculates the NTLM2 Session Response for the given challenge, using the
* specified password and client challenge.
*
* @param password
* The user's password.
* @param challenge
* The Type 2 challenge from the server.
* @param clientChallenge
* The random 8-byte client challenge.
*
* @return The NTLM2 Session Response. This is placed in the NTLM response
* field of the Type 3 message; the LM response field contains the
* client challenge, null-padded to 24 bytes.
*/
static byte[] getNTLM2SessionResponse(String password, byte[] challenge,
byte[] clientChallenge) throws NTLMEngineException {
try {
byte[] ntlmHash = ntlmHash(password);
// Look up MD5 algorithm (was necessary on jdk 1.4.2)
// This used to be needed, but java 1.5.0_07 includes the MD5
// algorithm (finally)
// Class x = Class.forName("gnu.crypto.hash.MD5");
// Method updateMethod = x.getMethod("update",new
// Class[]{byte[].class});
// Method digestMethod = x.getMethod("digest",new Class[0]);
// Object mdInstance = x.newInstance();
// updateMethod.invoke(mdInstance,new Object[]{challenge});
// updateMethod.invoke(mdInstance,new Object[]{clientChallenge});
// byte[] digest = (byte[])digestMethod.invoke(mdInstance,new
// Object[0]);
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(challenge);
md5.update(clientChallenge);
byte[] digest = md5.digest();
byte[] sessionHash = new byte[8];
System.arraycopy(digest, 0, sessionHash, 0, 8);
return lmResponse(ntlmHash, sessionHash);
} catch (Exception e) {
if (e instanceof NTLMEngineException)
throw (NTLMEngineException) e;
throw new NTLMEngineException(e.getMessage(), e);
}
}
/**
* Creates the LM Hash of the user's password.
*
* @param password
* The password.
*
* @return The LM Hash of the given password, used in the calculation of the
* LM Response.
*/
private static byte[] lmHash(String password) throws NTLMEngineException {
try {
byte[] oemPassword = password.toUpperCase().getBytes("US-ASCII");
int length = Math.min(oemPassword.length, 14);
byte[] keyBytes = new byte[14];
System.arraycopy(oemPassword, 0, keyBytes, 0, length);
Key lowKey = createDESKey(keyBytes, 0);
Key highKey = createDESKey(keyBytes, 7);
byte[] magicConstant = "KGS!@#$%".getBytes("US-ASCII");
Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
des.init(Cipher.ENCRYPT_MODE, lowKey);
byte[] lowHash = des.doFinal(magicConstant);
des.init(Cipher.ENCRYPT_MODE, highKey);
byte[] highHash = des.doFinal(magicConstant);
byte[] lmHash = new byte[16];
System.arraycopy(lowHash, 0, lmHash, 0, 8);
System.arraycopy(highHash, 0, lmHash, 8, 8);
return lmHash;
} catch (Exception e) {
throw new NTLMEngineException(e.getMessage(), e);
}
}
/**
* Creates the NTLM Hash of the user's password.
*
* @param password
* The password.
*
* @return The NTLM Hash of the given password, used in the calculation of
* the NTLM Response and the NTLMv2 and LMv2 Hashes.
*/
private static byte[] ntlmHash(String password) throws NTLMEngineException {
try {
byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked");
MD4 md4 = new MD4();
md4.update(unicodePassword);
return md4.getOutput();
} catch (java.io.UnsupportedEncodingException e) {
throw new NTLMEngineException("Unicode not supported: " + e.getMessage(), e);
}
}
/**
* Creates the NTLMv2 Hash of the user's password.
*
* @param target
* The authentication target (i.e., domain).
* @param user
* The username.
* @param password
* The password.
*
* @return The NTLMv2 Hash, used in the calculation of the NTLMv2 and LMv2
* Responses.
*/
private static byte[] ntlmv2Hash(String target, String user, String password)
throws NTLMEngineException {
try {
byte[] ntlmHash = ntlmHash(password);
HMACMD5 hmacMD5 = new HMACMD5(ntlmHash);
// Upper case username, mixed case target!!
hmacMD5.update(user.toUpperCase().getBytes("UnicodeLittleUnmarked"));
hmacMD5.update(target.getBytes("UnicodeLittleUnmarked"));
return hmacMD5.getOutput();
} catch (java.io.UnsupportedEncodingException e) {
throw new NTLMEngineException("Unicode not supported! " + e.getMessage(), e);
}
}
/**
* Creates the LM Response from the given hash and Type 2 challenge.
*
* @param hash
* The LM or NTLM Hash.
* @param challenge
* The server challenge from the Type 2 message.
*
* @return The response (either LM or NTLM, depending on the provided hash).
*/
private static byte[] lmResponse(byte[] hash, byte[] challenge) throws NTLMEngineException {
try {
byte[] keyBytes = new byte[21];
System.arraycopy(hash, 0, keyBytes, 0, 16);
Key lowKey = createDESKey(keyBytes, 0);
Key middleKey = createDESKey(keyBytes, 7);
Key highKey = createDESKey(keyBytes, 14);
Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
des.init(Cipher.ENCRYPT_MODE, lowKey);
byte[] lowResponse = des.doFinal(challenge);
des.init(Cipher.ENCRYPT_MODE, middleKey);
byte[] middleResponse = des.doFinal(challenge);
des.init(Cipher.ENCRYPT_MODE, highKey);
byte[] highResponse = des.doFinal(challenge);
byte[] lmResponse = new byte[24];
System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
System.arraycopy(highResponse, 0, lmResponse, 16, 8);
return lmResponse;
} catch (Exception e) {
throw new NTLMEngineException(e.getMessage(), e);
}
}
/**
* Creates the LMv2 Response from the given hash, client data, and Type 2
* challenge.
*
* @param hash
* The NTLMv2 Hash.
* @param clientData
* The client data (blob or client challenge).
* @param challenge
* The server challenge from the Type 2 message.
*
* @return The response (either NTLMv2 or LMv2, depending on the client
* data).
*/
private static byte[] lmv2Response(byte[] hash, byte[] challenge, byte[] clientData)
throws NTLMEngineException {
HMACMD5 hmacMD5 = new HMACMD5(hash);
hmacMD5.update(challenge);
hmacMD5.update(clientData);
byte[] mac = hmacMD5.getOutput();
byte[] lmv2Response = new byte[mac.length + clientData.length];
System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
System.arraycopy(clientData, 0, lmv2Response, mac.length, clientData.length);
return lmv2Response;
}
/**
* Creates the NTLMv2 blob from the given target information block and
* client challenge.
*
* @param targetInformation
* The target information block from the Type 2 message.
* @param clientChallenge
* The random 8-byte client challenge.
*
* @return The blob, used in the calculation of the NTLMv2 Response.
*/
private static byte[] createBlob(byte[] clientChallenge, byte[] targetInformation) {
byte[] blobSignature = new byte[] { (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00 };
byte[] reserved = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
byte[] unknown1 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
long time = System.currentTimeMillis();
time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch.
time *= 10000; // tenths of a microsecond.
// convert to little-endian byte array.
byte[] timestamp = new byte[8];
for (int i = 0; i < 8; i++) {
timestamp[i] = (byte) time;
time >>>= 8;
}
byte[] blob = new byte[blobSignature.length + reserved.length + timestamp.length + 8
+ unknown1.length + targetInformation.length];
int offset = 0;
System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
offset += blobSignature.length;
System.arraycopy(reserved, 0, blob, offset, reserved.length);
offset += reserved.length;
System.arraycopy(timestamp, 0, blob, offset, timestamp.length);
offset += timestamp.length;
System.arraycopy(clientChallenge, 0, blob, offset, 8);
offset += 8;
System.arraycopy(unknown1, 0, blob, offset, unknown1.length);
offset += unknown1.length;
System.arraycopy(targetInformation, 0, blob, offset, targetInformation.length);
return blob;
}
/**
* Creates a DES encryption key from the given key material.
*
* @param bytes
* A byte array containing the DES key material.
* @param offset
* The offset in the given byte array at which the 7-byte key
* material starts.
*
* @return A DES encryption key created from the key material starting at
* the specified offset in the given byte array.
*/
private static Key createDESKey(byte[] bytes, int offset) {
byte[] keyBytes = new byte[7];
System.arraycopy(bytes, offset, keyBytes, 0, 7);
byte[] material = new byte[8];
material[0] = keyBytes[0];
material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1);
material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2);
material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3);
material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4);
material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5);
material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6);
material[7] = (byte) (keyBytes[6] << 1);
oddParity(material);
return new SecretKeySpec(material, "DES");
}
/**
* Applies odd parity to the given byte array.
*
* @param bytes
* The data whose parity bits are to be adjusted for odd parity.
*/
private static void oddParity(byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^ (b >>> 4) ^ (b >>> 3)
^ (b >>> 2) ^ (b >>> 1)) & 0x01) == 0;
if (needsParity) {
bytes[i] |= (byte) 0x01;
} else {
bytes[i] &= (byte) 0xfe;
}
}
}
/** NTLM message generation, base class */
static class NTLMMessage {
/** The current response */
private byte[] messageContents = null;
/** The current output position */
private int currentOutputPosition = 0;
/** Constructor to use when message contents are not yet known */
NTLMMessage() {
}
/** Constructor to use when message contents are known */
NTLMMessage(String messageBody, int expectedType) throws NTLMEngineException {
messageContents = Base64.decodeBase64(EncodingUtils.getBytes(messageBody,
DEFAULT_CHARSET));
// Look for NTLM message
if (messageContents.length < SIGNATURE.length)
throw new NTLMEngineException("NTLM message decoding error - packet too short");
int i = 0;
while (i < SIGNATURE.length) {
if (messageContents[i] != SIGNATURE[i])
throw new NTLMEngineException(
"NTLM message expected - instead got unrecognized bytes");
i++;
}
// Check to be sure there's a type 2 message indicator next
int type = readULong(SIGNATURE.length);
if (type != expectedType)
throw new NTLMEngineException("NTLM type " + Integer.toString(expectedType)
+ " message expected - instead got type " + Integer.toString(type));
currentOutputPosition = messageContents.length;
}
/**
* Get the length of the signature and flags, so calculations can adjust
* offsets accordingly.
*/
protected int getPreambleLength() {
return SIGNATURE.length + 4;
}
/** Get the message length */
protected int getMessageLength() {
return currentOutputPosition;
}
/** Read a byte from a position within the message buffer */
protected byte readByte(int position) throws NTLMEngineException {
if (messageContents.length < position + 1)
throw new NTLMEngineException("NTLM: Message too short");
return messageContents[position];
}
/** Read a bunch of bytes from a position in the message buffer */
protected void readBytes(byte[] buffer, int position) throws NTLMEngineException {
if (messageContents.length < position + buffer.length)
throw new NTLMEngineException("NTLM: Message too short");
System.arraycopy(messageContents, position, buffer, 0, buffer.length);
}
/** Read a ushort from a position within the message buffer */
protected int readUShort(int position) throws NTLMEngineException {
return NTLMEngineImpl.readUShort(messageContents, position);
}
/** Read a ulong from a position within the message buffer */
protected int readULong(int position) throws NTLMEngineException {
return NTLMEngineImpl.readULong(messageContents, position);
}
/** Read a security buffer from a position within the message buffer */
protected byte[] readSecurityBuffer(int position) throws NTLMEngineException {
return NTLMEngineImpl.readSecurityBuffer(messageContents, position);
}
/**
* Prepares the object to create a response of the given length.
*
* @param length
* the maximum length of the response to prepare, not
* including the type and the signature (which this method
* adds).
*/
protected void prepareResponse(int maxlength, int messageType) {
messageContents = new byte[maxlength];
currentOutputPosition = 0;
addBytes(SIGNATURE);
addULong(messageType);
}
/**
* Adds the given byte to the response.
*
* @param b
* the byte to add.
*/
protected void addByte(byte b) {
messageContents[currentOutputPosition] = b;
currentOutputPosition++;
}
/**
* Adds the given bytes to the response.
*
* @param bytes
* the bytes to add.
*/
protected void addBytes(byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
messageContents[currentOutputPosition] = bytes[i];
currentOutputPosition++;
}
}
/** Adds a USHORT to the response */
protected void addUShort(int value) {
addByte((byte) (value & 0xff));
addByte((byte) (value >> 8 & 0xff));
}
/** Adds a ULong to the response */
protected void addULong(int value) {
addByte((byte) (value & 0xff));
addByte((byte) (value >> 8 & 0xff));
addByte((byte) (value >> 16 & 0xff));
addByte((byte) (value >> 24 & 0xff));
}
/**
* Returns the response that has been generated after shrinking the
* array if required and base64 encodes the response.
*
* @return The response as above.
*/
String getResponse() {
byte[] resp;
if (messageContents.length > currentOutputPosition) {
byte[] tmp = new byte[currentOutputPosition];
for (int i = 0; i < currentOutputPosition; i++) {
tmp[i] = messageContents[i];
}
resp = tmp;
} else {
resp = messageContents;
}
return EncodingUtils.getAsciiString(Base64.encodeBase64(resp));
}
}
/** Type 1 message assembly class */
static class Type1Message extends NTLMMessage {
protected byte[] hostBytes;
protected byte[] domainBytes;
/** Constructor. Include the arguments the message will need */
Type1Message(String domain, String host) throws NTLMEngineException {
super();
try {
// Strip off domain name from the host!
host = convertHost(host);
// Use only the base domain name!
domain = convertDomain(domain);
hostBytes = host.getBytes("UnicodeLittleUnmarked");
domainBytes = domain.toUpperCase().getBytes("UnicodeLittleUnmarked");
} catch (java.io.UnsupportedEncodingException e) {
throw new NTLMEngineException("Unicode unsupported: " + e.getMessage(), e);
}
}
/**
* Getting the response involves building the message before returning
* it
*/
@Override
String getResponse() {
// Now, build the message. Calculate its length first, including
// signature or type.
int finalLength = 32 + hostBytes.length + domainBytes.length;
// Set up the response. This will initialize the signature, message
// type, and flags.
prepareResponse(finalLength, 1);
// Flags. These are the complete set of flags we support.
addULong(FLAG_NEGOTIATE_NTLM | FLAG_NEGOTIATE_NTLM2 | FLAG_NEGOTIATE_SIGN
| FLAG_NEGOTIATE_SEAL |
/*
* FLAG_NEGOTIATE_ALWAYS_SIGN | FLAG_NEGOTIATE_KEY_EXCH |
*/
FLAG_UNICODE_ENCODING | FLAG_TARGET_DESIRED | FLAG_NEGOTIATE_128);
// Domain length (two times).
addUShort(domainBytes.length);
addUShort(domainBytes.length);
// Domain offset.
addULong(hostBytes.length + 32);
// Host length (two times).
addUShort(hostBytes.length);
addUShort(hostBytes.length);
// Host offset (always 32).
addULong(32);
// Host String.
addBytes(hostBytes);
// Domain String.
addBytes(domainBytes);
return super.getResponse();
}
}
/** Type 2 message class */
static class Type2Message extends NTLMMessage {
protected byte[] challenge;
protected String target;
protected byte[] targetInfo;
protected int flags;
Type2Message(String message) throws NTLMEngineException {
super(message, 2);
// Parse out the rest of the info we need from the message
// The nonce is the 8 bytes starting from the byte in position 24.
challenge = new byte[8];
readBytes(challenge, 24);
flags = readULong(20);
if ((flags & FLAG_UNICODE_ENCODING) == 0)
throw new NTLMEngineException(
"NTLM type 2 message has flags that make no sense: "
+ Integer.toString(flags));
// Do the target!
target = null;
// The TARGET_DESIRED flag is said to not have understood semantics
// in Type2 messages, so use the length of the packet to decide
// how to proceed instead
if (getMessageLength() >= 12 + 8) {
byte[] bytes = readSecurityBuffer(12);
if (bytes.length != 0) {
try {
target = new String(bytes, "UnicodeLittleUnmarked");
} catch (java.io.UnsupportedEncodingException e) {
throw new NTLMEngineException(e.getMessage(), e);
}
}
}
// Do the target info!
targetInfo = null;
// TARGET_DESIRED flag cannot be relied on, so use packet length
if (getMessageLength() >= 40 + 8) {
byte[] bytes = readSecurityBuffer(40);
if (bytes.length != 0) {
targetInfo = bytes;
}
}
}
/** Retrieve the challenge */
byte[] getChallenge() {
return challenge;
}
/** Retrieve the target */
String getTarget() {
return target;
}
/** Retrieve the target info */
byte[] getTargetInfo() {
return targetInfo;
}
/** Retrieve the response flags */
int getFlags() {
return flags;
}
}
/** Type 3 message assembly class */
static class Type3Message extends NTLMMessage {
// Response flags from the type2 message
protected int type2Flags;
protected byte[] domainBytes;
protected byte[] hostBytes;
protected byte[] userBytes;
protected byte[] lmResp;
protected byte[] ntResp;
/** Constructor. Pass the arguments we will need */
Type3Message(String domain, String host, String user, String password, byte[] nonce,
int type2Flags, String target, byte[] targetInformation)
throws NTLMEngineException {
// Save the flags
this.type2Flags = type2Flags;
// Strip off domain name from the host!
host = convertHost(host);
// Use only the base domain name!
domain = convertDomain(domain);
// Use the new code to calculate the responses, including v2 if that
// seems warranted.
try {
if (targetInformation != null && target != null) {
byte[] clientChallenge = makeRandomChallenge();
ntResp = getNTLMv2Response(target, user, password, nonce, clientChallenge,
targetInformation);
lmResp = getLMv2Response(target, user, password, nonce, clientChallenge);
} else {
if ((type2Flags & FLAG_NEGOTIATE_NTLM2) != 0) {
// NTLM2 session stuff is requested
byte[] clientChallenge = makeNTLM2RandomChallenge();
ntResp = getNTLM2SessionResponse(password, nonce, clientChallenge);
lmResp = clientChallenge;
// All the other flags we send (signing, sealing, key
// exchange) are supported, but they don't do anything
// at all in an
// NTLM2 context! So we're done at this point.
} else {
ntResp = getNTLMResponse(password, nonce);
lmResp = getLMResponse(password, nonce);
}
}
} catch (NTLMEngineException e) {
// This likely means we couldn't find the MD4 hash algorithm -
// fail back to just using LM
ntResp = new byte[0];
lmResp = getLMResponse(password, nonce);
}
try {
domainBytes = domain.toUpperCase().getBytes("UnicodeLittleUnmarked");
hostBytes = host.getBytes("UnicodeLittleUnmarked");
userBytes = user.getBytes("UnicodeLittleUnmarked");
} catch (java.io.UnsupportedEncodingException e) {
throw new NTLMEngineException("Unicode not supported: " + e.getMessage(), e);
}
}
/** Assemble the response */
@Override
String getResponse() {
int ntRespLen = ntResp.length;
int lmRespLen = lmResp.length;
int domainLen = domainBytes.length;
int hostLen = hostBytes.length;
int userLen = userBytes.length;
// Calculate the layout within the packet
int lmRespOffset = 64;
int ntRespOffset = lmRespOffset + lmRespLen;
int domainOffset = ntRespOffset + ntRespLen;
int userOffset = domainOffset + domainLen;
int hostOffset = userOffset + userLen;
int sessionKeyOffset = hostOffset + hostLen;
int finalLength = sessionKeyOffset + 0;
// Start the response. Length includes signature and type
prepareResponse(finalLength, 3);
// LM Resp Length (twice)
addUShort(lmRespLen);
addUShort(lmRespLen);
// LM Resp Offset
addULong(lmRespOffset);
// NT Resp Length (twice)
addUShort(ntRespLen);
addUShort(ntRespLen);
// NT Resp Offset
addULong(ntRespOffset);
// Domain length (twice)
addUShort(domainLen);
addUShort(domainLen);
// Domain offset.
addULong(domainOffset);
// User Length (twice)
addUShort(userLen);
addUShort(userLen);
// User offset
addULong(userOffset);
// Host length (twice)
addUShort(hostLen);
addUShort(hostLen);
// Host offset
addULong(hostOffset);
// 4 bytes of zeros - not sure what this is
addULong(0);
// Message length
addULong(finalLength);
// Flags. Currently: NEGOTIATE_NTLM + UNICODE_ENCODING +
// TARGET_DESIRED + NEGOTIATE_128
addULong(FLAG_NEGOTIATE_NTLM | FLAG_UNICODE_ENCODING | FLAG_TARGET_DESIRED
| FLAG_NEGOTIATE_128 | (type2Flags & FLAG_NEGOTIATE_NTLM2)
| (type2Flags & FLAG_NEGOTIATE_SIGN) | (type2Flags & FLAG_NEGOTIATE_SEAL)
| (type2Flags & FLAG_NEGOTIATE_KEY_EXCH)
| (type2Flags & FLAG_NEGOTIATE_ALWAYS_SIGN));
// Add the actual data
addBytes(lmResp);
addBytes(ntResp);
addBytes(domainBytes);
addBytes(userBytes);
addBytes(hostBytes);
return super.getResponse();
}
}
static void writeULong(byte[] buffer, int value, int offset) {
buffer[offset] = (byte) (value & 0xff);
buffer[offset + 1] = (byte) (value >> 8 & 0xff);
buffer[offset + 2] = (byte) (value >> 16 & 0xff);
buffer[offset + 3] = (byte) (value >> 24 & 0xff);
}
static int F(int x, int y, int z) {
return ((x & y) | (~x & z));
}
static int G(int x, int y, int z) {
return ((x & y) | (x & z) | (y & z));
}
static int H(int x, int y, int z) {
return (x ^ y ^ z);
}
static int rotintlft(int val, int numbits) {
return ((val << numbits) | (val >>> (32 - numbits)));
}
/**
* Cryptography support - MD4. The following class was based loosely on the
* RFC and on code found at http://www.cs.umd.edu/~harry/jotp/src/md.java.
* Code correctness was verified by looking at MD4.java from the jcifs
* library (http://jcifs.samba.org). It was massaged extensively to the
* final form found here by Karl Wright (kwright@metacarta.com).
*/
static class MD4 {
protected int A = 0x67452301;
protected int B = 0xefcdab89;
protected int C = 0x98badcfe;
protected int D = 0x10325476;
protected long count = 0L;
protected byte[] dataBuffer = new byte[64];
MD4() {
}
void update(byte[] input) {
// We always deal with 512 bits at a time. Correspondingly, there is
// a buffer 64 bytes long that we write data into until it gets
// full.
int curBufferPos = (int) (count & 63L);
int inputIndex = 0;
while (input.length - inputIndex + curBufferPos >= dataBuffer.length) {
// We have enough data to do the next step. Do a partial copy
// and a transform, updating inputIndex and curBufferPos
// accordingly
int transferAmt = dataBuffer.length - curBufferPos;
System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt);
count += transferAmt;
curBufferPos = 0;
inputIndex += transferAmt;
processBuffer();
}
// If there's anything left, copy it into the buffer and leave it.
// We know there's not enough left to process.
if (inputIndex < input.length) {
int transferAmt = input.length - inputIndex;
System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt);
count += transferAmt;
curBufferPos += transferAmt;
}
}
byte[] getOutput() {
// Feed pad/length data into engine. This must round out the input
// to a multiple of 512 bits.
int bufferIndex = (int) (count & 63L);
int padLen = (bufferIndex < 56) ? (56 - bufferIndex) : (120 - bufferIndex);
byte[] postBytes = new byte[padLen + 8];
// Leading 0x80, specified amount of zero padding, then length in
// bits.
postBytes[0] = (byte) 0x80;
// Fill out the last 8 bytes with the length
for (int i = 0; i < 8; i++) {
postBytes[padLen + i] = (byte) ((count * 8) >>> (8 * i));
}
// Update the engine
update(postBytes);
// Calculate final result
byte[] result = new byte[16];
writeULong(result, A, 0);
writeULong(result, B, 4);
writeULong(result, C, 8);
writeULong(result, D, 12);
return result;
}
protected void processBuffer() {
// Convert current buffer to 16 ulongs
int[] d = new int[16];
for (int i = 0; i < 16; i++) {
d[i] = (dataBuffer[i * 4] & 0xff) + ((dataBuffer[i * 4 + 1] & 0xff) << 8)
+ ((dataBuffer[i * 4 + 2] & 0xff) << 16)
+ ((dataBuffer[i * 4 + 3] & 0xff) << 24);
}
// Do a round of processing
int AA = A;
int BB = B;
int CC = C;
int DD = D;
round1(d);
round2(d);
round3(d);
A += AA;
B += BB;
C += CC;
D += DD;
}
protected void round1(int[] d) {
A = rotintlft((A + F(B, C, D) + d[0]), 3);
D = rotintlft((D + F(A, B, C) + d[1]), 7);
C = rotintlft((C + F(D, A, B) + d[2]), 11);
B = rotintlft((B + F(C, D, A) + d[3]), 19);
A = rotintlft((A + F(B, C, D) + d[4]), 3);
D = rotintlft((D + F(A, B, C) + d[5]), 7);
C = rotintlft((C + F(D, A, B) + d[6]), 11);
B = rotintlft((B + F(C, D, A) + d[7]), 19);
A = rotintlft((A + F(B, C, D) + d[8]), 3);
D = rotintlft((D + F(A, B, C) + d[9]), 7);
C = rotintlft((C + F(D, A, B) + d[10]), 11);
B = rotintlft((B + F(C, D, A) + d[11]), 19);
A = rotintlft((A + F(B, C, D) + d[12]), 3);
D = rotintlft((D + F(A, B, C) + d[13]), 7);
C = rotintlft((C + F(D, A, B) + d[14]), 11);
B = rotintlft((B + F(C, D, A) + d[15]), 19);
}
protected void round2(int[] d) {
A = rotintlft((A + G(B, C, D) + d[0] + 0x5a827999), 3);
D = rotintlft((D + G(A, B, C) + d[4] + 0x5a827999), 5);
C = rotintlft((C + G(D, A, B) + d[8] + 0x5a827999), 9);
B = rotintlft((B + G(C, D, A) + d[12] + 0x5a827999), 13);
A = rotintlft((A + G(B, C, D) + d[1] + 0x5a827999), 3);
D = rotintlft((D + G(A, B, C) + d[5] + 0x5a827999), 5);
C = rotintlft((C + G(D, A, B) + d[9] + 0x5a827999), 9);
B = rotintlft((B + G(C, D, A) + d[13] + 0x5a827999), 13);
A = rotintlft((A + G(B, C, D) + d[2] + 0x5a827999), 3);
D = rotintlft((D + G(A, B, C) + d[6] + 0x5a827999), 5);
C = rotintlft((C + G(D, A, B) + d[10] + 0x5a827999), 9);
B = rotintlft((B + G(C, D, A) + d[14] + 0x5a827999), 13);
A = rotintlft((A + G(B, C, D) + d[3] + 0x5a827999), 3);
D = rotintlft((D + G(A, B, C) + d[7] + 0x5a827999), 5);
C = rotintlft((C + G(D, A, B) + d[11] + 0x5a827999), 9);
B = rotintlft((B + G(C, D, A) + d[15] + 0x5a827999), 13);
}
protected void round3(int[] d) {
A = rotintlft((A + H(B, C, D) + d[0] + 0x6ed9eba1), 3);
D = rotintlft((D + H(A, B, C) + d[8] + 0x6ed9eba1), 9);
C = rotintlft((C + H(D, A, B) + d[4] + 0x6ed9eba1), 11);
B = rotintlft((B + H(C, D, A) + d[12] + 0x6ed9eba1), 15);
A = rotintlft((A + H(B, C, D) + d[2] + 0x6ed9eba1), 3);
D = rotintlft((D + H(A, B, C) + d[10] + 0x6ed9eba1), 9);
C = rotintlft((C + H(D, A, B) + d[6] + 0x6ed9eba1), 11);
B = rotintlft((B + H(C, D, A) + d[14] + 0x6ed9eba1), 15);
A = rotintlft((A + H(B, C, D) + d[1] + 0x6ed9eba1), 3);
D = rotintlft((D + H(A, B, C) + d[9] + 0x6ed9eba1), 9);
C = rotintlft((C + H(D, A, B) + d[5] + 0x6ed9eba1), 11);
B = rotintlft((B + H(C, D, A) + d[13] + 0x6ed9eba1), 15);
A = rotintlft((A + H(B, C, D) + d[3] + 0x6ed9eba1), 3);
D = rotintlft((D + H(A, B, C) + d[11] + 0x6ed9eba1), 9);
C = rotintlft((C + H(D, A, B) + d[7] + 0x6ed9eba1), 11);
B = rotintlft((B + H(C, D, A) + d[15] + 0x6ed9eba1), 15);
}
}
/**
* Cryptography support - HMACMD5 - algorithmically based on various web
* resources by Karl Wright
*/
static class HMACMD5 {
protected byte[] ipad;
protected byte[] opad;
protected MessageDigest md5;
HMACMD5(byte[] key) throws NTLMEngineException {
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception ex) {
// Umm, the algorithm doesn't exist - throw an
// NTLMEngineException!
throw new NTLMEngineException(
"Error getting md5 message digest implementation: " + ex.getMessage(), ex);
}
// Initialize the pad buffers with the key
ipad = new byte[64];
opad = new byte[64];
int keyLength = key.length;
if (keyLength > 64) {
// Use MD5 of the key instead, as described in RFC 2104
md5.update(key);
key = md5.digest();
keyLength = key.length;
}
int i = 0;
while (i < keyLength) {
ipad[i] = (byte) (key[i] ^ (byte) 0x36);
opad[i] = (byte) (key[i] ^ (byte) 0x5c);
i++;
}
while (i < 64) {
ipad[i] = (byte) 0x36;
opad[i] = (byte) 0x5c;
i++;
}
// Very important: update the digest with the ipad buffer
md5.reset();
md5.update(ipad);
}
/** Grab the current digest. This is the "answer". */
byte[] getOutput() {
byte[] digest = md5.digest();
md5.update(opad);
return md5.digest(digest);
}
/** Update by adding a complete array */
void update(byte[] input) {
md5.update(input);
}
/** Update the algorithm */
void update(byte[] input, int offset, int length) {
md5.update(input, offset, length);
}
}
public String generateType1Msg(
final String domain,
final String workstation) throws NTLMEngineException {
return getType1Message(workstation, domain);
}
public String generateType3Msg(
final String username,
final String password,
final String domain,
final String workstation,
final String challenge) throws NTLMEngineException {
Type2Message t2m = new Type2Message(challenge);
return getType3Message(
username,
password,
workstation,
domain,
t2m.getChallenge(),
t2m.getFlags(),
t2m.getTarget(),
t2m.getTargetInfo());
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthSchemeFactory;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link AuthSchemeFactory} implementation that creates and initializes
* {@link NTLMScheme} instances configured to use the default {@link NTLMEngine}
* implementation.
*
* @since 4.1
*/
@Immutable
public class NTLMSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
return new NTLMScheme(new NTLMEngineImpl());
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.impl.auth;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.auth.AuthenticationException;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) authentication
* scheme.
*
* @since 4.1
*/
public class NegotiateScheme extends AuthSchemeBase {
enum State {
UNINITIATED,
CHALLENGE_RECEIVED,
TOKEN_GENERATED,
FAILED,
}
private final Log log = LogFactory.getLog(getClass());
/** Authentication process state */
private State state;
/**
* Default constructor for the Negotiate authentication scheme.
*
*/
public NegotiateScheme(final SpnegoTokenGenerator spengoGenerator, boolean stripPort) {
super();
this.state = State.UNINITIATED;
}
public NegotiateScheme(final SpnegoTokenGenerator spengoGenerator) {
this(spengoGenerator, false);
}
public NegotiateScheme() {
this(null, false);
}
/**
* Tests if the Negotiate authentication process has been completed.
*
* @return <tt>true</tt> if authorization has been processed,
* <tt>false</tt> otherwise.
*
*/
public boolean isComplete() {
return this.state == State.TOKEN_GENERATED || this.state == State.FAILED;
}
/**
* Returns textual designation of the Negotiate authentication scheme.
*
* @return <code>Negotiate</code>
*/
public String getSchemeName() {
return "Negotiate";
}
@Deprecated
public Header authenticate(
final Credentials credentials,
final HttpRequest request) throws AuthenticationException {
return authenticate(credentials, request, null);
}
/**
* Produces Negotiate authorization Header based on token created by
* processChallenge.
*
* @param credentials Never used be the Negotiate scheme but must be provided to
* satisfy common-httpclient API. Credentials from JAAS will be used instead.
* @param request The request being authenticated
*
* @throws AuthenticationException if authorisation string cannot
* be generated due to an authentication failure
*
* @return an Negotiate authorisation Header
*/
@Override
public Header authenticate(
final Credentials credentials,
final HttpRequest request,
final HttpContext context) throws AuthenticationException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (state != State.CHALLENGE_RECEIVED) {
throw new IllegalStateException(
"Negotiation authentication process has not been initiated");
}
state = State.FAILED;
throw new AuthenticationException();
}
/**
* Returns the authentication parameter with the given name, if available.
*
* <p>There are no valid parameters for Negotiate authentication so this
* method always returns <tt>null</tt>.</p>
*
* @param name The name of the parameter to be returned
*
* @return the parameter with the given name
*/
public String getParameter(String name) {
if (name == null) {
throw new IllegalArgumentException("Parameter name may not be null");
}
return null;
}
/**
* The concept of an authentication realm is not supported by the Negotiate
* authentication scheme. Always returns <code>null</code>.
*
* @return <code>null</code>
*/
public String getRealm() {
return null;
}
/**
* Returns <tt>true</tt>.
* Negotiate authentication scheme is connection based.
*
* @return <tt>true</tt>.
*/
public boolean isConnectionBased() {
return true;
}
@Override
protected void parseChallenge(
final CharArrayBuffer buffer,
int beginIndex, int endIndex) throws MalformedChallengeException {
String challenge = buffer.substringTrimmed(beginIndex, endIndex);
if (log.isDebugEnabled()) {
log.debug("Received challenge '" + challenge + "' from the auth server");
}
log.debug("Authentication already attempted");
state = State.FAILED;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthSchemeFactory;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link AuthSchemeFactory} implementation that creates and initializes
* {@link DigestScheme} instances.
*
* @since 4.0
*/
@Immutable
public class DigestSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
return new DigestScheme();
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.auth.AuthenticationException;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.auth.params.AuthParams;
import org.apache.ogt.http.message.BasicHeaderValueFormatter;
import org.apache.ogt.http.message.BasicNameValuePair;
import org.apache.ogt.http.message.BufferedHeader;
import org.apache.ogt.http.util.CharArrayBuffer;
import org.apache.ogt.http.util.EncodingUtils;
/**
* Digest authentication scheme as defined in RFC 2617.
* Both MD5 (default) and MD5-sess are supported.
* Currently only qop=auth or no qop is supported. qop=auth-int
* is unsupported. If auth and auth-int are provided, auth is
* used.
* <p>
* Credential charset is configured via the
* {@link org.apache.ogt.http.auth.params.AuthPNames#CREDENTIAL_CHARSET}
* parameter of the HTTP request.
* <p>
* Since the digest username is included as clear text in the generated
* Authentication header, the charset of the username must be compatible
* with the
* {@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET
* http element charset}.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.auth.params.AuthPNames#CREDENTIAL_CHARSET}</li>
* </ul>
*
* @since 4.0
*/
@NotThreadSafe
public class DigestScheme extends RFC2617Scheme {
/**
* Hexa values used when creating 32 character long digest in HTTP DigestScheme
* in case of authentication.
*
* @see #encode(byte[])
*/
private static final char[] HEXADECIMAL = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f'
};
/** Whether the digest authentication process is complete */
private boolean complete;
private static final int QOP_MISSING = 0;
private static final int QOP_AUTH_INT = 1;
private static final int QOP_AUTH = 2;
private int qopVariant = QOP_MISSING;
private String lastNonce;
private long nounceCount;
private String cnonce;
private String nc;
/**
* Default constructor for the digest authetication scheme.
*/
public DigestScheme() {
super();
this.complete = false;
}
/**
* Processes the Digest challenge.
*
* @param header the challenge header
*
* @throws MalformedChallengeException is thrown if the authentication challenge
* is malformed
*/
@Override
public void processChallenge(
final Header header) throws MalformedChallengeException {
super.processChallenge(header);
if (getParameter("realm") == null) {
throw new MalformedChallengeException("missing realm in challange");
}
if (getParameter("nonce") == null) {
throw new MalformedChallengeException("missing nonce in challange");
}
boolean unsupportedQop = false;
// qop parsing
String qop = getParameter("qop");
if (qop != null) {
StringTokenizer tok = new StringTokenizer(qop,",");
while (tok.hasMoreTokens()) {
String variant = tok.nextToken().trim();
if (variant.equals("auth")) {
qopVariant = QOP_AUTH;
break; //that's our favourite, because auth-int is unsupported
} else if (variant.equals("auth-int")) {
qopVariant = QOP_AUTH_INT;
} else {
unsupportedQop = true;
}
}
}
if (unsupportedQop && (qopVariant == QOP_MISSING)) {
throw new MalformedChallengeException("None of the qop methods is supported");
}
this.complete = true;
}
/**
* Tests if the Digest authentication process has been completed.
*
* @return <tt>true</tt> if Digest authorization has been processed,
* <tt>false</tt> otherwise.
*/
public boolean isComplete() {
String s = getParameter("stale");
if ("true".equalsIgnoreCase(s)) {
return false;
} else {
return this.complete;
}
}
/**
* Returns textual designation of the digest authentication scheme.
*
* @return <code>digest</code>
*/
public String getSchemeName() {
return "digest";
}
/**
* Returns <tt>false</tt>. Digest authentication scheme is request based.
*
* @return <tt>false</tt>.
*/
public boolean isConnectionBased() {
return false;
}
public void overrideParamter(final String name, final String value) {
getParameters().put(name, value);
}
private String getCnonce() {
if (this.cnonce == null) {
this.cnonce = createCnonce();
}
return this.cnonce;
}
private String getNc() {
if (this.nc == null) {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("%08x", this.nounceCount);
this.nc = sb.toString();
}
return this.nc;
}
/**
* Produces a digest authorization string for the given set of
* {@link Credentials}, method name and URI.
*
* @param credentials A set of credentials to be used for athentication
* @param request The request being authenticated
*
* @throws org.apache.ogt.http.auth.InvalidCredentialsException if authentication credentials
* are not valid or not applicable for this authentication scheme
* @throws AuthenticationException if authorization string cannot
* be generated due to an authentication failure
*
* @return a digest authorization string
*/
public Header authenticate(
final Credentials credentials,
final HttpRequest request) throws AuthenticationException {
if (credentials == null) {
throw new IllegalArgumentException("Credentials may not be null");
}
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
// Add method name and request-URI to the parameter map
getParameters().put("methodname", request.getRequestLine().getMethod());
getParameters().put("uri", request.getRequestLine().getUri());
String charset = getParameter("charset");
if (charset == null) {
charset = AuthParams.getCredentialCharset(request.getParams());
getParameters().put("charset", charset);
}
String digest = createDigest(credentials);
return createDigestHeader(credentials, digest);
}
private static MessageDigest createMessageDigest(
final String digAlg) throws UnsupportedDigestAlgorithmException {
try {
return MessageDigest.getInstance(digAlg);
} catch (Exception e) {
throw new UnsupportedDigestAlgorithmException(
"Unsupported algorithm in HTTP Digest authentication: "
+ digAlg);
}
}
/**
* Creates an MD5 response digest.
*
* @return The created digest as string. This will be the response tag's
* value in the Authentication HTTP header.
* @throws AuthenticationException when MD5 is an unsupported algorithm
*/
private String createDigest(final Credentials credentials) throws AuthenticationException {
// Collecting required tokens
String uri = getParameter("uri");
String realm = getParameter("realm");
String nonce = getParameter("nonce");
String method = getParameter("methodname");
String algorithm = getParameter("algorithm");
if (uri == null) {
throw new IllegalStateException("URI may not be null");
}
if (realm == null) {
throw new IllegalStateException("Realm may not be null");
}
if (nonce == null) {
throw new IllegalStateException("Nonce may not be null");
}
// Reset
this.cnonce = null;
this.nc = null;
// If an algorithm is not specified, default to MD5.
if (algorithm == null) {
algorithm = "MD5";
}
// If an charset is not specified, default to ISO-8859-1.
String charset = getParameter("charset");
if (charset == null) {
charset = "ISO-8859-1";
}
if (qopVariant == QOP_AUTH_INT) {
throw new AuthenticationException(
"Unsupported qop in HTTP Digest authentication");
}
String digAlg = algorithm;
if (digAlg.equalsIgnoreCase("MD5-sess")) {
digAlg = "MD5";
}
if (nonce.equals(this.lastNonce)) {
this.nounceCount++;
} else {
this.nounceCount = 1;
this.lastNonce = nonce;
}
MessageDigest digester = createMessageDigest(digAlg);
String uname = credentials.getUserPrincipal().getName();
String pwd = credentials.getPassword();
// 3.2.2.2: Calculating digest
StringBuilder tmp = new StringBuilder(uname.length() + realm.length() + pwd.length() + 2);
tmp.append(uname);
tmp.append(':');
tmp.append(realm);
tmp.append(':');
tmp.append(pwd);
// unq(username-value) ":" unq(realm-value) ":" passwd
String a1 = tmp.toString();
//a1 is suitable for MD5 algorithm
if (algorithm.equalsIgnoreCase("MD5-sess")) {
// H( unq(username-value) ":" unq(realm-value) ":" passwd )
// ":" unq(nonce-value)
// ":" unq(cnonce-value)
algorithm = "MD5";
String cnonce = getCnonce();
String tmp2 = encode(digester.digest(EncodingUtils.getBytes(a1, charset)));
StringBuilder tmp3 = new StringBuilder(
tmp2.length() + nonce.length() + cnonce.length() + 2);
tmp3.append(tmp2);
tmp3.append(':');
tmp3.append(nonce);
tmp3.append(':');
tmp3.append(cnonce);
a1 = tmp3.toString();
}
String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset)));
String a2 = null;
if (qopVariant == QOP_AUTH_INT) {
// Unhandled qop auth-int
//we do not have access to the entity-body or its hash
//TODO: add Method ":" digest-uri-value ":" H(entity-body)
} else {
a2 = method + ':' + uri;
}
String hasha2 = encode(digester.digest(EncodingUtils.getAsciiBytes(a2)));
// 3.2.2.1
String serverDigestValue;
if (qopVariant == QOP_MISSING) {
StringBuilder tmp2 = new StringBuilder(
hasha1.length() + nonce.length() + hasha1.length());
tmp2.append(hasha1);
tmp2.append(':');
tmp2.append(nonce);
tmp2.append(':');
tmp2.append(hasha2);
serverDigestValue = tmp2.toString();
} else {
String qopOption = getQopVariantString();
String cnonce = getCnonce();
String nc = getNc();
StringBuilder tmp2 = new StringBuilder(hasha1.length() + nonce.length()
+ nc.length() + cnonce.length() + qopOption.length() + hasha2.length() + 5);
tmp2.append(hasha1);
tmp2.append(':');
tmp2.append(nonce);
tmp2.append(':');
tmp2.append(nc);
tmp2.append(':');
tmp2.append(cnonce);
tmp2.append(':');
tmp2.append(qopOption);
tmp2.append(':');
tmp2.append(hasha2);
serverDigestValue = tmp2.toString();
}
String serverDigest =
encode(digester.digest(EncodingUtils.getAsciiBytes(serverDigestValue)));
return serverDigest;
}
/**
* Creates digest-response header as defined in RFC2617.
*
* @param credentials User credentials
* @param digest The response tag's value as String.
*
* @return The digest-response as String.
*/
private Header createDigestHeader(
final Credentials credentials,
final String digest) {
CharArrayBuffer buffer = new CharArrayBuffer(128);
if (isProxy()) {
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": Digest ");
String uri = getParameter("uri");
String realm = getParameter("realm");
String nonce = getParameter("nonce");
String opaque = getParameter("opaque");
String response = digest;
String algorithm = getParameter("algorithm");
String uname = credentials.getUserPrincipal().getName();
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20);
params.add(new BasicNameValuePair("username", uname));
params.add(new BasicNameValuePair("realm", realm));
params.add(new BasicNameValuePair("nonce", nonce));
params.add(new BasicNameValuePair("uri", uri));
params.add(new BasicNameValuePair("response", response));
if (qopVariant != QOP_MISSING) {
params.add(new BasicNameValuePair("qop", getQopVariantString()));
params.add(new BasicNameValuePair("nc", getNc()));
params.add(new BasicNameValuePair("cnonce", getCnonce()));
}
if (algorithm != null) {
params.add(new BasicNameValuePair("algorithm", algorithm));
}
if (opaque != null) {
params.add(new BasicNameValuePair("opaque", opaque));
}
for (int i = 0; i < params.size(); i++) {
BasicNameValuePair param = params.get(i);
if (i > 0) {
buffer.append(", ");
}
boolean noQuotes = "nc".equals(param.getName()) ||
"qop".equals(param.getName());
BasicHeaderValueFormatter.DEFAULT
.formatNameValuePair(buffer, param, !noQuotes);
}
return new BufferedHeader(buffer);
}
private String getQopVariantString() {
String qopOption;
if (qopVariant == QOP_AUTH_INT) {
qopOption = "auth-int";
} else {
qopOption = "auth";
}
return qopOption;
}
/**
* Encodes the 128 bit (16 bytes) MD5 digest into a 32 characters long
* <CODE>String</CODE> according to RFC 2617.
*
* @param binaryData array containing the digest
* @return encoded MD5, or <CODE>null</CODE> if encoding failed
*/
private static String encode(byte[] binaryData) {
int n = binaryData.length;
char[] buffer = new char[n * 2];
for (int i = 0; i < n; i++) {
int low = (binaryData[i] & 0x0f);
int high = ((binaryData[i] & 0xf0) >> 4);
buffer[i * 2] = HEXADECIMAL[high];
buffer[(i * 2) + 1] = HEXADECIMAL[low];
}
return new String(buffer);
}
/**
* Creates a random cnonce value based on the current time.
*
* @return The cnonce value as String.
* @throws UnsupportedDigestAlgorithmException if MD5 algorithm is not supported.
*/
public static String createCnonce() {
String cnonce;
MessageDigest md5Helper = createMessageDigest("MD5");
cnonce = Long.toString(System.currentTimeMillis());
cnonce = encode(md5Helper.digest(EncodingUtils.getAsciiBytes(cnonce)));
return cnonce;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.auth.AuthenticationException;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.auth.InvalidCredentialsException;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.auth.NTCredentials;
import org.apache.ogt.http.impl.auth.AuthSchemeBase;
import org.apache.ogt.http.message.BufferedHeader;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* NTLM is a proprietary authentication scheme developed by Microsoft
* and optimized for Windows platforms.
*
* @since 4.0
*/
@NotThreadSafe
public class NTLMScheme extends AuthSchemeBase {
enum State {
UNINITIATED,
CHALLENGE_RECEIVED,
MSG_TYPE1_GENERATED,
MSG_TYPE2_RECEVIED,
MSG_TYPE3_GENERATED,
FAILED,
}
private final NTLMEngine engine;
private State state;
private String challenge;
public NTLMScheme(final NTLMEngine engine) {
super();
if (engine == null) {
throw new IllegalArgumentException("NTLM engine may not be null");
}
this.engine = engine;
this.state = State.UNINITIATED;
this.challenge = null;
}
public String getSchemeName() {
return "ntlm";
}
public String getParameter(String name) {
// String parameters not supported
return null;
}
public String getRealm() {
// NTLM does not support the concept of an authentication realm
return null;
}
public boolean isConnectionBased() {
return true;
}
@Override
protected void parseChallenge(
final CharArrayBuffer buffer,
int beginIndex, int endIndex) throws MalformedChallengeException {
String challenge = buffer.substringTrimmed(beginIndex, endIndex);
if (challenge.length() == 0) {
if (this.state == State.UNINITIATED) {
this.state = State.CHALLENGE_RECEIVED;
} else {
this.state = State.FAILED;
}
this.challenge = null;
} else {
this.state = State.MSG_TYPE2_RECEVIED;
this.challenge = challenge;
}
}
public Header authenticate(
final Credentials credentials,
final HttpRequest request) throws AuthenticationException {
NTCredentials ntcredentials = null;
try {
ntcredentials = (NTCredentials) credentials;
} catch (ClassCastException e) {
throw new InvalidCredentialsException(
"Credentials cannot be used for NTLM authentication: "
+ credentials.getClass().getName());
}
String response = null;
if (this.state == State.CHALLENGE_RECEIVED || this.state == State.FAILED) {
response = this.engine.generateType1Msg(
ntcredentials.getDomain(),
ntcredentials.getWorkstation());
this.state = State.MSG_TYPE1_GENERATED;
} else if (this.state == State.MSG_TYPE2_RECEVIED) {
response = this.engine.generateType3Msg(
ntcredentials.getUserName(),
ntcredentials.getPassword(),
ntcredentials.getDomain(),
ntcredentials.getWorkstation(),
this.challenge);
this.state = State.MSG_TYPE3_GENERATED;
} else {
throw new AuthenticationException("Unexpected state: " + this.state);
}
CharArrayBuffer buffer = new CharArrayBuffer(32);
if (isProxy()) {
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": NTLM ");
buffer.append(response);
return new BufferedHeader(buffer);
}
public boolean isComplete() {
return this.state == State.MSG_TYPE3_GENERATED || this.state == State.FAILED;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.commons.codec.binary.Base64;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.auth.AuthenticationException;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.auth.InvalidCredentialsException;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.auth.params.AuthParams;
import org.apache.ogt.http.message.BufferedHeader;
import org.apache.ogt.http.util.CharArrayBuffer;
import org.apache.ogt.http.util.EncodingUtils;
/**
* Basic authentication scheme as defined in RFC 2617.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.auth.params.AuthPNames#CREDENTIAL_CHARSET}</li>
* </ul>
*
* @since 4.0
*/
@NotThreadSafe
public class BasicScheme extends RFC2617Scheme {
/** Whether the basic authentication process is complete */
private boolean complete;
/**
* Default constructor for the basic authentication scheme.
*/
public BasicScheme() {
super();
this.complete = false;
}
/**
* Returns textual designation of the basic authentication scheme.
*
* @return <code>basic</code>
*/
public String getSchemeName() {
return "basic";
}
/**
* Processes the Basic challenge.
*
* @param header the challenge header
*
* @throws MalformedChallengeException is thrown if the authentication challenge
* is malformed
*/
@Override
public void processChallenge(
final Header header) throws MalformedChallengeException {
super.processChallenge(header);
this.complete = true;
}
/**
* Tests if the Basic authentication process has been completed.
*
* @return <tt>true</tt> if Basic authorization has been processed,
* <tt>false</tt> otherwise.
*/
public boolean isComplete() {
return this.complete;
}
/**
* Returns <tt>false</tt>. Basic authentication scheme is request based.
*
* @return <tt>false</tt>.
*/
public boolean isConnectionBased() {
return false;
}
/**
* Produces basic authorization header for the given set of {@link Credentials}.
*
* @param credentials The set of credentials to be used for authentication
* @param request The request being authenticated
* @throws InvalidCredentialsException if authentication credentials are not
* valid or not applicable for this authentication scheme
* @throws AuthenticationException if authorization string cannot
* be generated due to an authentication failure
*
* @return a basic authorization string
*/
public Header authenticate(
final Credentials credentials,
final HttpRequest request) throws AuthenticationException {
if (credentials == null) {
throw new IllegalArgumentException("Credentials may not be null");
}
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
String charset = AuthParams.getCredentialCharset(request.getParams());
return authenticate(credentials, charset, isProxy());
}
/**
* Returns a basic <tt>Authorization</tt> header value for the given
* {@link Credentials} and charset.
*
* @param credentials The credentials to encode.
* @param charset The charset to use for encoding the credentials
*
* @return a basic authorization header
*/
public static Header authenticate(
final Credentials credentials,
final String charset,
boolean proxy) {
if (credentials == null) {
throw new IllegalArgumentException("Credentials may not be null");
}
if (charset == null) {
throw new IllegalArgumentException("charset may not be null");
}
StringBuilder tmp = new StringBuilder();
tmp.append(credentials.getUserPrincipal().getName());
tmp.append(":");
tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());
byte[] base64password = Base64.encodeBase64(
EncodingUtils.getBytes(tmp.toString(), charset));
CharArrayBuffer buffer = new CharArrayBuffer(32);
if (proxy) {
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": Basic ");
buffer.append(base64password, 0, base64password.length);
return new BufferedHeader(buffer);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.message.BasicHeaderValueParser;
import org.apache.ogt.http.message.HeaderValueParser;
import org.apache.ogt.http.message.ParserCursor;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Abstract authentication scheme class that lays foundation for all
* RFC 2617 compliant authentication schemes and provides capabilities common
* to all authentication schemes defined in RFC 2617.
*
* @since 4.0
*/
@NotThreadSafe // AuthSchemeBase, params
public abstract class RFC2617Scheme extends AuthSchemeBase {
/**
* Authentication parameter map.
*/
private Map<String, String> params;
/**
* Default constructor for RFC2617 compliant authentication schemes.
*/
public RFC2617Scheme() {
super();
}
@Override
protected void parseChallenge(
final CharArrayBuffer buffer, int pos, int len) throws MalformedChallengeException {
HeaderValueParser parser = BasicHeaderValueParser.DEFAULT;
ParserCursor cursor = new ParserCursor(pos, buffer.length());
HeaderElement[] elements = parser.parseElements(buffer, cursor);
if (elements.length == 0) {
throw new MalformedChallengeException("Authentication challenge is empty");
}
this.params = new HashMap<String, String>(elements.length);
for (HeaderElement element : elements) {
this.params.put(element.getName(), element.getValue());
}
}
/**
* Returns authentication parameters map. Keys in the map are lower-cased.
*
* @return the map of authentication parameters
*/
protected Map<String, String> getParameters() {
if (this.params == null) {
this.params = new HashMap<String, String>();
}
return this.params;
}
/**
* Returns authentication parameter with the given name, if available.
*
* @param name The name of the parameter to be returned
*
* @return the parameter with the given name
*/
public String getParameter(final String name) {
if (name == null) {
throw new IllegalArgumentException("Parameter name may not be null");
}
if (this.params == null) {
return null;
}
return this.params.get(name.toLowerCase(Locale.ENGLISH));
}
/**
* Returns authentication realm. The realm may not be null.
*
* @return the authentication realm
*/
public String getRealm() {
return getParameter("realm");
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import java.io.IOException;
/**
* Abstract SPNEGO token generator. Implementations should take an Kerberos ticket and transform
* into a SPNEGO token.
* <p>
* Implementations of this interface are expected to be thread-safe.
*
* @since 4.1
*/
public interface SpnegoTokenGenerator {
byte [] generateSpnegoDERObject(byte [] kerberosTicket) throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthSchemeFactory;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link AuthSchemeFactory} implementation that creates and initializes
* {@link BasicScheme} instances.
*
* @since 4.0
*/
@Immutable
public class BasicSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
return new BasicScheme();
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.annotation.Immutable;
/**
* Authentication credentials required to respond to a authentication
* challenge are invalid
*
*
* @since 4.0
*/
@Immutable
public class UnsupportedDigestAlgorithmException extends RuntimeException {
private static final long serialVersionUID = 319558534317118022L;
/**
* Creates a new UnsupportedAuthAlgoritmException with a <tt>null</tt> detail message.
*/
public UnsupportedDigestAlgorithmException() {
super();
}
/**
* Creates a new UnsupportedAuthAlgoritmException with the specified message.
*
* @param message the exception detail message
*/
public UnsupportedDigestAlgorithmException(String message) {
super(message);
}
/**
* Creates a new UnsupportedAuthAlgoritmException 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 UnsupportedDigestAlgorithmException(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.impl.auth;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AuthenticationException;
/**
* Signals NTLM protocol failure.
*
*
* @since 4.0
*/
@Immutable
public class NTLMEngineException extends AuthenticationException {
private static final long serialVersionUID = 6027981323731768824L;
public NTLMEngineException() {
super();
}
/**
* Creates a new NTLMEngineException with the specified message.
*
* @param message the exception detail message
*/
public NTLMEngineException(String message) {
super(message);
}
/**
* Creates a new NTLMEngineException 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 NTLMEngineException(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.impl.auth;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthSchemeFactory;
import org.apache.ogt.http.params.HttpParams;
/**
* SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) authentication
* scheme factory.
*
* @since 4.1
*/
@Immutable
public class NegotiateSchemeFactory implements AuthSchemeFactory {
private final SpnegoTokenGenerator spengoGenerator;
private final boolean stripPort;
public NegotiateSchemeFactory(final SpnegoTokenGenerator spengoGenerator, boolean stripPort) {
super();
this.spengoGenerator = spengoGenerator;
this.stripPort = stripPort;
}
public NegotiateSchemeFactory(final SpnegoTokenGenerator spengoGenerator) {
this(spengoGenerator, false);
}
public NegotiateSchemeFactory() {
this(null, false);
}
public AuthScheme newInstance(final HttpParams params) {
return new NegotiateScheme(this.spengoGenerator, this.stripPort);
}
public boolean isStripPort() {
return stripPort;
}
public SpnegoTokenGenerator getSpengoGenerator() {
return spengoGenerator;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.FormattedHeader;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.auth.AUTH;
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.auth.MalformedChallengeException;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Abstract authentication scheme class that serves as a basis
* for all authentication schemes supported by HttpClient. This class
* defines the generic way of parsing an authentication challenge. It
* does not make any assumptions regarding the format of the challenge
* nor does it impose any specific way of responding to that challenge.
*
*
* @since 4.0
*/
@NotThreadSafe // proxy
public abstract class AuthSchemeBase implements ContextAwareAuthScheme {
/**
* Flag whether authenticating against a proxy.
*/
private boolean proxy;
public AuthSchemeBase() {
super();
}
/**
* Processes the given challenge token. Some authentication schemes
* may involve multiple challenge-response exchanges. Such schemes must be able
* to maintain the state information when dealing with sequential challenges
*
* @param header the challenge header
*
* @throws MalformedChallengeException is thrown if the authentication challenge
* is malformed
*/
public void processChallenge(final Header header) throws MalformedChallengeException {
if (header == null) {
throw new IllegalArgumentException("Header may not be null");
}
String authheader = header.getName();
if (authheader.equalsIgnoreCase(AUTH.WWW_AUTH)) {
this.proxy = false;
} else if (authheader.equalsIgnoreCase(AUTH.PROXY_AUTH)) {
this.proxy = true;
} else {
throw new MalformedChallengeException("Unexpected header name: " + authheader);
}
CharArrayBuffer buffer;
int pos;
if (header instanceof FormattedHeader) {
buffer = ((FormattedHeader) header).getBuffer();
pos = ((FormattedHeader) header).getValuePos();
} else {
String s = header.getValue();
if (s == null) {
throw new MalformedChallengeException("Header value is null");
}
buffer = new CharArrayBuffer(s.length());
buffer.append(s);
pos = 0;
}
while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) {
pos++;
}
int beginIndex = pos;
while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) {
pos++;
}
int endIndex = pos;
String s = buffer.substring(beginIndex, endIndex);
if (!s.equalsIgnoreCase(getSchemeName())) {
throw new MalformedChallengeException("Invalid scheme identifier: " + s);
}
parseChallenge(buffer, pos, buffer.length());
}
@SuppressWarnings("deprecation")
public Header authenticate(
final Credentials credentials,
final HttpRequest request,
final HttpContext context) throws AuthenticationException {
return authenticate(credentials, request);
}
protected abstract void parseChallenge(
CharArrayBuffer buffer, int beginIndex, int endIndex) throws MalformedChallengeException;
/**
* Returns <code>true</code> if authenticating against a proxy, <code>false</code>
* otherwise.
*
* @return <code>true</code> if authenticating against a proxy, <code>false</code>
* otherwise
*/
public boolean isProxy() {
return this.proxy;
}
@Override
public String toString() {
return getSchemeName();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals 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.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.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.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.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.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.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.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 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.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.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.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.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.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.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 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.