You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by js...@apache.org on 2003/01/27 16:25:48 UTC
cvs commit: jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/cookie CookiePolicy.java CookieSpec.java CookieSpecBase.java MalformedCookieException.java NetscapeDraftSpec.java RFC2109Spec.java
jsdever 2003/01/27 07:25:47
Modified: httpclient/src/java/org/apache/commons/httpclient
Authenticator.java AutoCloseInputStream.java
ChunkedInputStream.java ChunkedOutputStream.java
ConnectMethod.java ContentLengthInputStream.java
Cookie.java HttpConnection.java HttpMethodBase.java
WireLogInputStream.java
httpclient/src/java/org/apache/commons/httpclient/cookie
CookiePolicy.java CookieSpec.java
CookieSpecBase.java MalformedCookieException.java
NetscapeDraftSpec.java RFC2109Spec.java
Log:
Checkstyle cleanups.
Contributed by: Bike Bowler
Revision Changes Path
1.38 +89 -79 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/Authenticator.java
Index: Authenticator.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/Authenticator.java,v
retrieving revision 1.37
retrieving revision 1.38
diff -u -r1.37 -r1.38
--- Authenticator.java 23 Jan 2003 22:47:43 -0000 1.37
+++ Authenticator.java 27 Jan 2003 15:25:44 -0000 1.38
@@ -2,6 +2,7 @@
* $Header$
* $Revision$
* $Date$
+ *
* ====================================================================
*
* The Apache Software License, Version 1.1
@@ -28,7 +29,7 @@
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
- * 4. The names "The Jakarta Project", "HttpClient", and "Apache Software
+ * 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
@@ -59,6 +60,7 @@
* [Additional notices, if required by prior licensing conditions]
*
*/
+
package org.apache.commons.httpclient;
import org.apache.commons.httpclient.util.Base64;
@@ -98,6 +100,7 @@
* @author Ortwin Gl�ck
* @author Sean C. Sullivan
* @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
+ * @author <a href="mailto:mbowler@GargoyleSoftware.com>Mike Bowler</a>
* @version $Revision$ $Date$
*/
public class Authenticator {
@@ -105,9 +108,9 @@
// -------------------------------------- Static variables and initializers
/**
- * <tt>org.apache.commons.httpclient.Authenticator</tt> log.
+ * <tt>org.apache.commons.httpclient.Authenticator</tt> LOG.
*/
- private static final Log log = LogFactory.getLog(Authenticator.class);
+ private static final Log LOG = LogFactory.getLog(Authenticator.class);
/**
@@ -176,7 +179,7 @@
public static String createDigest(String uname, String pwd,
Map mapCredentials) throws HttpException {
- log.trace("enter Authenticator.createDigest(String, String, Map)");
+ LOG.trace("enter Authenticator.createDigest(String, String, Map)");
final String digAlg = "MD5";
@@ -198,7 +201,7 @@
try {
md5Helper = MessageDigest.getInstance(digAlg);
} catch (Exception e) {
- log.error("ERROR! Unsupported algorithm in HTTP Digest "
+ LOG.error("ERROR! Unsupported algorithm in HTTP Digest "
+ "authentication: " + digAlg, e);
throw new HttpException("Unsupported algorithm in HTTP Digest "
+ "authentication: " + digAlg);
@@ -208,7 +211,8 @@
String a2 = method + ":" + uri;
String md5a2 = encode(md5Helper.digest(HttpConstants.getBytes(a2)));
String digestValue = uname + ":" + realm + ":" + pwd;
- String md5a1 = encode(md5Helper.digest(HttpConstants.getBytes(digestValue)));
+ String md5a1
+ = encode(md5Helper.digest(HttpConstants.getBytes(digestValue)));
String serverDigestValue;
if (qop == null) {
@@ -240,7 +244,7 @@
public static boolean authenticate(HttpMethod method, HttpState state)
throws HttpException, UnsupportedOperationException {
- log.trace("enter Authenticator.authenticate(HttpMethod, HttpState)");
+ LOG.trace("enter Authenticator.authenticate(HttpMethod, HttpState)");
Header challengeHeader = method.getResponseHeader(WWW_AUTH);
@@ -263,7 +267,7 @@
public static boolean authenticateProxy(HttpMethod method, HttpState state)
throws HttpException, UnsupportedOperationException {
- log.trace("enter Authenticator.authenticateProxy(HttpMethod, "
+ LOG.trace("enter Authenticator.authenticateProxy(HttpMethod, "
+ "HttpState)");
Header challengeHeader = method.getResponseHeader(PROXY_AUTH);
@@ -280,12 +284,13 @@
* @return the credentials as a Basic Authentication string
*/
private static String basic(UsernamePasswordCredentials credentials) {
- log.trace("enter Authenticator.basic(UsernamePasswordCredentials)");
+ LOG.trace("enter Authenticator.basic(UsernamePasswordCredentials)");
- String authString = credentials.getUserName() + ":" +
- credentials.getPassword();
+ final String authString = credentials.getUserName() + ":"
+ + credentials.getPassword();
- return "Basic " + HttpConstants.getString(Base64.encode(HttpConstants.getBytes(authString)));
+ return "Basic " + HttpConstants.getString(
+ Base64.encode(HttpConstants.getBytes(authString)));
}
@@ -304,15 +309,15 @@
private static Header basic(String realm, HttpState state,
String responseHeader) throws HttpException {
- log.trace("enter Authenticator.basic(String, HttpState, String)");
+ LOG.trace("enter Authenticator.basic(String, HttpState, String)");
boolean proxy = PROXY_AUTH_RESP.equals(responseHeader);
UsernamePasswordCredentials credentials = null;
try {
- credentials = (UsernamePasswordCredentials) (proxy ?
- state.getProxyCredentials(realm) :
- state.getCredentials(realm));
+ credentials = (UsernamePasswordCredentials) (proxy
+ ? state.getProxyCredentials(realm)
+ : state.getCredentials(realm));
} catch (ClassCastException e) {
throw new HttpException("UsernamePasswordCredentials required for "
+ "Basic authentication.");
@@ -331,6 +336,7 @@
* Create a NTLM <tt>Authorization</tt> header for the given
* <i>Challenge</i> and <i>state</i> to the given <i>method</i>.
*
+ * @param challenge The challenge.
* @param method the {@link HttpMethod request} requiring the ntlm
* @param state a {@link HttpState} object providing
* {@link Credentials}
@@ -343,7 +349,7 @@
private static Header ntlm(String challenge, HttpMethod method,
HttpState state, String responseHeader) throws HttpException {
- log.trace("enter Authenticator.ntlm(String, HttpMethod, HttpState, "
+ LOG.trace("enter Authenticator.ntlm(String, HttpMethod, HttpState, "
+ "String)");
boolean proxy = PROXY_AUTH_RESP.equals(responseHeader);
@@ -353,9 +359,9 @@
if (method.getRequestHeader("Host") != null) {
String host = method.getRequestHeader("Host").getValue();
try {
- credentials = (NTCredentials) (proxy ?
- state.getProxyCredentials(host) :
- state.getCredentials(host));
+ credentials = (NTCredentials) (proxy
+ ? state.getProxyCredentials(host)
+ : state.getCredentials(host));
} catch (ClassCastException e) {
throw new HttpException("NTCredentials required "
+ "for NTLM authentication.");
@@ -363,12 +369,12 @@
}
if (credentials == null) {
- log.info("No credentials for specific host, " +
- "attempting to use default credentials.");
+ LOG.info("No credentials for specific host, "
+ + "attempting to use default credentials.");
try {
- credentials = (NTCredentials) (proxy ?
- state.getProxyCredentials(null) :
- state.getCredentials(null));
+ credentials = (NTCredentials) (proxy
+ ? state.getProxyCredentials(null)
+ : state.getCredentials(null));
} catch (ClassCastException e) {
throw new HttpException(
"NTCredentials required for NTLM authentication.");
@@ -377,8 +383,8 @@
try {
challenge =
- challenge.substring(challenge.toLowerCase().indexOf("ntlm") +
- "ntlm".length()).trim();
+ challenge.substring(challenge.toLowerCase().indexOf("ntlm")
+ + "ntlm".length()).trim();
} catch (IndexOutOfBoundsException e) {
throw new HttpException("Invalid NTLM challenge.");
}
@@ -391,8 +397,8 @@
String response = "NTLM " + ntlm.getResponseFor(challenge,
credentials.getUserName(), credentials.getPassword(),
credentials.getHost(), credentials.getDomain());
- if (log.isDebugEnabled()) {
- log.debug("Replying to challenge with: " + response);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Replying to challenge with: " + response);
}
return new Header(responseHeader, response);
}
@@ -415,31 +421,31 @@
private static Header digest(String realm, HttpMethod method,
HttpState state, String responseHeader) throws HttpException {
- log.trace("enter Authenticator.digest(String, HttpMethod, HttpState, "
+ LOG.trace("enter Authenticator.digest(String, HttpMethod, HttpState, "
+ "String)");
boolean proxy = PROXY_AUTH_RESP.equals(responseHeader);
UsernamePasswordCredentials credentials = null;
try {
- credentials = (UsernamePasswordCredentials) (proxy ?
- state.getProxyCredentials(realm) :
- state.getCredentials(realm));
+ credentials = (UsernamePasswordCredentials) (proxy
+ ? state.getProxyCredentials(realm)
+ : state.getCredentials(realm));
} catch (ClassCastException e) {
throw new HttpException("UsernamePasswordCredentials required for "
+ "Digest authentication.");
}
if (credentials == null) {
- if (log.isInfoEnabled()) {
- log.info("No credentials found for realm \"" + realm + "\", "
+ if (LOG.isInfoEnabled()) {
+ LOG.info("No credentials found for realm \"" + realm + "\", "
+ "attempting to use default credentials.");
}
try {
- credentials = (UsernamePasswordCredentials) (proxy ?
- state.getProxyCredentials(null) :
- state.getCredentials(null));
+ credentials = (UsernamePasswordCredentials) (proxy
+ ? state.getProxyCredentials(null)
+ : state.getCredentials(null));
} catch (ClassCastException e) {
throw new HttpException("UsernamePasswordCredentials required "
+ "for Digest authentication.");
@@ -467,14 +473,14 @@
* UsernamePasswordCredentials}.
*
* @param credentials Credentials to create the digest with
- * @param headers The headers for the current request
+ * @param mapHeaders The headers for the current request
* @return a string containing the authorization header for digest
* @throws HttpException When a recoverable error occurs
*/
private static String digest(UsernamePasswordCredentials credentials,
Map mapHeaders) throws HttpException {
- log.trace("enter Authenticator.digest(UsernamePasswordCredentials, "
+ LOG.trace("enter Authenticator.digest(UsernamePasswordCredentials, "
+ "Map)");
String digest = createDigest(credentials.getUserName(),
@@ -503,7 +509,7 @@
*/
private static Map getHTTPDigestCredentials(HttpMethod method,
boolean proxy) {
- log.trace("enter Authenticator.getHTTPDigestCredentials(HttpMethod, "
+ LOG.trace("enter Authenticator.getHTTPDigestCredentials(HttpMethod, "
+ "boolean)");
//Determine wether to use proxy or www header
@@ -549,10 +555,10 @@
*/
private static Map parseAuthenticateHeader(Header authHeader) {
- log.trace("enter parseAuthenticateHeader(Header)");
+ LOG.trace("enter parseAuthenticateHeader(Header)");
- if (log.isDebugEnabled()) {
- log.debug("Attempting to parse authenticate header: '"
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Attempting to parse authenticate header: '"
+ authHeader + "'");
}
if (authHeader == null || authHeader.getValue() == null) {
@@ -579,8 +585,8 @@
atComma = authValue.indexOf(',', atStart);
// skip any commas in quotes
- while (atComma > atQuote1 && atComma < atQuote2 &&
- atComma > 0) {
+ while (atComma > atQuote1 && atComma < atQuote2
+ && atComma > 0) {
atComma = authValue.indexOf(',', atComma + 1);
}
@@ -589,10 +595,10 @@
atComma = authValueLength;
}
- if (log.isDebugEnabled()) {
- log.debug("atStart =" + atStart + ", atQuote1 =" +
- atQuote1 + ", atQuote2=" + atQuote2 + ", atComma ="
- + atComma);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("atStart =" + atStart + ", atQuote1 ="
+ + atQuote1 + ", atQuote2=" + atQuote2 + ", atComma ="
+ + atComma);
}
try {
@@ -602,24 +608,24 @@
//find the blank and parse out the scheme
atSpace = challenge.indexOf(' ');
- scheme = (atSpace > 0) ?
- challenge.substring(0, atSpace).trim() : challenge;
+ scheme = (atSpace > 0)
+ ? challenge.substring(0, atSpace).trim() : challenge;
//store the challenge keyed on the scheme
challengeMap.put(scheme.toLowerCase(), challenge);
- if (log.isDebugEnabled()) {
- log.debug(scheme.toLowerCase() + "=>" + challenge);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(scheme.toLowerCase() + "=>" + challenge);
}
} catch (StringIndexOutOfBoundsException e) {
- log.warn("Parsing authorization challenge'" + challenge +
- "' failed", e);
+ LOG.warn("Parsing authorization challenge'" + challenge
+ + "' failed", e);
}
} // end of while
} catch (StringIndexOutOfBoundsException e) {
- log.warn("Parsing authorization header value'" + authValue +
- "' failed", e);
+ LOG.warn("Parsing authorization header value'" + authValue
+ + "' failed", e);
}
return challengeMap;
@@ -649,7 +655,7 @@
Header authenticateHeader, String responseHeader)
throws HttpException, UnsupportedOperationException {
- log.trace("enter Authenticator.authenticate(HttpMethod, HttpState, "
+ LOG.trace("enter Authenticator.authenticate(HttpMethod, HttpState, "
+ "Header, String)");
// check the preemptive policy
@@ -661,7 +667,7 @@
if (!(preemptiveDefault.equals("true")
|| preemptiveDefault.equals("false"))) { // property problem
- log.warn("Configuration property " + PREEMPTIVE_PROPERTY
+ LOG.warn("Configuration property " + PREEMPTIVE_PROPERTY
+ " must be either true or false. Using default: "
+ PREEMPTIVE_DEFAULT);
preemptiveDefault = PREEMPTIVE_DEFAULT;
@@ -672,7 +678,7 @@
//if there is no challenge, attempt to use preemptive authorization
if (authenticateHeader == null) {
if (preemptive) {
- log.debug("Preemptively sending default basic credentials");
+ LOG.debug("Preemptively sending default basic credentials");
try {
Header requestHeader = Authenticator.basic(null, state,
@@ -680,8 +686,8 @@
method.addRequestHeader(requestHeader);
return true;
} catch (HttpException httpe) {
- if (log.isDebugEnabled()) {
- log.debug(
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(
"No default credentials to preemptively send");
}
return false;
@@ -736,7 +742,7 @@
* TODO: + Add createCnonce() method
*/
private static String createCnonce() throws HttpException {
- log.trace("enter Authenticator.createCnonce()");
+ LOG.trace("enter Authenticator.createCnonce()");
String cnonce;
final String digAlg = "MD5";
@@ -745,7 +751,7 @@
try {
md5Helper = MessageDigest.getInstance(digAlg);
} catch (Exception e) {
- log.error("ERROR! Unsupported algorithm in HTTP Digest "
+ LOG.error("ERROR! Unsupported algorithm in HTTP Digest "
+ "authentication: " + digAlg);
throw new HttpException("Unsupported algorithm in HTTP Digest "
+ "authentication: " + digAlg);
@@ -772,7 +778,7 @@
private static String createDigestHeader(String uname, Map mapCredentials,
String digest) {
- log.trace("enter Authenticator.createDigestHeader(String, Map, "
+ LOG.trace("enter Authenticator.createDigestHeader(String, Map, "
+ "String)");
StringBuffer sb = new StringBuffer();
@@ -814,9 +820,11 @@
* TODO: + Add encode() method
*/
private static String encode(byte[] binaryData) {
- log.trace("enter Authenticator.encode(byte[])");
+ LOG.trace("enter Authenticator.encode(byte[])");
- if (binaryData.length != 16) return null;
+ if (binaryData.length != 16) {
+ return null;
+ }
char[] buffer = new char[32];
for (int i = 0; i < 16; i++) {
@@ -853,8 +861,8 @@
realm = realm.substring(atFirst + 1, atLast);
}
- if (log.isDebugEnabled()) {
- log.debug("Parsed realm '" + realm + "' from challenge '"
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Parsed realm '" + realm + "' from challenge '"
+ challenge + "'");
}
@@ -877,7 +885,7 @@
* TODO: + Add processDigestToken() method
*/
private static void processDigestToken(String token, Map tokens) {
- log.trace("enter Authenticator.processDigestToken(String, Map)");
+ LOG.trace("enter Authenticator.processDigestToken(String, Map)");
int atEqual = token.indexOf("=");
@@ -900,15 +908,17 @@
* is same as <CODE>str</CODE>
*/
private static String removeQuotes(String str) {
- log.trace("enter Authenticator.removeQuotes(String)");
+ LOG.trace("enter Authenticator.removeQuotes(String)");
- if (str == null) return null;
+ if (str == null) {
+ return null;
+ }
int atFirst = str.indexOf("\"") + 1;
int atLast = str.lastIndexOf("\"");
- return (atFirst > 0 && atLast > atFirst) ?
- str.substring(atFirst, atLast) : str;
+ return (atFirst > 0 && atLast > atFirst)
+ ? str.substring(atFirst, atLast) : str;
}
}
1.6 +25 -10 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/AutoCloseInputStream.java
Index: AutoCloseInputStream.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/AutoCloseInputStream.java,v
retrieving revision 1.5
retrieving revision 1.6
diff -u -r1.5 -r1.6
--- AutoCloseInputStream.java 23 Jan 2003 22:47:43 -0000 1.5
+++ AutoCloseInputStream.java 27 Jan 2003 15:25:45 -0000 1.6
@@ -2,6 +2,7 @@
* $Header$
* $Revision$
* $Date$
+ *
* ====================================================================
*
* The Apache Software License, Version 1.1
@@ -28,7 +29,7 @@
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
- * 4. The names "The Jakarta Project", "HttpClient", and "Apache Software
+ * 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
@@ -72,18 +73,26 @@
*
* @author Ortwin Gl�ck
* @author Eric Johnson
+ * @author <a href="mailto:mbowler@GargoyleSoftware.com>Mike Bowler</a>
*
* @since 2.0
*/
class AutoCloseInputStream extends FilterInputStream {
- // assume that the underlying stream is open until we get an EOF indication.
+ /**
+ * True if this stream is open. Assume that the underlying stream
+ * is open until we get an EOF indication.
+ */
private boolean streamOpen = true;
+ /** True if the stream closed itself. */
private boolean selfClosed = false;
- /** The watcher is notified when the contents of the stream have been exhausted */
+ /**
+ * The watcher is notified when the contents of the stream have
+ * been exhausted
+ */
private ResponseConsumedWatcher watcher = null;
/**
@@ -93,7 +102,8 @@
* @param watcher To be notified when the contents of the stream have been
* consumed.
*/
- public AutoCloseInputStream(InputStream in, ResponseConsumedWatcher watcher) {
+ public AutoCloseInputStream(
+ final InputStream in, final ResponseConsumedWatcher watcher) {
super(in);
this.watcher = watcher;
}
@@ -128,7 +138,7 @@
public int read(byte[] b, int off, int len) throws IOException {
int l = -1;
- if ( isReadAllowed() ) {
+ if (isReadAllowed()) {
l = super.read(b, off, len);
checkClose(l);
}
@@ -147,7 +157,7 @@
public int read(byte[] b) throws IOException {
int l = -1;
- if ( isReadAllowed() ) {
+ if (isReadAllowed()) {
l = super.read(b);
checkClose(l);
}
@@ -157,6 +167,7 @@
/**
* Close the stream, and also close the underlying stream if it is not
* already closed.
+ * @throws IOException If an IO problem occurs.
*/
public void close() throws IOException {
if (!selfClosed) {
@@ -169,6 +180,7 @@
* Close the underlying stream should the end of the stream arrive.
*
* @param readResult The result of the read operation to check.
+ * @throws IOException If an IO problem occurs.
*/
private void checkClose(int readResult) throws IOException {
if (readResult == -1) {
@@ -181,6 +193,7 @@
* not, check to see whether our stream has already been closed!
*
* @return <code>true</code> if it is still OK to read from the stream.
+ * @throws IOException If an IO problem occurs.
*/
private boolean isReadAllowed() throws IOException {
if (!streamOpen && selfClosed) {
@@ -191,14 +204,16 @@
/**
* Notify the watcher that the contents have been consumed.
+ * @throws IOException If an IO problem occurs.
*/
private void notifyWatcher() throws IOException {
if (streamOpen) {
super.close();
streamOpen = false;
- if (watcher != null)
+ if (watcher != null) {
watcher.responseConsumed();
+ }
}
}
}
1.10 +124 -61 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/ChunkedInputStream.java
Index: ChunkedInputStream.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/ChunkedInputStream.java,v
retrieving revision 1.9
retrieving revision 1.10
diff -u -r1.9 -r1.10
--- ChunkedInputStream.java 23 Jan 2003 22:47:44 -0000 1.9
+++ ChunkedInputStream.java 27 Jan 2003 15:25:45 -0000 1.10
@@ -2,17 +2,18 @@
* $Header$
* $Revision$
* $Date$
+ *
* ====================================================================
*
* The Apache Software License, Version 1.1
*
- * Copyright (c) 1999-2003 The Apache Software Foundation. All rights
- * reserved.
- *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
+ * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
+ * reserved.
+ *
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
@@ -28,7 +29,7 @@
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
- * 4. The names "The Jakarta Project", "HttpClient", and "Apache Software
+ * 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
@@ -62,16 +63,19 @@
package org.apache.commons.httpclient;
-import java.io.*;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
/**
- * <p>Transparently coalesces chunks of a HTTP stream that uses Transfer-Encoding
- * chunked.</p>
+ * <p>Transparently coalesces chunks of a HTTP stream that uses
+ * Transfer-Encoding chunked.</p>
*
- * <p>Note that this class NEVER closes the underlying stream, even when close gets
- * called. Instead, it will read until the "end" of its chunking on close, which
- * allows for the seamless invocation of subsequent HTTP 1.1 calls, while not
- * requiring the client to remember to read the entire contents of the response.</p>
+ * <p>Note that this class NEVER closes the underlying stream, even when close
+ * gets called. Instead, it will read until the "end" of its chunking on close,
+ * which allows for the seamless invocation of subsequent HTTP 1.1 calls, while
+ * not requiring the client to remember to read the entire contents of the
+ * response.</p>
*
* @see ResponseInputStream
*
@@ -79,16 +83,29 @@
* @author Sean C. Sullivan
* @author Martin Elwin
* @author Eric Johnson
+ * @author <a href="mailto:mbowler@GargoyleSoftware.com>Mike Bowler</a>
*
* @since 2.0
*
*/
public class ChunkedInputStream extends InputStream {
+ /** The inputstream that we're wrapping */
private InputStream in;
- private int chunkSize, pos;
+
+ /** The chunk size */
+ private int chunkSize;
+
+ /** The current position within the current chunk */
+ private int pos;
+
+ /** True if we've reached the end of stream */
private boolean eof = false;
+
+ /** True if this stream is closed */
private boolean closed = false;
+
+ /** The method that this stream came from */
private HttpMethod method;
/**
@@ -97,11 +114,11 @@
* @param in must be non-null
* @param method must be non-null
*
- * @throws java.io.IOException
- * @throws java.lang.NullPointerException
- *
+ * @throws IOException If an IO error occurs
*/
- public ChunkedInputStream(InputStream in, HttpMethod method) throws IOException {
+ public ChunkedInputStream(
+ final InputStream in, final HttpMethod method) throws IOException {
+
if (null == in) {
throw new NullPointerException("InputStream parameter");
}
@@ -119,37 +136,60 @@
}
/**
- * Returns all the data in a chunked stream in coalesced form. A chunk is
- * followed by a CRLF. The method returns -1 as soon as a chunksize of 0 is
- * detected.
- * Footers are read automcatically at the end of the stream and can be obtained
- * with the getFooters() method.
- *
- * @return -1 of the end of the stream has been reached or the next data byte
- * @throws IOException
+ * <p> Returns all the data in a chunked stream in coalesced form. A chunk
+ * is followed by a CRLF. The method returns -1 as soon as a chunksize of 0
+ * is detected.</p>
+ *
+ * <p> Footers are read automcatically at the end of the stream and can be
+ * obtained with the getFooters() method.</p>
+ *
+ * @return -1 of the end of the stream has been reached or the next data
+ * byte
+ * @throws IOException If an IO problem occurs
*/
public int read() throws IOException {
- if (closed)
+ if (closed) {
throw new IOException("Attempted read from closed stream.");
- if (eof) return -1;
+ }
+ if (eof) {
+ return -1;
+ }
if (pos >= chunkSize) {
nextChunk();
- if (eof) return -1;
+ if (eof) {
+ return -1;
+ }
}
pos++;
return in.read();
}
- public int read(byte[] b, int off, int len) throws java.io.IOException {
+ /**
+ * Read some bytes from the stream.
+ * @param b The byte array that will hold the contents from the stream.
+ * @param off The offset into the byte array at which bytes will start to be
+ * placed.
+ * @param len the maximum number of bytes that can be returned.
+ * @return The number of bytes returned or -1 if the end of stream has been
+ * reached.
+ * @see java.io.InputStream#read(byte[], int, int)
+ * @throws IOException if an IO problem occurs.
+ */
+ public int read (byte[] b, int off, int len) throws IOException {
- if (closed)
+ if (closed) {
throw new IOException("Attempted read from closed stream.");
+ }
- if (eof) return -1;
+ if (eof) {
+ return -1;
+ }
if (pos >= chunkSize) {
nextChunk();
- if (eof) return -1;
+ if (eof) {
+ return -1;
+ }
}
len = Math.min(len, chunkSize - pos);
int count = in.read(b, off, len);
@@ -157,15 +197,29 @@
return count;
}
- public int read(byte[] b) throws java.io.IOException {
+ /**
+ * Read some bytes from the stream.
+ * @param b The byte array that will hold the contents from the stream.
+ * @return The number of bytes returned or -1 if the end of stream has been
+ * reached.
+ * @see java.io.InputStream#read(byte[])
+ * @throws IOException if an IO problem occurs.
+ */
+ public int read (byte[] b) throws IOException {
return read(b, 0, b.length);
}
+ /**
+ * Read the next chunk.
+ * @throws IOException If an IO error occurs.
+ */
private void nextChunk() throws IOException {
int cr = in.read();
int lf = in.read();
- if ((cr != '\r') ||
- (lf != '\n')) throw new IOException("CRLF expected at end of chunk: "+cr+"/"+lf);
+ if ((cr != '\r') || (lf != '\n')) {
+ throw new IOException(
+ "CRLF expected at end of chunk: " + cr + "/" + lf);
+ }
chunkSize = getChunkSizeFromInputStream(in);
pos = 0;
if (chunkSize == 0) {
@@ -175,30 +229,31 @@
}
/**
- * Expects the stream to start with a chunksize in hex with optional comments
- * after a semicolon. The line must end with a CRLF:
- * "a3; some comment\r\n"
- * Positions the stream at the start of the next line.
+ * Expects the stream to start with a chunksize in hex with optional
+ * comments after a semicolon. The line must end with a CRLF: "a3; some
+ * comment\r\n" Positions the stream at the start of the next line.
*
+ * @param in The new input stream.
* @return the chunk size as integer
- *
* @throws IOException when the chunk size could not be parsed
- * @throws java.lang.RuntimeException
- *
- *
*/
- private static int getChunkSizeFromInputStream(final InputStream in) throws IOException {
+ private static int getChunkSizeFromInputStream(
+ final InputStream in) throws IOException {
+
ByteArrayOutputStream baos = new ByteArrayOutputStream();
- int state = 0; //0: normal, 1: \r was scanned, 2: inside quoted string, -1: end
+ // States: 0=normal, 1=\r was scanned, 2=inside quoted string, -1=end
+ int state = 0;
while (state != -1) {
int b = in.read();
- if (b == -1) throw new IOException("chunked stream ended unexpectedly");
+ if (b == -1) {
+ throw new IOException("chunked stream ended unexpectedly");
+ }
switch (state) {
- case 0:
+ case 0:
switch (b) {
case '\r':
state = 1;
- break;
+ break;
case '\"':
state = 2;
/* fall through */
@@ -212,7 +267,8 @@
state = -1;
} else {
// this was not CRLF
- throw new IOException("Protocol violation: Unexpected single newline character in chunk size");
+ throw new IOException("Protocol violation: Unexpected"
+ + " single newline character in chunk size");
}
break;
@@ -243,14 +299,15 @@
int result;
try {
result = Integer.parseInt(dataString.trim(), 16);
- } catch(NumberFormatException e) {
- throw new IOException("Bad chunk size: "+dataString);
+ } catch (NumberFormatException e) {
+ throw new IOException ("Bad chunk size: " + dataString);
}
return result;
}
/**
* Stores the footers into map of Headers
+ * @throws IOException If an IO problem occurs
*/
private void parseFooters() throws IOException {
String line = readLine();
@@ -258,7 +315,7 @@
int colonPos = line.indexOf(':');
if (colonPos != -1) {
String key = line.substring(0, colonPos).trim();
- String val = line.substring(colonPos+1).trim();
+ String val = line.substring(colonPos + 1).trim();
Header footer = new Header(key, val);
method.addResponseFooter(footer);
}
@@ -266,12 +323,17 @@
}
}
+ /**
+ * Read the next line from {@link #in}.
+ * @return String The next line.
+ * @throws IOException If an IO problem occurs.
+ */
private String readLine() throws IOException {
StringBuffer buf = new StringBuffer();
- for(;;) {
+ while (true) {
int ch = in.read();
- if(ch < 0) {
- if(buf.length() == 0) {
+ if (ch < 0) {
+ if (buf.length() == 0) {
return null;
} else {
break;
@@ -281,7 +343,7 @@
} else if (ch == '\n') {
break;
}
- buf.append((char)ch);
+ buf.append((char) ch);
}
return (buf.toString());
}
@@ -290,6 +352,7 @@
* Upon close, this reads the remainder of the chunked message,
* leaving the underlying socket at a position to start reading the
* next response without scanning.
+ * @throws IOException If an IO problem occurs.
*/
public void close() throws IOException {
if (!closed) {
@@ -297,8 +360,7 @@
if (!eof) {
exhaustInputStream(this);
}
- }
- finally {
+ } finally {
eof = true;
closed = true;
}
@@ -314,11 +376,12 @@
* shared that way.</p>
*
* @param inStream The {@link InputStream} to exhaust.
+ * @throws IOException If an IO problem occurs
*/
static void exhaustInputStream(InputStream inStream) throws IOException {
// read and discard the remainder of the message
byte buffer[] = new byte[1024];
- while ( inStream.read(buffer) >= 0) {
+ while (inStream.read(buffer) >= 0) {
;
}
}
1.5 +32 -29 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/ChunkedOutputStream.java
Index: ChunkedOutputStream.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/ChunkedOutputStream.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- ChunkedOutputStream.java 23 Jan 2003 22:09:33 -0000 1.4
+++ ChunkedOutputStream.java 27 Jan 2003 15:25:45 -0000 1.5
@@ -4,6 +4,7 @@
* $Date$
*
* ====================================================================
+ *
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2003 The Apache Software Foundation. All rights
@@ -28,7 +29,7 @@
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
- * 4. The names "The Jakarta Project", "HttpClient", and "Apache Software
+ * 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
@@ -62,12 +63,10 @@
package org.apache.commons.httpclient;
-
+import java.io.IOException;
+import java.io.OutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import java.io.*;
-
-
/**
* <p>
@@ -78,6 +77,7 @@
* @author Sean C. Sullivan
* @author <a href="mailto:dion@apache.org">dIon Gillard</a>
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
+ * @author <a href="mailto:mbowler@GargoyleSoftware.com>Mike Bowler</a>
* @version $Revision$ $Date$
*
* @see ChunkedInputStream
@@ -104,10 +104,10 @@
// ------------------------------------------------------- Static Variables
/** Log object for this class. */
- private static final Log log = LogFactory.getLog(ChunkedOutputStream.class);
+ private static final Log LOG = LogFactory.getLog(ChunkedOutputStream.class);
/** Log for any wire messages. */
- private static final Log wireLog = LogFactory.getLog("httpclient.wire");
+ private static final Log WIRE_LOG = LogFactory.getLog("httpclient.wire");
// ----------------------------------------------------- Instance Variables
@@ -144,7 +144,7 @@
* @throws IOException if an input or output exception occurred
*/
public void print(String s) throws IOException {
- log.trace("enter ChunckedOutputStream.print(String)");
+ LOG.trace("enter ChunckedOutputStream.print(String)");
if (s == null) {
s = "null";
}
@@ -181,8 +181,8 @@
* @throws IOException if an input/output error occurs
* @throws IllegalStateException if stream already closed
*/
- public void write(int b) throws IOException {
- if (closed){
+ public void write (int b) throws IOException, IllegalStateException {
+ if (closed) {
throw new IllegalStateException("Output stream already closed");
}
//FIXME: If using chunking, the chunks are ONE byte long!
@@ -190,9 +190,9 @@
stream.write(CRLF, 0, CRLF.length);
stream.write(b);
stream.write(ENDCHUNK, 0, ENDCHUNK.length);
- if (wireLog.isDebugEnabled()) {
- wireLog.debug(">> byte 1 \\r\\n (chunk length \"header\")");
- wireLog.debug(">> byte " + b + "\\r\\n (chunked byte)");
+ if (WIRE_LOG.isDebugEnabled()) {
+ WIRE_LOG.debug(">> byte 1 \\r\\n (chunk length \"header\")");
+ WIRE_LOG.debug(">> byte " + b + "\\r\\n (chunked byte)");
}
}
@@ -204,20 +204,21 @@
* @param len the length of data within <code>b</code> to write
* @throws IOException when errors occur writing output
*/
- public void write(byte[] b, int off, int len) throws IOException {
- log.trace("enter ChunckedOutputStream.write(byte[], int, int)");
+ public void write (byte[] b, int off, int len) throws IOException {
+ LOG.trace("enter ChunckedOutputStream.write(byte[], int, int)");
- if (closed){
+ if (closed) {
throw new IllegalStateException("Output stream already closed");
}
- byte chunkHeader[] = HttpConstants.getBytes(Integer.toHexString(len) + "\r\n");
+ byte chunkHeader[] = HttpConstants.getBytes (
+ Integer.toHexString(len) + "\r\n");
stream.write(chunkHeader, 0, chunkHeader.length);
stream.write(b, off, len);
stream.write(ENDCHUNK, 0, ENDCHUNK.length);
- if (wireLog.isDebugEnabled()) {
- wireLog.debug(">> byte(s)" + len + " \\r\\n (chunk length "
+ if (WIRE_LOG.isDebugEnabled()) {
+ WIRE_LOG.debug(">> byte(s)" + len + " \\r\\n (chunk length "
+ "\"header\")");
- wireLog.debug(">> \"" + new String(b, off, len)
+ WIRE_LOG.debug(">> \"" + new String(b, off, len)
+ "\"\\r\\n (chunked bytes)");
}
}
@@ -230,7 +231,7 @@
* @throws IOException if an error occurs closing the stream
*/
public void writeClosingChunk() throws IOException {
- log.trace("enter ChunkedOutputStream.writeClosingChunk()");
+ LOG.trace("enter ChunkedOutputStream.writeClosingChunk()");
if (!closed) {
try {
@@ -238,9 +239,10 @@
stream.write(ZERO, 0, ZERO.length);
stream.write(CRLF, 0, CRLF.length);
stream.write(ENDCHUNK, 0, ENDCHUNK.length);
- wireLog.debug(">> byte 0 \\r\\n\\r\\n (final chunk)");
+ WIRE_LOG.debug(">> byte 0 \\r\\n\\r\\n (final chunk)");
} catch (IOException e) {
- log.debug("Unexpected exception caught when closing output stream", e);
+ LOG.debug("Unexpected exception caught when closing "
+ + "output stream", e);
throw e;
} finally {
// regardless of what happens, mark the stream as closed.
@@ -253,8 +255,9 @@
/**
* Flushes the underlying stream.
+ * @throws IOException If an IO problem occurs.
*/
- public void flush() throws java.io.IOException {
+ public void flush() throws IOException {
stream.flush();
}
@@ -266,7 +269,7 @@
* @throws IOException if an error occurs closing the stream
*/
public void close() throws IOException {
- log.trace("enter ChunkedOutputStream.close()");
+ LOG.trace("enter ChunkedOutputStream.close()");
writeClosingChunk();
super.close();
}
1.6 +12 -11 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/ConnectMethod.java
Index: ConnectMethod.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/ConnectMethod.java,v
retrieving revision 1.5
retrieving revision 1.6
diff -u -r1.5 -r1.6
--- ConnectMethod.java 23 Jan 2003 22:47:45 -0000 1.5
+++ ConnectMethod.java 27 Jan 2003 15:25:45 -0000 1.6
@@ -2,6 +2,7 @@
* $Header$
* $Revision$
* $Date$
+ *
* ====================================================================
*
* The Apache Software License, Version 1.1
@@ -28,7 +29,7 @@
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
- * 4. The names "The Jakarta Project", "HttpClient", and "Apache Software
+ * 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
@@ -63,7 +64,6 @@
package org.apache.commons.httpclient;
import java.io.IOException;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -72,6 +72,7 @@
*
* @author Ortwin Gl�ck
* @author dIon Gillard
+ * @author <a href="mailto:mbowler@GargoyleSoftware.com>Mike Bowler</a>
* @since 2.0
* @version $Revision$ $Date$
*/
@@ -86,7 +87,7 @@
* to the server
*/
public ConnectMethod(HttpMethod method) {
- log.trace("enter ConnectMethod(HttpMethod)");
+ LOG.trace("enter ConnectMethod(HttpMethod)");
this.method = method;
}
@@ -111,9 +112,9 @@
public int execute(HttpState state, HttpConnection conn)
throws IOException, HttpException {
- log.trace("enter ConnectMethod.execute(HttpState, HttpConnection)");
+ LOG.trace("enter ConnectMethod.execute(HttpState, HttpConnection)");
int code = super.execute(state, conn);
- log.debug("CONNECT status code " + code);
+ LOG.debug("CONNECT status code " + code);
if ((code >= 200) && (code < 300)) {
conn.tunnelCreated();
code = method.execute(state, conn);
@@ -131,7 +132,7 @@
*/
protected void writeRequestHeaders(HttpState state, HttpConnection conn)
throws HttpException, IOException {
- log.trace("enter ConnectMethod.writeRequestHeaders(HttpState, "
+ LOG.trace("enter ConnectMethod.writeRequestHeaders(HttpState, "
+ "HttpConnection)");
if (method instanceof HttpMethodBase) {
@@ -168,7 +169,7 @@
/** Log object for this class. */
- private static final Log log = LogFactory.getLog(ConnectMethod.class);
+ private static final Log LOG = LogFactory.getLog(ConnectMethod.class);
/** The wrapped method */
private HttpMethod method;
1.5 +44 -13 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/ContentLengthInputStream.java
Index: ContentLengthInputStream.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/ContentLengthInputStream.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- ContentLengthInputStream.java 23 Jan 2003 22:47:45 -0000 1.4
+++ ContentLengthInputStream.java 27 Jan 2003 15:25:45 -0000 1.5
@@ -2,6 +2,7 @@
* $Header$
* $Revision$
* $Date$
+ *
* ====================================================================
*
* The Apache Software License, Version 1.1
@@ -28,7 +29,7 @@
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
- * 4. The names "The Jakarta Project", "HttpClient", and "Apache Software
+ * 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
@@ -62,20 +63,31 @@
package org.apache.commons.httpclient;
-import java.io.*;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
/**
* Cuts the wrapped InputStream off after a specified number of bytes.
*
* @author Ortwin Gl�ck
* @author Eric Johnson
+ * @author <a href="mailto:mbowler@GargoyleSoftware.com>Mike Bowler</a>
* @since 2.0
*/
public class ContentLengthInputStream extends FilterInputStream {
+
+ /**
+ * The maximum number of bytes that can be read from the stream. Subsequent
+ * read operations will return -1.
+ */
private int contentLength;
+
+ /** The current position */
private int pos = 0;
+ /** True if the stream is closed. */
private boolean closed = false;
/**
@@ -91,10 +103,11 @@
}
/**
- * Reads until the end of the known length of content.
+ * <p>Reads until the end of the known length of content.</p>
*
* <p>Does not close the underlying socket input, but instead leaves it
* primed to parse the next response.</p>
+ * @throws IOException If an IO problem occurs.
*/
public void close() throws IOException {
if (!closed) {
@@ -108,12 +121,21 @@
}
}
- public int read() throws java.io.IOException {
- if (closed)
+
+ /**
+ * Read the next byte from the stream
+ * @return The next byte or -1 if the end of stream has been reached.
+ * @throws IOException If an IO problem occurs
+ * @see java.io.InputStream#read()
+ */
+ public int read() throws IOException {
+ if (closed) {
throw new IOException("Attempted read from closed stream.");
+ }
- if (pos >= contentLength)
+ if (pos >= contentLength) {
return -1;
+ }
pos++;
return super.read();
}
@@ -130,12 +152,14 @@
*
* @throws java.io.IOException Should an error occur on the wrapped stream.
*/
- public int read(byte[] b, int off, int len) throws java.io.IOException {
- if (closed)
+ public int read (byte[] b, int off, int len) throws java.io.IOException {
+ if (closed) {
throw new IOException("Attempted read from closed stream.");
+ }
- if (pos >= contentLength)
+ if (pos >= contentLength) {
return -1;
+ }
if (pos + len > contentLength) {
len = contentLength - pos;
@@ -146,7 +170,14 @@
}
- public int read(byte[] b) throws java.io.IOException {
+ /**
+ * Read more bytes from the stream.
+ * @param b The byte array to put the new data in.
+ * @return The number of bytes read into the buffer.
+ * @throws IOException If an IO problem occurs
+ * @see java.io.InputStream#read(byte[])
+ */
+ public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
1.34 +106 -67 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/Cookie.java
Index: Cookie.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/Cookie.java,v
retrieving revision 1.33
retrieving revision 1.34
diff -u -r1.33 -r1.34
--- Cookie.java 23 Jan 2003 22:47:45 -0000 1.33
+++ Cookie.java 27 Jan 2003 15:25:45 -0000 1.34
@@ -86,6 +86,7 @@
* @author <a href="mailto:JEvans@Cyveillance.com">John Evans</a>
* @author Marc A. Saegesser
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
+ * @author <a href="mailto:mbowler@GargoyleSoftware.com>Mike Bowler</a>
* @version $Revision$ $Date$
*/
@@ -128,7 +129,7 @@
*/
public Cookie(String domain, String name, String value, String path, Date expires, boolean secure) {
super(name, value);
- log.trace("enter Cookie(String, String, String, String, Date, boolean)");
+ LOG.trace("enter Cookie(String, String, String, String, Date, boolean)");
if (name == null) {
throw new IllegalArgumentException("Cookie name may not be null");
}
@@ -426,7 +427,7 @@
* Two cookies are equal if the name, path and domain match.
*/
public boolean equals(Object obj) {
- log.trace("enter Cookie.equals(Object)");
+ LOG.trace("enter Cookie.equals(Object)");
if ((obj != null) && (obj instanceof Cookie)) {
Cookie that = (Cookie) obj;
return (null == this.getName() ? null == that.getName() : this.getName().equals(that.getName())) &&
@@ -459,7 +460,7 @@
*/
public boolean matches(String domain, int port, String path, boolean secure, Date date)
{
- log.trace("enter Cookie.matches(Strinng, int, String, boolean, Date");
+ LOG.trace("enter Cookie.matches(Strinng, int, String, boolean, Date");
CookieSpec matcher = CookiePolicy.getDefaultSpec();
return matcher.match(domain, port, path, secure, this);
}
@@ -474,7 +475,7 @@
* @deprecated use {@link CookieSpec} interface
*/
public boolean matches(String domain, int port, String path, boolean secure) {
- log.trace("enter Cookie.matches(String, int, String, boolean");
+ LOG.trace("enter Cookie.matches(String, int, String, boolean");
return matches(domain, port, path, secure, new Date());
}
@@ -490,7 +491,7 @@
* @deprecated use {@link CookieSpec} interface
*/
public static Header createCookieHeader(String domain, String path, Cookie[] cookies) {
- log.trace("enter Cookie.createCookieHeader(String, String, Cookie[])");
+ LOG.trace("enter Cookie.createCookieHeader(String, String, Cookie[])");
return Cookie.createCookieHeader(domain,path,false,cookies);
}
@@ -507,7 +508,7 @@
*/
public static Header createCookieHeader(String domain, String path, boolean secure, Cookie[] cookies)
throws IllegalArgumentException {
- log.trace("enter Cookie.createCookieHeader(String, String, boolean, Cookie[])");
+ LOG.trace("enter Cookie.createCookieHeader(String, String, boolean, Cookie[])");
// Make sure domain isn't null here. Path will be validated in subsequent call to createCookieHeader
if(domain == null){
@@ -520,8 +521,8 @@
try {
port = Integer.parseInt(domain.substring(ndx+1,domain.length()));
} catch(NumberFormatException e){
- // ignore?, but at least log
- log.warn("Cookie.createCookieHeader(): Invalid port number in domain " + domain);
+ // ignore?, but at least LOG
+ LOG.warn("Cookie.createCookieHeader(): Invalid port number in domain " + domain);
}
}
return Cookie.createCookieHeader(domain,port,path,secure,cookies);
@@ -540,34 +541,42 @@
*/
public static Header createCookieHeader(String domain, int port, String path, boolean secure, Cookie[] cookies)
throws IllegalArgumentException {
- log.trace("enter Cookie.createCookieHeader(String, int, String, boolean, Cookie[])");
+ LOG.trace("enter Cookie.createCookieHeader(String, int, String, boolean, Cookie[])");
return Cookie.createCookieHeader(domain, port, path, secure, new Date(), cookies);
}
/**
- * Create a <tt>Cookie</tt> header containing
- * all cookies in <i>cookies</i>,
- * associated with the given <i>domain</i>, <i>port</i>,
- * <i>path</i> and <i>https</i> setting, and which are
- * not expired according to the given <i>date</i>.
+ * Create a <tt>Cookie</tt> header containing all cookies in <i>cookies</i>,
+ * associated with the given <i>domain</i>, <i>port</i>, <i>path</i> and
+ * <i>https</i> setting, and which are not expired according to the given
+ * <i>date</i>.
* <p>
* If no cookies match, returns null.
- * @exception java.lang.IllegalArgumentException if domain or path is null
+ *
+ * @param domain The domain
+ * @param port The port
+ * @param path The path
+ * @param secure True if this cookie has the secure flag set
+ * @param now The date to check for expiry
+ * @param cookies The cookies to use.
+ * @return The new header
+ * @exception IllegalArgumentException if domain or path is null
*
* @deprecated use {@link CookieSpec} interface
*/
- public static Header createCookieHeader(String domain, int port, String path, boolean secure, Date now, Cookie[] cookies)
- throws IllegalArgumentException {
- log.trace("enter Cookie.createCookieHeader(String, int, String, boolean, Date, Cookie[])");
+ public static Header createCookieHeader(
+ String domain, int port, String path, boolean secure,
+ Date now, Cookie[] cookies)
+ throws IllegalArgumentException {
+
+ LOG.trace("enter Cookie.createCookieHeader(String, int, String, boolean, Date, Cookie[])");
CookieSpec matcher = CookiePolicy.getDefaultSpec();
cookies = matcher.match(domain, port, path, secure, cookies);
- if ((cookies != null) && (cookies.length > 0))
- {
+ if ((cookies != null) && (cookies.length > 0)) {
return matcher.formatCookieHeader(cookies);
}
- else
- {
+ else {
return null;
}
}
@@ -580,9 +589,12 @@
* createCookieHeader method.</p>
* <p>The compare only compares the path of the cookie, see section 4.3.4
* of RFC2109</p>
+ * @param o1 The first object to be compared
+ * @param o2 The second object to be compared
+ * @return See {@link java.util.Comparator#compare(Object,Object)}
*/
public int compare(Object o1, Object o2) {
- log.trace("enter Cookie.compare(Object, Object)");
+ LOG.trace("enter Cookie.compare(Object, Object)");
if (!(o1 instanceof Cookie)) {
throw new ClassCastException(o1.getClass().getName());
@@ -590,8 +602,8 @@
if (!(o2 instanceof Cookie)) {
throw new ClassCastException(o2.getClass().getName());
}
- Cookie c1 = (Cookie)o1;
- Cookie c2 = (Cookie)o2;
+ Cookie c1 = (Cookie) o1;
+ Cookie c2 = (Cookie) o2;
if (c1.getPath() == null && c2.getPath() == null) {
return 0;
} else if (c1.getPath() == null) {
@@ -609,7 +621,7 @@
return 1;
}
} else {
- return stringCollator.compare(c1.getPath(), c2.getPath());
+ return STRING_COLLATOR.compare(c1.getPath(), c2.getPath());
}
}
@@ -627,16 +639,21 @@
* on an insecure channel.
*
* @param domain the domain from which the {@link Header} was received
- * @param port the port from which the {@link Header} was received (currently ignored)
+ * @param port the port from which the {@link Header} was received
+ * (currently ignored)
* @param path the path from which the {@link Header} was received
- * @param setCookie the <tt>Set-Cookie</tt> {@link Header} received from the server
- * @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie {@link Header}
+ * @param setCookie the <tt>Set-Cookie</tt> {@link Header} received from the
+ * server
+ * @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie {@link
+ * Header}
* @throws HttpException if an exception occurs during parsing
- * @throws java.lang.IllegalArgumentException if domain or path are null
+ * @throws IllegalArgumentException if domain or path are null
*/
- public static Cookie[] parse(String domain, int port, String path, Header setCookie)
- throws HttpException, IllegalArgumentException {
- log.trace("enter Cookie.parse(String, int, String, Header)");
+ public static Cookie[] parse(
+ String domain, int port, String path, Header setCookie)
+ throws HttpException, IllegalArgumentException {
+
+ LOG.trace("enter Cookie.parse(String, int, String, Header)");
return Cookie.parse(domain,port,path,false,setCookie);
}
@@ -647,17 +664,19 @@
*
* @param domain the domain from which the {@link Header} was received
* @param path the path from which the {@link Header} was received
- * @param setCookie the <tt>Set-Cookie</tt> {@link Header} received from the server
- * @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie {@link Header}
+ * @param setCookie the <tt>Set-Cookie</tt> {@link Header} received from the
+ * server
+ * @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie {@link
+ * Header}
* @throws HttpException if an exception occurs during parsing
- * @throws java.lang.IllegalArgumentException if domain or path are null
+ * @throws IllegalArgumentException if domain or path are null
*
* @deprecated use {@link CookieSpec} interface
*/
public static Cookie[] parse(String domain, String path, Header setCookie)
throws HttpException, IllegalArgumentException {
- log.trace("enter Cookie.parse(String, String, Header)");
- return Cookie.parse(domain,80,path,false,setCookie);
+ LOG.trace("enter Cookie.parse(String, String, Header)");
+ return Cookie.parse (domain, 80, path, false, setCookie);
}
/**
@@ -666,18 +685,24 @@
*
* @param domain the domain from which the {@link Header} was received
* @param path the path from which the {@link Header} was received
- * @param secure <tt>true</tt> when the header was recieved over a secure channel
- * @param setCookie the <tt>Set-Cookie</tt> {@link Header} received from the server
- * @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie {@link Header}
+ * @param secure <tt>true</tt> when the header was recieved over a secure
+ * channel
+ * @param setCookie the <tt>Set-Cookie</tt> {@link Header} received from the
+ * server
+ * @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie {@link
+ * Header}
* @throws HttpException if an exception occurs during parsing
- * @throws java.lang.IllegalArgumentException if domain or path are null
+ * @throws IllegalArgumentException if domain or path are null
*
* @deprecated use {@link CookieSpec} interface
*/
- public static Cookie[] parse(String domain, String path, boolean secure, Header setCookie)
- throws HttpException {
- log.trace("enter Cookie.parse(String, String, boolean, Header)");
- return Cookie.parse(domain,(secure ? 443 : 80),path,secure,setCookie);
+ public static Cookie[] parse(String domain, String path,
+ boolean secure, Header setCookie)
+ throws HttpException, IllegalArgumentException {
+
+ LOG.trace ("enter Cookie.parse(String, String, boolean, Header)");
+ return Cookie.parse (
+ domain, (secure ? 443 : 80), path, secure, setCookie);
}
/**
@@ -701,26 +726,31 @@
* </PRE>
*
* @param domain the domain from which the {@link Header} was received
+ * @param port The port from which the {@link Header} was received.
* @param path the path from which the {@link Header} was received
- * @param secure <tt>true</tt> when the {@link Header} was received over HTTPS
- * @param setCookie the <tt>Set-Cookie</tt> {@link Header} received from the server
- * @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie {@link Header}
+ * @param secure <tt>true</tt> when the {@link Header} was received over
+ * HTTPS
+ * @param setCookie the <tt>Set-Cookie</tt> {@link Header} received from
+ * the server
+ * @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie {@link
+ * Header}
* @throws HttpException if an exception occurs during parsing
- * @throws java.lang.IllegalArgumentException if domain or path are null
*
* @deprecated use {@link CookieSpec} interface
*/
- public static Cookie[] parse(String domain, int port, String path, boolean secure, Header setCookie)
- throws HttpException, IllegalArgumentException {
- log.trace("enter Cookie.parse(String, int, String, boolean, Header)");
+ public static Cookie[] parse(String domain, int port, String path,
+ boolean secure, Header setCookie)
+ throws HttpException {
+
+ LOG.trace("enter Cookie.parse(String, int, String, boolean, Header)");
CookieSpec parser = CookiePolicy.getDefaultSpec();
Cookie[] cookies = parser.parse(domain, port, path, secure, setCookie);
- for (int i = 0; i < cookies.length; i++)
- {
- Cookie cookie = cookies[i];
- CookieSpec validator = CookiePolicy.getSpecByVersion(cookie.getVersion());
+ for (int i = 0; i < cookies.length; i++) {
+ final Cookie cookie = cookies[i];
+ final CookieSpec validator
+ = CookiePolicy.getSpecByVersion(cookie.getVersion());
validator.validate(domain, port, path, secure, cookie);
}
return cookies;
@@ -743,10 +773,16 @@
/** My secure flag. */
private boolean _secure;
- /** Specifies if the set-cookie header included a Path attribute for this cookie */
+ /**
+ * Specifies if the set-cookie header included a Path attribute for this
+ * cookie
+ */
private boolean _hasPathAttribute = false;
- /** Specifies if the set-cookie header included a Domain attribute for this cookie */
+ /**
+ * Specifies if the set-cookie header included a Domain attribute for this
+ * cookie
+ */
private boolean _hasDomainAttribute = false;
/** The version of the cookie specification I was created from. */
@@ -754,13 +790,16 @@
// -------------------------------------------------------------- Constants
- /** Collator for Cookie comparisons. Could be replaced with references to specific Locales. */
- private static final RuleBasedCollator stringCollator =
- (RuleBasedCollator)RuleBasedCollator.getInstance(
+ /**
+ * Collator for Cookie comparisons. Could be replaced with references to
+ * specific Locales.
+ */
+ private static final RuleBasedCollator STRING_COLLATOR =
+ (RuleBasedCollator) RuleBasedCollator.getInstance(
new Locale("en", "US", ""));
/** Log object for this class */
- private static final Log log = LogFactory.getLog(Cookie.class);
+ private static final Log LOG = LogFactory.getLog(Cookie.class);
}
1.37 +6 -6 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HttpConnection.java
Index: HttpConnection.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HttpConnection.java,v
retrieving revision 1.36
retrieving revision 1.37
diff -u -r1.36 -r1.37
--- HttpConnection.java 25 Jan 2003 04:46:39 -0000 1.36
+++ HttpConnection.java 27 Jan 2003 15:25:45 -0000 1.37
@@ -824,10 +824,10 @@
break;
}
} else if (ch == '\r') {
-// log.debug("HttpConnection.readLine() found \\r, continuing");
+// LOG.debug("HttpConnection.readLine() found \\r, continuing");
continue;
} else if (ch == '\n') {
-// log.debug("HttpConnection.readLine() found \\n, breaking");
+// LOG.debug("HttpConnection.readLine() found \\n, breaking");
break;
}
buf.append((char)ch);
1.101 +6 -6 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HttpMethodBase.java
Index: HttpMethodBase.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/HttpMethodBase.java,v
retrieving revision 1.100
retrieving revision 1.101
diff -u -r1.100 -r1.101
--- HttpMethodBase.java 27 Jan 2003 04:44:30 -0000 1.100
+++ HttpMethodBase.java 27 Jan 2003 15:25:45 -0000 1.101
@@ -936,7 +936,7 @@
//check to see if we have visited this url before
if (visited.contains(generateVisitedKey(conn))) {
- log.error("Link " + generateVisitedKey(conn) + "' revisited");
+ LOG.error("Link " + generateVisitedKey(conn) + "' revisited");
return statusCode;
}
visited.add(generateVisitedKey(conn));
@@ -1023,7 +1023,7 @@
try{
checkValidRedirect(currentUrl, redirectUrl);
} catch (HttpException ex) {
- //log the error and let the client handle the redirect
+ //LOG the error and let the client handle the redirect
log.warn(ex.getMessage());
return false;
}
1.6 +4 -4 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/WireLogInputStream.java
Index: WireLogInputStream.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/WireLogInputStream.java,v
retrieving revision 1.5
retrieving revision 1.6
diff -u -r1.5 -r1.6
--- WireLogInputStream.java 23 Jan 2003 22:47:49 -0000 1.5
+++ WireLogInputStream.java 27 Jan 2003 15:25:46 -0000 1.6
@@ -66,7 +66,7 @@
import org.apache.commons.logging.*;
/**
- * Logs all data read to the wire log.
+ * Logs all data read to the wire LOG.
*
* @author Ortwin Gl�ck
*
1.5 +8 -6 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/cookie/CookiePolicy.java
Index: CookiePolicy.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/cookie/CookiePolicy.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- CookiePolicy.java 26 Jan 2003 06:59:20 -0000 1.4
+++ CookiePolicy.java 27 Jan 2003 15:25:47 -0000 1.5
@@ -2,6 +2,7 @@
* $Header$
* $Revision$
* $Date$
+ *
* ====================================================================
*
* The Apache Software License, Version 1.1
@@ -28,7 +29,7 @@
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
- * 4. The names "The Jakarta Project", "HttpClient", and "Apache Software
+ * 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
@@ -82,6 +83,7 @@
* <tt>COMPATIBILITY</tt>, <tt>NETSCAPE_DRAFT</tt>, <tt>RFC2109</tt>.
*
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
+ * @author <a href="mailto:mbowler@GargoyleSoftware.com>Mike Bowler</a>
*
* @since 2.0
*/
@@ -107,7 +109,7 @@
private static int defaultPolicy = RFC2109;
/** Log object. */
- protected static final Log log = LogFactory.getLog(CookiePolicy.class);
+ protected static final Log LOG = LogFactory.getLog(CookiePolicy.class);
static {
String s = System.getProperty(SYSTEM_PROPERTY);
@@ -119,7 +121,7 @@
} else if ("RFC2109".equalsIgnoreCase(s)) {
setDefaultPolicy(RFC2109);
} else {
- log.warn("Unrecognized cookiespec property '" + s
+ LOG.warn("Unrecognized cookiespec property '" + s
+ "' - using default");
setDefaultPolicy(defaultPolicy);
}
1.6 +5 -4 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/cookie/CookieSpec.java
Index: CookieSpec.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/cookie/CookieSpec.java,v
retrieving revision 1.5
retrieving revision 1.6
diff -u -r1.5 -r1.6
--- CookieSpec.java 26 Jan 2003 06:59:20 -0000 1.5
+++ CookieSpec.java 27 Jan 2003 15:25:47 -0000 1.6
@@ -2,6 +2,7 @@
* $Header$
* $Revision$
* $Date$
+ *
* ====================================================================
*
* The Apache Software License, Version 1.1
@@ -28,7 +29,7 @@
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
- * 4. The names "The Jakarta Project", "HttpClient", and "Apache Software
+ * 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
1.8 +265 -259 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java
Index: CookieSpecBase.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java,v
retrieving revision 1.7
retrieving revision 1.8
diff -u -r1.7 -r1.8
--- CookieSpecBase.java 23 Jan 2003 22:48:06 -0000 1.7
+++ CookieSpecBase.java 27 Jan 2003 15:25:47 -0000 1.8
@@ -2,6 +2,7 @@
* $Header$
* $Revision$
* $Date$
+ *
* ====================================================================
*
* The Apache Software License, Version 1.1
@@ -28,7 +29,7 @@
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
- * 4. The names "The Jakarta Project", "HttpClient", and "Apache Software
+ * 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
@@ -58,8 +59,7 @@
*
* [Additional notices, if required by prior licensing conditions]
*
- */
-
+ */
package org.apache.commons.httpclient.cookie;
@@ -75,7 +75,6 @@
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HeaderElement;
import org.apache.commons.httpclient.Cookie;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -92,17 +91,17 @@
* @author <a href="mailto:JEvans@Cyveillance.com">John Evans</a>
* @author Marc A. Saegesser
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
+ * @author <a href="mailto:mbowler@GargoyleSoftware.com>Mike Bowler</a>
*
* @since 2.0
*/
-public class CookieSpecBase implements CookieSpec
-{
+public class CookieSpecBase implements CookieSpec {
/** Log object */
- protected static final Log log = LogFactory.getLog(CookieSpec.class);
+ protected static final Log LOG = LogFactory.getLog(CookieSpec.class);
/** List of valid date formats for the "expires" cookie attribute. */
- private static final DateFormat[] expiryFormats = {
+ private static final DateFormat[] EXPIRY_FORMATS = {
// RFC 1123, 822, Date and time specification is English.
new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss z", Locale.US),
new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US),
@@ -117,9 +116,7 @@
};
/** Default constructor */
-
- public CookieSpecBase()
- {
+ public CookieSpecBase() {
super();
}
@@ -143,39 +140,41 @@
* | "Version" "=" 1*DIGIT
* </PRE>
*
- * @param host the host from which the <tt>Set-Cookie</tt> value was received
- * @param port the port from which the <tt>Set-Cookie</tt> value was received
- * @param path the path from which the <tt>Set-Cookie</tt> value was received
- * @param secure <tt>true</tt> when the <tt>Set-Cookie</tt> value was received over secure conection
+ * @param host the host from which the <tt>Set-Cookie</tt> value was
+ * received
+ * @param port the port from which the <tt>Set-Cookie</tt> value was
+ * received
+ * @param path the path from which the <tt>Set-Cookie</tt> value was
+ * received
+ * @param secure <tt>true</tt> when the <tt>Set-Cookie</tt> value was
+ * received over secure conection
* @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
- * @throws java.lang.IllegalArgumentException if an input parameter is illegal
*/
-
- public Cookie[] parse(String host, int port, String path, boolean secure, final String header)
- throws MalformedCookieException
- {
- log.trace("enter CookieSpecBase.parse(String, port, path, boolean, Header)");
-
- if(host == null)
- {
- throw new IllegalArgumentException("Host of origin may not be null");
- }
- if(host.trim().equals(""))
- {
- throw new IllegalArgumentException("Host of origin may not be blank");
+ public Cookie[] parse(String host, int port, String path,
+ boolean secure, final String header)
+ throws MalformedCookieException {
+
+ LOG.trace("enter CookieSpecBase.parse("
+ + "String, port, path, boolean, Header)");
+
+ if (host == null) {
+ throw new IllegalArgumentException(
+ "Host of origin may not be null");
+ }
+ if (host.trim().equals("")) {
+ throw new IllegalArgumentException(
+ "Host of origin may not be blank");
}
- if(port < 0)
- {
+ if (port < 0) {
throw new IllegalArgumentException("Invalid port: " + port);
}
- if(path == null)
- {
- throw new IllegalArgumentException("Path of origin may not be null.");
+ if (path == null) {
+ throw new IllegalArgumentException(
+ "Path of origin may not be null.");
}
- if(header == null)
- {
+ if (header == null) {
throw new IllegalArgumentException("Header may not be null.");
}
@@ -185,19 +184,15 @@
host = host.toLowerCase();
HeaderElement[] headerElements = null;
- try
- {
+ try {
headerElements = HeaderElement.parse(header);
- }
- catch(HttpException e)
- {
+ } catch (HttpException e) {
throw new MalformedCookieException(e.getMessage());
}
String defaultPath = path;
int lastSlashIndex = defaultPath.lastIndexOf(PATH_DELIM);
- if(lastSlashIndex > 0)
- {
+ if (lastSlashIndex > 0) {
defaultPath = defaultPath.substring(0, lastSlashIndex);
}
@@ -218,8 +213,7 @@
// could be null. In case only a header element and no parameters.
if (parameters != null) {
- for (int j = 0; j < parameters.length; j++)
- {
+ for (int j = 0; j < parameters.length; j++) {
parseAttribute(parameters[j], cookie);
}
}
@@ -230,7 +224,8 @@
/**
- * Parse the <tt>"Set-Cookie"</tt> {@link Header} into an array of {@link Cookie}s.
+ * Parse the <tt>"Set-Cookie"</tt> {@link Header} into an array of {@link
+ * Cookie}s.
*
* <P>The syntax for the Set-Cookie response header is:
*
@@ -248,22 +243,26 @@
* | "Version" "=" 1*DIGIT
* </PRE>
*
- * @param host the host from which the <tt>Set-Cookie</tt> header was received
- * @param port the port from which the <tt>Set-Cookie</tt> header was received
- * @param path the path from which the <tt>Set-Cookie</tt> header was received
- * @param secure <tt>true</tt> when the <tt>Set-Cookie</tt> header was received over secure conection
+ * @param host the host from which the <tt>Set-Cookie</tt> header was
+ * received
+ * @param port the port from which the <tt>Set-Cookie</tt> header was
+ * received
+ * @param path the path from which the <tt>Set-Cookie</tt> header was
+ * received
+ * @param secure <tt>true</tt> when the <tt>Set-Cookie</tt> header was
+ * received over secure conection
* @param header the <tt>Set-Cookie</tt> received from the server
- * @return an array of <tt>Cookie</tt>s parsed from the <tt>"Set-Cookie"</tt> header
+ * @return an array of <tt>Cookie</tt>s parsed from the <tt>"Set-Cookie"
+ * </tt> header
* @throws MalformedCookieException if an exception occurs during parsing
- * @throws java.lang.IllegalArgumentException if an input parameter is illegal
*/
-
- public Cookie[] parse(String host, int port, String path, boolean secure, final Header header)
- throws MalformedCookieException
- {
- log.trace("enter CookieSpecBase.parse(String, port, path, boolean, String)");
- if(header == null)
- {
+ public Cookie[] parse(
+ String host, int port, String path, boolean secure, final Header header)
+ throws MalformedCookieException {
+
+ LOG.trace("enter CookieSpecBase.parse("
+ + "String, port, path, boolean, String)");
+ if (header == null) {
throw new IllegalArgumentException("Header may not be null.");
}
return parse(host, port, path, secure, header.getValue());
@@ -271,95 +270,98 @@
/**
- * Parse the cookie attribute and update the corresponsing {@link Cookie} properties.
+ * Parse the cookie attribute and update the corresponsing {@link Cookie}
+ * properties.
*
- * @param attribute {@link HeaderElement} cookie attribute from the <tt>Set-Cookie</tt>
+ * @param attribute {@link HeaderElement} cookie attribute from the
+ * <tt>Set- Cookie</tt>
* @param cookie {@link Cookie} to be updated
* @throws MalformedCookieException if an exception occurs during parsing
- * @throws java.lang.IllegalArgumentException if an input parameter is illegal
*/
- public void parseAttribute(final NameValuePair attribute, final Cookie cookie)
- throws MalformedCookieException
- {
- if(attribute == null)
- {
+ public void parseAttribute(
+ final NameValuePair attribute, final Cookie cookie)
+ throws MalformedCookieException {
+
+ if (attribute == null) {
throw new IllegalArgumentException("Attribute may not be null.");
}
- if(cookie == null)
- {
+ if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null.");
}
- String param_name = attribute.getName().toLowerCase();
- String param_value = attribute.getValue();
+ final String paramName = attribute.getName().toLowerCase();
+ String paramValue = attribute.getValue();
- if (param_name.equals("path")) {
+ if (paramName.equals("path")) {
- if (param_value == null) {
- throw new MalformedCookieException("Missing value for path attribute");
+ if (paramValue == null) {
+ throw new MalformedCookieException(
+ "Missing value for path attribute");
}
- if (param_value.trim().equals("")) {
- throw new MalformedCookieException("Blank value for path attribute");
+ if (paramValue.trim().equals("")) {
+ throw new MalformedCookieException(
+ "Blank value for path attribute");
}
- cookie.setPath(param_value);
+ cookie.setPath(paramValue);
cookie.setPathAttributeSpecified(true);
- }
- else if (param_name.equals("domain")) {
+ } else if (paramName.equals("domain")) {
- if (param_value == null) {
- throw new MalformedCookieException("Missing value for domain attribute");
+ if (paramValue == null) {
+ throw new MalformedCookieException(
+ "Missing value for domain attribute");
}
- if (param_value.trim().equals("")) {
- throw new MalformedCookieException("Blank value for domain attribute");
+ if (paramValue.trim().equals("")) {
+ throw new MalformedCookieException(
+ "Blank value for domain attribute");
}
- cookie.setDomain(param_value);
+ cookie.setDomain(paramValue);
cookie.setDomainAttributeSpecified(true);
- }
- else if (param_name.equals("max-age")) {
+ } else if (paramName.equals("max-age")) {
- if (param_value == null) {
- throw new MalformedCookieException("Missing value for max-age attribute");
+ if (paramValue == null) {
+ throw new MalformedCookieException(
+ "Missing value for max-age attribute");
}
int age;
try {
- age = Integer.parseInt(param_value);
+ age = Integer.parseInt(paramValue);
} catch (NumberFormatException e) {
- throw new MalformedCookieException( "Invalid max-age attribute: " + e.getMessage());
+ throw new MalformedCookieException ("Invalid max-age "
+ + "attribute: " + e.getMessage());
}
- cookie.setExpiryDate(new Date(System.currentTimeMillis() +
- age * 1000L));
+ cookie.setExpiryDate(
+ new Date(System.currentTimeMillis() + age * 1000L));
- }
- else if (param_name.equals("secure")) {
+ } else if (paramName.equals("secure")) {
cookie.setSecure(true);
- }
- else if (param_name.equals("comment")) {
+ } else if (paramName.equals("comment")) {
- cookie.setComment(param_value);
+ cookie.setComment(paramValue);
- }
- else if (param_name.equals("expires")) {
+ } else if (paramName.equals("expires")) {
- if (param_value == null) {
- throw new MalformedCookieException("Missing value for expires attribute");
+ if (paramValue == null) {
+ throw new MalformedCookieException(
+ "Missing value for expires attribute");
}
boolean set = false;
// trim single quotes around expiry if present
// see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=5279
- if(param_value.length() > 1 &&
- param_value.startsWith("'") &&
- param_value.endsWith("'")) {
- param_value = param_value.substring(1,param_value.length()-1);
+ if (paramValue.length() > 1
+ && paramValue.startsWith("'")
+ && paramValue.endsWith("'")) {
+ paramValue
+ = paramValue.substring (1, paramValue.length() - 1);
}
- for(int k=0;k<expiryFormats.length;k++) {
+ for (int k = 0; k < EXPIRY_FORMATS.length; k++) {
try {
- Date date = expiryFormats[k].parse(param_value);
+ Date date = EXPIRY_FORMATS[k].parse(paramValue);
cookie.setExpiryDate(date);
set = true;
break;
@@ -367,14 +369,15 @@
//Ignore and move on
}
}
- if(!set) {
- throw new MalformedCookieException("Unable to parse expiration date parameter: " + param_value);
+ if (!set) {
+ throw new MalformedCookieException(
+ "Unable to parse expiration date parameter: "
+ + paramValue);
}
- }
- else {
- if (log.isWarnEnabled())
- {
- log.warn("Unrecognized cookie attribute: " + attribute.toString());
+ } else {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Unrecognized cookie attribute: "
+ + attribute.toString());
}
}
}
@@ -386,103 +389,108 @@
* @param host the host from which the {@link Cookie} was received
* @param port the port from which the {@link Cookie} was received
* @param path the path from which the {@link Cookie} was received
- * @param secure <tt>true</tt> when the {@link Cookie} was received using a secure connection
- * @throws MalformedCookieException if an exception occurs during validation
- * @throws java.lang.IllegalArgumentException if an input parameter is illegal
+ * @param secure <tt>true</tt> when the {@link Cookie} was received using a
+ * secure connection
+ * @param cookie The cookie to validate.
+ * @throws MalformedCookieException if an exception occurs during
+ * validation
*/
- public void validate(String host, int port, String path, boolean secure, final Cookie cookie) throws MalformedCookieException
- {
- log.trace("enter CookieSpecBase.validate(String, port, path, boolean, Cookie)");
- if(host == null)
- {
- throw new IllegalArgumentException("Host of origin may not be null");
- }
- if(host.trim().equals(""))
- {
- throw new IllegalArgumentException("Host of origin may not be blank");
+ public void validate(String host, int port, String path,
+ boolean secure, final Cookie cookie)
+ throws MalformedCookieException {
+
+ LOG.trace("enter CookieSpecBase.validate("
+ + "String, port, path, boolean, Cookie)");
+ if (host == null) {
+ throw new IllegalArgumentException(
+ "Host of origin may not be null");
+ }
+ if (host.trim().equals("")) {
+ throw new IllegalArgumentException(
+ "Host of origin may not be blank");
}
- if(port < 0)
- {
+ if (port < 0) {
throw new IllegalArgumentException("Invalid port: " + port);
}
- if(path == null)
- {
- throw new IllegalArgumentException("Path of origin may not be null.");
+ if (path == null) {
+ throw new IllegalArgumentException(
+ "Path of origin may not be null.");
}
if (path.trim().equals("")) {
path = PATH_DELIM;
}
host = host.toLowerCase();
// check version
- if (cookie.getVersion() < 0)
- {
- throw new MalformedCookieException( "Illegal version number " + cookie.getValue());
+ if (cookie.getVersion() < 0) {
+ throw new MalformedCookieException ("Illegal version number "
+ + cookie.getValue());
}
// security check... we musn't allow the server to give us an
// invalid domain scope
- // 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.
- if (host.indexOf(".") >= 0)
- {
+ // 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.
+ if (host.indexOf(".") >= 0) {
// 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(cookie.getDomain()))
- {
+ if (!host.endsWith(cookie.getDomain())) {
throw new MalformedCookieException(
- "Illegal domain attribute \"" + cookie.getDomain() + "\". Domain of origin: \"" + host + "\"");
+ "Illegal domain attribute \"" + cookie.getDomain()
+ + "\". Domain of origin: \"" + host + "\"");
}
}
// another security check... we musn't allow the server to give us a
// cookie that doesn't match this path
- if(!path.startsWith(cookie.getPath()))
- {
+ if (!path.startsWith(cookie.getPath())) {
throw new MalformedCookieException(
- "Illegal path attribute \"" + cookie.getPath() + "\". Path of origin: \"" + path + "\"");
+ "Illegal path attribute \"" + cookie.getPath()
+ + "\". Path of origin: \"" + path + "\"");
}
}
/**
- * Return <tt>true</tt> if the cookie should be submitted with a request with
- * given attributes, <tt>false</tt> otherwise.
+ * Return <tt>true</tt> if the cookie should be submitted with a request
+ * with given attributes, <tt>false</tt> otherwise.
* @param host the host to which the request is being submitted
* @param port the port to which the request is being submitted (ignored)
* @param path the path to which the request is being submitted
* @param secure <tt>true</tt> if the request is using a secure connection
- * @param {@link Cookie} to be matched
+ * @param cookie {@link Cookie} to be matched
* @return true if the cookie matches the criterium
*/
- public boolean match(String host, int port, String path, boolean secure, final Cookie cookie)
- {
- log.trace("enter CookieSpecBase.match(String, int, String, boolean, Cookie");
- if(host == null)
- {
- throw new IllegalArgumentException("Host of origin may not be null");
- }
- if(host.trim().equals(""))
- {
- throw new IllegalArgumentException("Host of origin may not be blank");
+ public boolean match(String host, int port, String path,
+ boolean secure, final Cookie cookie) {
+
+ LOG.trace("enter CookieSpecBase.match("
+ + "String, int, String, boolean, Cookie");
+
+ if (host == null) {
+ throw new IllegalArgumentException(
+ "Host of origin may not be null");
+ }
+ if (host.trim().equals("")) {
+ throw new IllegalArgumentException(
+ "Host of origin may not be blank");
}
- if(port < 0)
- {
+ if (port < 0) {
throw new IllegalArgumentException("Invalid port: " + port);
}
- if(path == null)
- {
- throw new IllegalArgumentException("Path of origin may not be null.");
+ if (path == null) {
+ throw new IllegalArgumentException(
+ "Path of origin may not be null.");
}
- if(cookie == null)
- {
+ if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (path.trim().equals("")) {
@@ -490,44 +498,55 @@
}
host = host.toLowerCase();
if (cookie.getDomain() == null) {
- log.warn("Invalid cookie state: domain not specified");
+ LOG.warn("Invalid cookie state: domain not specified");
return false;
}
if (cookie.getPath() == null) {
- log.warn("Invalid cookie state: path not specified");
+ LOG.warn("Invalid cookie state: path not specified");
return false;
}
- return (
- (cookie.getExpiryDate() == null ||
- cookie.getExpiryDate().after(new Date())) && // only add the cookie if it hasn't yet expired
- (domainMatch(host, cookie.getDomain())) && // and the domain pattern matches
- (pathMatch(path, cookie.getPath())) && // and the path is null or matching
- (cookie.getSecure() ? secure : true) // and if the secure flag is set, only if the request is actually secure
- );
+ return
+ // only add the cookie if it hasn't yet expired
+ (cookie.getExpiryDate() == null
+ || cookie.getExpiryDate().after(new Date()))
+ // and the domain pattern matches
+ && (domainMatch(host, cookie.getDomain()))
+ // and the path is null or matching
+ && (pathMatch(path, cookie.getPath()))
+ // and if the secure flag is set, only if the request is
+ // actually secure
+ && (cookie.getSecure() ? secure : true);
}
/**
* Performs a domain-match as described in RFC2109.
+ * @param host The host to check.
+ * @param domain The domain.
+ * @return true if the specified host matches the given domain.
*/
- private static boolean domainMatch(String host, String domain)
- {
- boolean match = host.equals(domain) ||
- (domain.startsWith(".") && host.endsWith(domain));
+ private static boolean domainMatch(String host, String domain) {
+ boolean match = host.equals(domain)
+ || (domain.startsWith(".") && host.endsWith(domain));
return match;
}
/**
- * Performs a path-match slightly smarter than a straight-forward startsWith check.
+ * Performs a path-match slightly smarter than a straight-forward startsWith
+ * check.
+ * @param path The path to check.
+ * @param topmostPath The path to check against.
+ * @return true if the paths match
*/
- private static boolean pathMatch(final String path, final String topmostPath)
- {
- boolean match = path.startsWith( topmostPath );
+ private static boolean pathMatch(
+ final String path, final String topmostPath) {
+
+ boolean match = path.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 && path.length() != topmostPath.length() ) {
+ if (match && path.length() != topmostPath.length()) {
if (!topmostPath.endsWith(PATH_DELIM)) {
match = (path.charAt(topmostPath.length()) == PATH_DELIM_CHAR);
}
@@ -536,38 +555,39 @@
}
/**
- * Return an array of {@link Cookie}s that should be submitted with a request with
- * given attributes, <tt>false</tt> otherwise.
+ * Return an array of {@link Cookie}s that should be submitted with a
+ * request with given attributes, <tt>false</tt> otherwise.
* @param host the host to which the request is being submitted
- * @param port the port to which the request is being submitted (currenlty ignored)
+ * @param port the port to which the request is being submitted (currently
+ * ignored)
* @param path the path to which the request is being submitted
* @param secure <tt>true</tt> if the request is using a secure protocol
- * @param an array of <tt>Cookie</tt>s to be matched
+ * @param cookies an array of <tt>Cookie</tt>s to be matched
* @return an array of <tt>Cookie</tt>s matching the criterium
*/
- public Cookie[] match(String host, int port, String path, boolean secure, final Cookie cookies[])
- {
- log.trace("enter CookieSpecBase.match(String, int, String, boolean, Cookie[])");
-
- if(host == null)
- {
- throw new IllegalArgumentException("Host of origin may not be null");
- }
- if(host.trim().equals(""))
- {
- throw new IllegalArgumentException("Host of origin may not be blank");
+ public Cookie[] match(String host, int port, String path,
+ boolean secure, final Cookie cookies[]) {
+
+ LOG.trace("enter CookieSpecBase.match("
+ + "String, int, String, boolean, Cookie[])");
+
+ if (host == null) {
+ throw new IllegalArgumentException(
+ "Host of origin may not be null");
+ }
+ if (host.trim().equals("")) {
+ throw new IllegalArgumentException(
+ "Host of origin may not be blank");
}
- if(port < 0)
- {
+ if (port < 0) {
throw new IllegalArgumentException("Invalid port: " + port);
}
- if(path == null)
- {
- throw new IllegalArgumentException("Path of origin may not be null.");
+ if (path == null) {
+ throw new IllegalArgumentException(
+ "Path of origin may not be null.");
}
- if(cookies == null)
- {
+ if (cookies == null) {
throw new IllegalArgumentException("Cookie array may not be null");
}
if (path.trim().equals("")) {
@@ -581,33 +601,30 @@
return null;
}
List matching = new LinkedList();
- for(int i=0;i<cookies.length;i++)
- {
- if(match(host, port, path, secure, cookies[i]))
- {
+ for (int i = 0; i < cookies.length; i++) {
+ if (match(host, port, path, secure, cookies[i])) {
addInPathOrder(matching, cookies[i]);
}
}
- return (Cookie[])matching.toArray(new Cookie[matching.size()]);
+ return (Cookie[]) matching.toArray(new Cookie[matching.size()]);
}
/**
- * Adds the given cookie into the given list in descending path order. That is,
- * more specific path to least specific paths. This may not be the fastest
- * algorythm, but it'll work OK for the small number of cookies we're
- * generally dealing with.
+ * Adds the given cookie into the given list in descending path order. That
+ * is, more specific path to least specific paths. This may not be the
+ * fastest algorythm, but it'll work OK for the small number of cookies
+ * we're generally dealing with.
*
* @param list - the list to add the cookie to
* @param addCookie - the Cookie to add to list
*/
- private static void addInPathOrder(List list, Cookie addCookie)
- {
+ private static void addInPathOrder(List list, Cookie addCookie) {
int i = 0;
- for(i=0;i<list.size();i++){
- Cookie c = (Cookie)list.get(i);
- if(addCookie.compare(addCookie, c) > 0){
+ for (i = 0; i < list.size(); i++) {
+ Cookie c = (Cookie) list.get(i);
+ if (addCookie.compare(addCookie, c) > 0) {
break;
}
}
@@ -616,15 +633,12 @@
/**
* Return a string suitable for sending in a <tt>"Cookie"</tt> header
- * @param a {@link Cookie} to be formatted as string
+ * @param cookie a {@link Cookie} to be formatted as string
* @return a string suitable for sending in a <tt>"Cookie"</tt> header.
*/
-
- public String formatCookie(Cookie cookie)
- {
- log.trace("enter CookieSpecBase.formatCookie(Cookie)");
- if(cookie == null)
- {
+ public String formatCookie(Cookie cookie) {
+ LOG.trace("enter CookieSpecBase.formatCookie(Cookie)");
+ if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
StringBuffer buf = new StringBuffer();
@@ -633,31 +647,26 @@
}
/**
- * Create a <tt>"Cookie"</tt> header value containing all {@link Cookie}s in <i>cookies</i>
- * suitable for sending in a <tt>"Cookie"</tt> header
- * @param an array of {@link Cookie}s to be formatted
+ * Create a <tt>"Cookie"</tt> header value containing all {@link Cookie}s in
+ * <i>cookies</i> suitable for sending in a <tt>"Cookie"</tt> header
+ * @param cookies an array of {@link Cookie}s to be formatted
* @return a string suitable for sending in a Cookie header.
- * @throws java.lang.IllegalArgumentException if an input parameter is illegal
+ * @throws IllegalArgumentException if an input parameter is illegal
*/
public String formatCookies(Cookie[] cookies)
- throws IllegalArgumentException
- {
- log.trace("enter CookieSpecBase.formatCookies(Cookie[])");
- if(cookies == null)
- {
+ throws IllegalArgumentException {
+ LOG.trace("enter CookieSpecBase.formatCookies(Cookie[])");
+ if (cookies == null) {
throw new IllegalArgumentException("Cookie array may not be null");
}
- if(cookies.length == 0)
- {
+ if (cookies.length == 0) {
throw new IllegalArgumentException("Cookie array may not be empty");
}
StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < cookies.length; i++)
- {
- if (i > 0)
- {
+ for (int i = 0; i < cookies.length; i++) {
+ if (i > 0) {
buffer.append("; ");
}
buffer.append(formatCookie(cookies[i]));
@@ -667,29 +676,26 @@
/**
- * Create a <tt>"Cookie"</tt> {@link Header} containing all {@link Cookie}s in <i>cookies</i>.
- * @param an array of {@link Cookie}s to be formatted as a <tt>"Cookie"</tt> header
+ * Create a <tt>"Cookie"</tt> {@link Header} containing all {@link Cookie}s
+ * in <i>cookies</i>.
+ * @param cookies an array of {@link Cookie}s to be formatted as a <tt>"
+ * Cookie"</tt> header
* @return a <tt>"Cookie"</tt> {@link Header}.
- * @throws java.lang.IllegalArgumentException if an input parameter is illegal
*/
-
- public Header formatCookieHeader(Cookie[] cookies)
- {
- log.trace("enter CookieSpecBase.formatCookieHeader(Cookie[])");
+ public Header formatCookieHeader(Cookie[] cookies) {
+ LOG.trace("enter CookieSpecBase.formatCookieHeader(Cookie[])");
return new Header("Cookie", formatCookies(cookies));
}
/**
* Create a <tt>"Cookie"</tt> {@link Header} containing the {@link Cookie}.
- * @param <tt>Cookie</tt>s to be formatted as a <tt>Cookie</tt> header
+ * @param cookie <tt>Cookie</tt>s to be formatted as a <tt>Cookie</tt>
+ * header
* @return a Cookie header.
- * @throws java.lang.IllegalArgumentException if an input parameter is illegal
*/
-
- public Header formatCookieHeader(Cookie cookie)
- {
- log.trace("enter CookieSpecBase.formatCookieHeader(Cookie)");
+ public Header formatCookieHeader(Cookie cookie) {
+ LOG.trace("enter CookieSpecBase.formatCookieHeader(Cookie)");
return new Header("Cookie", formatCookie(cookie));
}
1.4 +5 -4 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/cookie/MalformedCookieException.java
Index: MalformedCookieException.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/cookie/MalformedCookieException.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- MalformedCookieException.java 26 Jan 2003 06:59:20 -0000 1.3
+++ MalformedCookieException.java 27 Jan 2003 15:25:47 -0000 1.4
@@ -2,6 +2,7 @@
* $Header$
* $Revision$
* $Date$
+ *
* ====================================================================
*
* The Apache Software License, Version 1.1
@@ -28,7 +29,7 @@
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
- * 4. The names "The Jakarta Project", "HttpClient", and "Apache Software
+ * 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
1.6 +70 -69 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/cookie/NetscapeDraftSpec.java
Index: NetscapeDraftSpec.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/cookie/NetscapeDraftSpec.java,v
retrieving revision 1.5
retrieving revision 1.6
diff -u -r1.5 -r1.6
--- NetscapeDraftSpec.java 23 Jan 2003 22:48:06 -0000 1.5
+++ NetscapeDraftSpec.java 27 Jan 2003 15:25:47 -0000 1.6
@@ -2,6 +2,7 @@
* $Header$
* $Revision$
* $Date$
+ *
* ====================================================================
*
* The Apache Software License, Version 1.1
@@ -28,7 +29,7 @@
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
- * 4. The names "The Jakarta Project", "HttpClient", and "Apache Software
+ * 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
@@ -83,61 +84,57 @@
* @author <a href="mailto:JEvans@Cyveillance.com">John Evans</a>
* @author Marc A. Saegesser
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
+ * @author <a href="mailto:mbowler@GargoyleSoftware.com>Mike Bowler</a>
*
* @since 2.0
*/
-public class NetscapeDraftSpec extends CookieSpecBase
-{
+public class NetscapeDraftSpec extends CookieSpecBase {
/** Default constructor */
-
- public NetscapeDraftSpec()
- {
+ public NetscapeDraftSpec() {
super();
}
/**
- * Parse the cookie attribute and update the corresponsing {@link Cookie} properties
- * as defined by the Netscape draft specification
+ * Parse the cookie attribute and update the corresponsing {@link Cookie}
+ * properties as defined by the Netscape draft specification
*
- * @param attribute {@link NameValuePair} cookie attribute from the <tt>Set-Cookie</tt>
+ * @param attribute {@link NameValuePair} cookie attribute from the
+ * <tt>Set- Cookie</tt>
* @param cookie {@link Cookie} to be updated
* @throws MalformedCookieException if an exception occurs during parsing
- * @throws java.lang.IllegalArgumentException if an input parameter is illegal
*/
-
- public void parseAttribute(final NameValuePair attribute, final Cookie cookie)
- throws MalformedCookieException
- {
- if(attribute == null)
- {
+ public void parseAttribute(
+ final NameValuePair attribute, final Cookie cookie)
+ throws MalformedCookieException {
+
+ if (attribute == null) {
throw new IllegalArgumentException("Attribute may not be null.");
}
- if(cookie == null)
- {
+ if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null.");
}
- String param_name = attribute.getName().toLowerCase();
- String param_value = attribute.getValue();
+ final String paramName = attribute.getName().toLowerCase();
+ final String paramValue = attribute.getValue();
- if (param_name.equals("expires")) {
+ if (paramName.equals("expires")) {
- if (param_value == null) {
- throw new MalformedCookieException("Missing value for expires attribute");
+ if (paramValue == null) {
+ throw new MalformedCookieException(
+ "Missing value for expires attribute");
}
- try
- {
- DateFormat expiryFormat = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US);
- Date date = expiryFormat.parse(param_value);
+ try {
+ DateFormat expiryFormat = new SimpleDateFormat(
+ "EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US);
+ Date date = expiryFormat.parse(paramValue);
cookie.setExpiryDate(date);
- }
- catch (ParseException e) {
- throw new MalformedCookieException("Invalid expires attribute: " + e.getMessage());
+ } catch (ParseException e) {
+ throw new MalformedCookieException("Invalid expires "
+ + "attribute: " + e.getMessage());
}
- }
- else {
+ } else {
super.parseAttribute(attribute, cookie);
}
}
@@ -148,55 +145,59 @@
* @param host the host from which the {@link Cookie} was received
* @param port the port from which the {@link Cookie} was received
* @param path the path from which the {@link Cookie} was received
- * @param secure <tt>true</tt> when the {@link Cookie} was received using a secure connection
- * @throws MalformedCookieException if an exception occurs during validation
- * @throws java.lang.IllegalArgumentException if an input parameter is illegal
+ * @param secure <tt>true</tt> when the {@link Cookie} was received
+ * using a secure connection
+ * @param cookie The cookie to validate.
+ * @throws MalformedCookieException if an exception occurs during
+ * validation
*/
-
- public void validate(String host, int port, String path, boolean secure, final Cookie cookie) throws MalformedCookieException
- {
- log.trace("enterNetscapeDraftCookieProcessor RCF2109CookieProcessor.validate(Cookie)");
+ public void validate(String host, int port, String path,
+ boolean secure, final Cookie cookie)
+ throws MalformedCookieException {
+
+ LOG.trace("enterNetscapeDraftCookieProcessor "
+ + "RCF2109CookieProcessor.validate(Cookie)");
// Perform generic validation
super.validate(host, port, path, secure, cookie);
// Perform Netscape Cookie draft specific validation
- if (host.indexOf(".") >= 0)
- {
- int domainParts = new StringTokenizer(cookie.getDomain(), ".").countTokens();
-
- if (isSpecialDomain(cookie.getDomain()))
- {
- if(domainParts < 2)
- {
- throw new MalformedCookieException("Domain attribute \""+ cookie.getDomain() + "\" violates the Netscape cookie specification for special domains");
+ if (host.indexOf(".") >= 0) {
+ int domainParts = new StringTokenizer(cookie.getDomain(), ".")
+ .countTokens();
+
+ if (isSpecialDomain(cookie.getDomain())) {
+ if (domainParts < 2) {
+ throw new MalformedCookieException("Domain attribute \""
+ + cookie.getDomain()
+ + "\" violates the Netscape cookie specification for "
+ + "special domains");
}
+ } else {
+ if (domainParts < 3) {
+ throw new MalformedCookieException("Domain attribute \""
+ + cookie.getDomain()
+ + "\" violates the Netscape cookie specification");
+ }
}
- else
- {
- if(domainParts < 3)
- {
- throw new MalformedCookieException("Domain attribute \""+ cookie.getDomain() + "\" 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(String domain)
- {
- String ucDomain = domain.toUpperCase();
- if(ucDomain.endsWith(".COM") ||
- ucDomain.endsWith(".EDU") ||
- ucDomain.endsWith(".NET") ||
- ucDomain.endsWith(".GOV") ||
- ucDomain.endsWith(".MIL") ||
- ucDomain.endsWith(".ORG") ||
- ucDomain.endsWith(".INT")){
+ private static boolean isSpecialDomain(final String domain) {
+ final String ucDomain = domain.toUpperCase();
+ if (ucDomain.endsWith(".COM")
+ || ucDomain.endsWith(".EDU")
+ || ucDomain.endsWith(".NET")
+ || ucDomain.endsWith(".GOV")
+ || ucDomain.endsWith(".MIL")
+ || ucDomain.endsWith(".ORG")
+ || ucDomain.endsWith(".INT")) {
return true;
}
return false;
}
-
}
1.6 +108 -104 jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/cookie/RFC2109Spec.java
Index: RFC2109Spec.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/cookie/RFC2109Spec.java,v
retrieving revision 1.5
retrieving revision 1.6
diff -u -r1.5 -r1.6
--- RFC2109Spec.java 23 Jan 2003 22:48:06 -0000 1.5
+++ RFC2109Spec.java 27 Jan 2003 15:25:47 -0000 1.6
@@ -2,6 +2,7 @@
* $Header$
* $Revision$
* $Date$
+ *
* ====================================================================
*
* The Apache Software License, Version 1.1
@@ -28,7 +29,7 @@
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
- * 4. The names "The Jakarta Project", "HttpClient", and "Apache Software
+ * 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
@@ -78,58 +79,55 @@
* @author <a href="mailto:JEvans@Cyveillance.com">John Evans</a>
* @author Marc A. Saegesser
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
+ * @author <a href="mailto:mbowler@GargoyleSoftware.com>Mike Bowler</a>
*
* @since 2.0
*/
-public class RFC2109Spec extends CookieSpecBase
-{
+public class RFC2109Spec extends CookieSpecBase {
- /** Default constructor */
-
- public RFC2109Spec()
- {
+ /** Default constructor */
+ public RFC2109Spec() {
super();
}
/**
- * Parse RFC 2109 specific cookie attribute and update the corresponsing {@link Cookie}
- * properties.
+ * Parse RFC 2109 specific cookie attribute and update the corresponsing
+ * {@link Cookie} properties.
*
- * @param attribute {@link NameValuePair} cookie attribute from the <tt>Set-Cookie</tt>
+ * @param attribute {@link NameValuePair} cookie attribute from the
+ * <tt>Set- Cookie</tt>
* @param cookie {@link Cookie} to be updated
* @throws MalformedCookieException if an exception occurs during parsing
- * @throws java.lang.IllegalArgumentException if an input parameter is illegal
*/
-
- public void parseAttribute(final NameValuePair attribute, final Cookie cookie)
- throws MalformedCookieException
- {
- if(attribute == null)
- {
+ public void parseAttribute(
+ final NameValuePair attribute, final Cookie cookie)
+ throws MalformedCookieException {
+
+ if (attribute == null) {
throw new IllegalArgumentException("Attribute may not be null.");
}
- if(cookie == null)
- {
+ if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null.");
}
- String param_name = attribute.getName().toLowerCase();
- String param_value = attribute.getValue();
+ final String paramName = attribute.getName().toLowerCase();
+ final String paramValue = attribute.getValue();
- if (param_name.equals("version")) {
+ if (paramName.equals("version")) {
- if (param_value == null) {
- throw new MalformedCookieException("Missing value for version attribute");
+ if (paramValue == null) {
+ throw new MalformedCookieException(
+ "Missing value for version attribute");
}
try {
- cookie.setVersion(Integer.parseInt(param_value));
+ cookie.setVersion(Integer.parseInt(paramValue));
} catch (NumberFormatException e) {
- throw new MalformedCookieException( "Invalid version attribute: " + e.getMessage());
+ throw new MalformedCookieException("Invalid version: "
+ + e.getMessage());
}
- }
- else {
+ } else {
super.parseAttribute(attribute, cookie);
}
}
@@ -140,82 +138,94 @@
* @param host the host from which the {@link Cookie} was received
* @param port the port from which the {@link Cookie} was received
* @param path the path from which the {@link Cookie} was received
- * @param secure <tt>true</tt> when the {@link Cookie} was received using a secure connection
- * @throws MalformedCookieException if an exception occurs during validation
- * @throws java.lang.IllegalArgumentException if an input parameter is illegal
+ * @param secure <tt>true</tt> when the {@link Cookie} was received using a
+ * secure connection
+ * @param cookie The cookie to validate
+ * @throws MalformedCookieException if an exception occurs during
+ * validation
*/
-
- public void validate(String host, int port, String path, boolean secure, final Cookie cookie) throws MalformedCookieException
- {
- log.trace("enter RFC2109Spec.validate(String, int, String, boolean, Cookie)");
+ public void validate(String host, int port, String path,
+ boolean secure, final Cookie cookie) throws MalformedCookieException {
+
+ LOG.trace("enter RFC2109Spec.validate(String, int, String, "
+ + "boolean, Cookie)");
+
// Perform generic validation
super.validate(host, port, path, secure, cookie);
// Perform RFC 2109 specific validation
- if (cookie.isDomainAttributeSpecified() && (!cookie.getDomain().equals(host)))
- {
+ if (cookie.isDomainAttributeSpecified()
+ && (!cookie.getDomain().equals(host))) {
+
// domain must start with dot
- if (!cookie.getDomain().startsWith("."))
- {
- throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain() + "\" violates RFC 2109: domain must start with a dot");
+ if (!cookie.getDomain().startsWith(".")) {
+ throw new MalformedCookieException("Domain attribute \""
+ + cookie.getDomain()
+ + "\" violates RFC 2109: domain must start with a dot");
}
// domain must have at least one embedded dot
int dotIndex = cookie.getDomain().indexOf('.', 1);
- if(dotIndex < 0 || dotIndex == cookie.getDomain().length()-1)
- {
- throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain() + "\" violates RFC 2109: domain must contain an embedded dot");
+ if(dotIndex < 0 || dotIndex == cookie.getDomain().length() - 1) {
+ throw new MalformedCookieException("Domain attribute \""
+ + cookie.getDomain()
+ + "\" violates RFC 2109: domain must contain an "
+ + "embedded dot");
}
// host minus domain may not contain any dots
if (host.substring(0,
- host.length() -
- cookie.getDomain().length()).indexOf('.') != -1)
- {
- throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain() + "\" violates RFC 2109: host minus domain may not contain any dots");
+ host.length()
+ - cookie.getDomain().length()).indexOf('.') != -1) {
+ throw new MalformedCookieException("Domain attribute \""
+ + cookie.getDomain()
+ + "\" violates RFC 2109: host minus domain may not "
+ + "contain any dots");
}
}
}
/**
- * 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 a {@link Cookie} to be formatted as string
+ * 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 name The name.
+ * @param value The value
+ * @param version The cookie version
* @return a string suitable for sending in a <tt>"Cookie"</tt> header.
*/
- private String formatNameValuePair(final String name, final String value, int version)
- {
- StringBuffer buffer = new StringBuffer();
- if (version < 1)
- {
+ private String formatNameValuePair(
+ final String name, final String value, int version) {
+
+ final StringBuffer buffer = new StringBuffer();
+ if (version < 1) {
buffer.append(name).append("=").append(value);
- }
- else
- {
+ } else {
buffer.append(name).append("=\"").append(value).append("\"");
}
return buffer.toString();
-
}
/**
* 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 a {@link Cookie} to be formatted as string
+ * @param cookie a {@link Cookie} to be formatted as string
+ * @param version The version to use.
* @return a string suitable for sending in a <tt>"Cookie"</tt> header.
*/
-
- private String formatCookieAsVer(Cookie cookie, int version)
- {
- log.trace("enter RFC2109Spec.formatCookieAsVer(Cookie)");
- if(cookie == null)
- {
+ private String formatCookieAsVer(Cookie cookie, int version) {
+ LOG.trace("enter RFC2109Spec.formatCookieAsVer(Cookie)");
+ if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
StringBuffer buf = new StringBuffer();
- buf.append(formatNameValuePair(cookie.getName(), cookie.getValue(), version));
- if (cookie.getDomain() != null && cookie.isDomainAttributeSpecified()) {
+ buf.append(formatNameValuePair(cookie.getName(),
+ cookie.getValue(), version));
+ if (cookie.getDomain() != null
+ && cookie.isDomainAttributeSpecified()) {
+
buf.append("; ");
- buf.append(formatNameValuePair("$Domain", cookie.getDomain(), version));
+ buf.append(formatNameValuePair("$Domain",
+ cookie.getDomain(), version));
}
if (cookie.getPath() != null && cookie.isPathAttributeSpecified()) {
buf.append("; ");
@@ -226,46 +236,40 @@
/**
- * Return a string suitable for sending in a <tt>"Cookie"</tt> header as defined in RFC 2109
- * @param a {@link Cookie} to be formatted as string
+ * Return a string suitable for sending in a <tt>"Cookie"</tt> header as
+ * defined in RFC 2109
+ * @param cookie a {@link Cookie} to be formatted as string
* @return a string suitable for sending in a <tt>"Cookie"</tt> header.
*/
-
- public String formatCookie(Cookie cookie)
- {
- log.trace("enter RFC2109Spec.formatCookie(Cookie)");
- if(cookie == null)
- {
+ public String formatCookie(Cookie cookie) {
+ LOG.trace("enter RFC2109Spec.formatCookie(Cookie)");
+ if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
return formatCookieAsVer(cookie, cookie.getVersion());
}
/**
- * Create a RFC 2109 compliant <tt>"Cookie"</tt> header value containing all
- * {@link Cookie}s in <i>cookies</i> suitable for sending in a <tt>"Cookie"</tt> header
- * @param an array of {@link Cookie}s to be formatted
+ * Create a RFC 2109 compliant <tt>"Cookie"</tt> header value containing all
+ * {@link Cookie}s in <i>cookies</i> suitable for sending in a <tt>"Cookie"
+ * </tt> header
+ * @param cookies an array of {@link Cookie}s to be formatted
* @return a string suitable for sending in a Cookie header.
- * @throws java.lang.IllegalArgumentException if an input parameter is illegal
*/
-
- public String formatCookies(Cookie[] cookies)
- {
- log.trace("enter RFC2109Spec.formatCookieHeader(Cookie[])");
+ public String formatCookies(Cookie[] cookies) {
+ LOG.trace("enter RFC2109Spec.formatCookieHeader(Cookie[])");
int version = Integer.MAX_VALUE;
// Pick the lowerest common denominator
- for (int i = 0; i < cookies.length; i++)
- {
+ for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
- if (cookie.getVersion() < version)
- {
+ if (cookie.getVersion() < version) {
version = cookie.getVersion();
}
}
- StringBuffer buffer = new StringBuffer();
- buffer.append(formatNameValuePair("$Version", Integer.toString(version), version));
- for (int i = 0; i < cookies.length; i++)
- {
+ final StringBuffer buffer = new StringBuffer();
+ buffer.append(formatNameValuePair("$Version",
+ Integer.toString(version), version));
+ for (int i = 0; i < cookies.length; i++) {
buffer.append("; ");
buffer.append(formatCookieAsVer(cookies[i], version));
}
@@ -274,17 +278,17 @@
/**
- * Create a RFC 2109 compliant <tt>"Cookie"</tt> {@link Header} containing the {@link Cookie}.
- * @param <tt>Cookie</tt>s to be formatted as a <tt>Cookie</tt> header
+ * Create a RFC 2109 compliant <tt>"Cookie"</tt> {@link Header} containing
+ * the {@link Cookie}.
+ * @param cookie <tt>Cookie</tt>s to be formatted as a <tt>Cookie</tt>
+ * header
* @return a Cookie header.
- * @throws java.lang.IllegalArgumentException if an input parameter is illegal
*/
-
- public Header formatCookieHeader(Cookie cookie)
- {
- log.trace("enter RFC2109Spec.formatCookieHeader(Cookie)");
+ public Header formatCookieHeader(Cookie cookie) {
+ LOG.trace("enter RFC2109Spec.formatCookieHeader(Cookie)");
StringBuffer buffer = new StringBuffer();
- buffer.append(formatNameValuePair("$Version", Integer.toString(cookie.getVersion()), cookie.getVersion()));
+ buffer.append(formatNameValuePair("$Version",
+ Integer.toString(cookie.getVersion()), cookie.getVersion()));
buffer.append("; ");
buffer.append(formatCookie(cookie));
return new Header("Cookie", buffer.toString());
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>