New code style. No functional changes.

This commit is contained in:
Harald Kuhr
2011-02-17 12:36:40 +01:00
parent 191643a36c
commit 43cc440e67
60 changed files with 1671 additions and 1665 deletions
@@ -37,11 +37,10 @@ import java.net.*;
* @see SimpleAuthenticator
* @see java.net.Authenticator
*
* @author Harald Kuhr (haraldk@iconmedialab.no),
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version 1.0
*/
public interface AuthenticatorFilter {
public boolean accept(InetAddress pAddress, int pPort, String pProtocol,
String pPrompt, String pScheme);
public boolean accept(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme);
}
@@ -0,0 +1,144 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name "TwelveMonkeys" nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.net;
import com.twelvemonkeys.io.*;
import com.twelvemonkeys.io.enc.Base64Decoder;
import com.twelvemonkeys.io.enc.DecoderStream;
import java.io.*;
/**
* This class does BASE64 encoding (and decoding).
*
* @author unascribed
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/util/BASE64.java#1 $
* @deprecated Use {@link com.twelvemonkeys.io.enc.Base64Encoder}/{@link Base64Decoder} instead
*/
class BASE64 {
/**
* This array maps the characters to their 6 bit values
*/
private final static char[] PEM_ARRAY = {
//0 1 2 3 4 5 6 7
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 0
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 1
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 2
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', // 3
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 4
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', // 5
'w', 'x', 'y', 'z', '0', '1', '2', '3', // 6
'4', '5', '6', '7', '8', '9', '+', '/' // 7
};
/**
* Encodes the input data using the standard base64 encoding scheme.
*
* @param pData the bytes to encode to base64
* @return a string with base64 encoded data
*/
public static String encode(byte[] pData) {
int offset = 0;
int len;
StringBuilder buf = new StringBuilder();
while ((pData.length - offset) > 0) {
byte a, b, c;
if ((pData.length - offset) > 2) {
len = 3;
}
else {
len = pData.length - offset;
}
switch (len) {
case 1:
a = pData[offset];
b = 0;
buf.append(PEM_ARRAY[(a >>> 2) & 0x3F]);
buf.append(PEM_ARRAY[((a << 4) & 0x30) + ((b >>> 4) & 0xf)]);
buf.append('=');
buf.append('=');
offset++;
break;
case 2:
a = pData[offset];
b = pData[offset + 1];
c = 0;
buf.append(PEM_ARRAY[(a >>> 2) & 0x3F]);
buf.append(PEM_ARRAY[((a << 4) & 0x30) + ((b >>> 4) & 0xf)]);
buf.append(PEM_ARRAY[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)]);
buf.append('=');
offset += offset + 2; // ???
break;
default:
a = pData[offset];
b = pData[offset + 1];
c = pData[offset + 2];
buf.append(PEM_ARRAY[(a >>> 2) & 0x3F]);
buf.append(PEM_ARRAY[((a << 4) & 0x30) + ((b >>> 4) & 0xf)]);
buf.append(PEM_ARRAY[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)]);
buf.append(PEM_ARRAY[c & 0x3F]);
offset = offset + 3;
break;
}
}
return buf.toString();
}
public static byte[] decode(String pData) throws IOException {
InputStream in = new DecoderStream(new ByteArrayInputStream(pData.getBytes()), new Base64Decoder());
ByteArrayOutputStream bytes = new FastByteArrayOutputStream(pData.length() * 3);
FileUtil.copy(in, bytes);
return bytes.toByteArray();
}
//private final static sun.misc.BASE64Decoder DECODER = new sun.misc.BASE64Decoder();
public static void main(String[] pArgs) throws IOException {
if (pArgs.length == 1) {
System.out.println(encode(pArgs[0].getBytes()));
}
else
if (pArgs.length == 2 && ("-d".equals(pArgs[0]) || "--decode".equals(pArgs[0])))
{
System.out.println(new String(decode(pArgs[1])));
}
else {
System.err.println("BASE64 [ -d | --decode ] arg");
System.err.println("Encodes or decodes a given string");
System.exit(5);
}
}
}
@@ -29,7 +29,6 @@
package com.twelvemonkeys.net;
import com.twelvemonkeys.lang.StringUtil;
import com.twelvemonkeys.util.BASE64;
import java.io.*;
import java.net.*;
@@ -65,18 +64,18 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
private final static String HTTP_HEADER_END = "\r\n\r\n";
private static final String HEADER_WWW_AUTH = "WWW-Authenticate";
private final static int BUF_SIZE = 8192;
private int mMaxRedirects = (System.getProperty("http.maxRedirects") != null)
private int maxRedirects = (System.getProperty("http.maxRedirects") != null)
? Integer.parseInt(System.getProperty("http.maxRedirects"))
: 20;
protected int mTimeout = -1;
protected int mConnectTimeout = -1;
private Socket mSocket = null;
protected InputStream mErrorStream = null;
protected InputStream mInputStream = null;
protected OutputStream mOutputStream = null;
private String[] mResponseHeaders = null;
protected Properties mResponseHeaderFields = null;
protected Properties mRequestProperties = new Properties();
protected int timeout = -1;
protected int connectTimeout = -1;
private Socket socket = null;
protected InputStream errorStream = null;
protected InputStream inputStream = null;
protected OutputStream outputStream = null;
private String[] responseHeaders = null;
protected Properties responseHeaderFields = null;
protected Properties requestProperties = new Properties();
/**
* Creates a HttpURLConnection.
@@ -114,7 +113,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
protected HttpURLConnection(URL pURL, int pTimeout, int pConnectTimeout) {
super(pURL);
setTimeout(pTimeout);
mConnectTimeout = pConnectTimeout;
connectTimeout = pConnectTimeout;
}
/**
@@ -135,13 +134,13 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
if (connected) {
throw new IllegalAccessError("Already connected");
}
String oldValue = mRequestProperties.getProperty(pKey);
String oldValue = requestProperties.getProperty(pKey);
if (oldValue == null) {
mRequestProperties.setProperty(pKey, pValue);
requestProperties.setProperty(pKey, pValue);
}
else {
mRequestProperties.setProperty(pKey, oldValue + ", " + pValue);
requestProperties.setProperty(pKey, oldValue + ", " + pValue);
}
}
@@ -158,7 +157,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
if (connected) {
throw new IllegalAccessError("Already connected");
}
return mRequestProperties.getProperty(pKey);
return requestProperties.getProperty(pKey);
}
/**
@@ -212,7 +211,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
* if there is no such field in the header.
*/
public String getHeaderField(String pName) {
return mResponseHeaderFields.getProperty(StringUtil.toLowerCase(pName));
return responseHeaderFields.getProperty(StringUtil.toLowerCase(pName));
}
/**
@@ -230,10 +229,10 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
*/
public String getHeaderField(int pIndex) {
// TODO: getInputStream() first, to make sure we have header fields
if (pIndex >= mResponseHeaders.length) {
if (pIndex >= responseHeaders.length) {
return null;
}
String field = mResponseHeaders[pIndex];
String field = responseHeaders[pIndex];
// pIndex == 0, means the response code etc (i.e. "HTTP/1.1 200 OK").
if ((pIndex == 0) || (field == null)) {
@@ -256,10 +255,10 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
*/
public String getHeaderFieldKey(int pIndex) {
// TODO: getInputStream() first, to make sure we have header fields
if (pIndex >= mResponseHeaders.length) {
if (pIndex >= responseHeaders.length) {
return null;
}
String field = mResponseHeaders[pIndex];
String field = responseHeaders[pIndex];
if (StringUtil.isEmpty(field)) {
return null;
@@ -283,10 +282,10 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
if (pTimeout < 0) { // Must be positive
throw new IllegalArgumentException("Timeout must be positive.");
}
mTimeout = pTimeout;
if (mSocket != null) {
timeout = pTimeout;
if (socket != null) {
try {
mSocket.setSoTimeout(pTimeout);
socket.setSoTimeout(pTimeout);
}
catch (SocketException se) {
// Not much to do about that...
@@ -305,12 +304,12 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
public int getTimeout() {
try {
return ((mSocket != null)
? mSocket.getSoTimeout()
: mTimeout);
return ((socket != null)
? socket.getSoTimeout()
: timeout);
}
catch (SocketException se) {
return mTimeout;
return timeout;
}
}
@@ -332,24 +331,24 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
}
int length;
if (mInputStream == null) {
if (inputStream == null) {
return null;
}
// "De-chunk" the output stream
else if ("chunked".equalsIgnoreCase(getHeaderField("Transfer-Encoding"))) {
if (!(mInputStream instanceof ChunkedInputStream)) {
mInputStream = new ChunkedInputStream(mInputStream);
if (!(inputStream instanceof ChunkedInputStream)) {
inputStream = new ChunkedInputStream(inputStream);
}
}
// Make sure we don't wait forever, if the content-length is known
else if ((length = getHeaderFieldInt("Content-Length", -1)) >= 0) {
if (!(mInputStream instanceof FixedLengthInputStream)) {
mInputStream = new FixedLengthInputStream(mInputStream, length);
if (!(inputStream instanceof FixedLengthInputStream)) {
inputStream = new FixedLengthInputStream(inputStream, length);
}
}
return mInputStream;
return inputStream;
}
/**
@@ -364,7 +363,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
if (!connected) {
connect();
}
return mOutputStream;
return outputStream;
}
/**
@@ -374,15 +373,15 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
* instance can be reused for other requests.
*/
public void disconnect() {
if (mSocket != null) {
if (socket != null) {
try {
mSocket.close();
socket.close();
}
catch (IOException ioe) {
// Does not matter, I guess.
}
mSocket = null;
socket = null;
}
connected = false;
}
@@ -397,37 +396,37 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
: HTTP_DEFAULT_PORT;
// Create socket if we don't have one
if (mSocket == null) {
//mSocket = new Socket(pURL.getHost(), port); // Blocks...
mSocket = createSocket(pURL, port, mConnectTimeout);
mSocket.setSoTimeout(mTimeout);
if (socket == null) {
//socket = new Socket(pURL.getHost(), port); // Blocks...
socket = createSocket(pURL, port, connectTimeout);
socket.setSoTimeout(timeout);
}
// Get Socket output stream
OutputStream os = mSocket.getOutputStream();
OutputStream os = socket.getOutputStream();
// Connect using HTTP
writeRequestHeaders(os, pURL, method, mRequestProperties, usingProxy(), pAuth, pAuthType);
writeRequestHeaders(os, pURL, method, requestProperties, usingProxy(), pAuth, pAuthType);
// Get response input stream
InputStream sis = mSocket.getInputStream();
InputStream sis = socket.getInputStream();
BufferedInputStream is = new BufferedInputStream(sis);
// Detatch reponse headers from reponse input stream
InputStream header = detatchResponseHeader(is);
// Parse headers and set response code/message
mResponseHeaders = parseResponseHeader(header);
mResponseHeaderFields = parseHeaderFields(mResponseHeaders);
responseHeaders = parseResponseHeader(header);
responseHeaderFields = parseHeaderFields(responseHeaders);
//System.err.println("Headers fields:");
//mResponseHeaderFields.list(System.err);
//responseHeaderFields.list(System.err);
// Test HTTP response code, to see if further action is needed
switch (getResponseCode()) {
case HTTP_OK:
// 200 OK
mInputStream = is;
mErrorStream = null;
inputStream = is;
errorStream = null;
break;
/*
@@ -472,7 +471,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
// Avoid infinite loop
if (pRetries++ <= 0) {
throw new ProtocolException("Server redirected too many times (" + mMaxRedirects + ") (Authentication required: " + auth + ")"); // This is what sun.net.www.protocol.http.HttpURLConnection does
throw new ProtocolException("Server redirected too many times (" + maxRedirects + ") (Authentication required: " + auth + ")"); // This is what sun.net.www.protocol.http.HttpURLConnection does
}
else if (pa != null) {
connect(pURL, pa, method, pRetries);
@@ -506,8 +505,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
// Test if we can reuse the Socket
if (!(newLoc.getAuthority().equals(pURL.getAuthority()) && (newLoc.getPort() == pURL.getPort()))) {
mSocket.close(); // Close the socket, won't need it anymore
mSocket = null;
socket.close(); // Close the socket, won't need it anymore
socket = null;
}
if (location != null) {
//System.err.println("Redirecting to " + location);
@@ -526,22 +525,22 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
default :
// Not 200 OK, or any of the redirect responses
// Probably an error...
mErrorStream = is;
mInputStream = null;
errorStream = is;
inputStream = null;
}
// --- Need rethinking...
// No further questions, let the Socket wait forever (until the server
// closes the connection)
//mSocket.setSoTimeout(0);
//socket.setSoTimeout(0);
// Probably not... The timeout should only kick if the read BLOCKS.
// Shutdown output, meaning any writes to the outputstream below will
// probably fail...
//mSocket.shutdownOutput();
//socket.shutdownOutput();
// Not a good idea at all... POSTs need the outputstream to send the
// form-data.
// --- /Need rethinking.
mOutputStream = os;
outputStream = os;
}
private static interface SocketConnector extends Runnable {
@@ -663,7 +662,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
return; // Ignore
}
connected = true;
connect(url, null, null, mMaxRedirects);
connect(url, null, null, maxRedirects);
}
/**
@@ -3,7 +3,6 @@ package com.twelvemonkeys.net;
import com.twelvemonkeys.io.FileUtil;
import com.twelvemonkeys.lang.StringUtil;
import com.twelvemonkeys.lang.DateUtil;
import com.twelvemonkeys.util.BASE64;
import com.twelvemonkeys.util.CollectionUtil;
import java.io.*;
@@ -28,29 +28,31 @@
package com.twelvemonkeys.net;
import com.twelvemonkeys.lang.Validate;
import java.net.Authenticator;
import java.net.InetAddress;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.Hashtable;
import java.util.HashMap;
import java.util.Map;
/**
* A simple Authenticator implementation.
* Singleton class, obtain reference through the static
* Singleton class, obtain reference through the static
* {@code getInstance} method.
* <P>
* <p/>
* <EM>After swearing, sweating, pulling my hair, banging my head repeatedly
* into the walls and reading the java.net.Authenticator API documentation
* into the walls and reading the java.net.Authenticator API documentation
* once more, an idea came to my mind. This is the result. I hope you find it
* useful. -- Harald K.</EM>
*
* @see java.net.Authenticator
*
* @author Harald Kuhr (haraldk@iconmedialab.no)
* @version 1.0
* @version 1.0
* @see java.net.Authenticator
*/
public class SimpleAuthenticator extends Authenticator {
/** The reference to the single instance of this class. */
private static SimpleAuthenticator sInstance = null;
/** Keeps track of the state of this class. */
@@ -63,237 +65,179 @@ public class SimpleAuthenticator extends Authenticator {
/** Basic authentication scheme. */
public final static String BASIC = "Basic";
/**
* The hastable that keeps track of the PasswordAuthentications.
*/
/** The hastable that keeps track of the PasswordAuthentications. */
protected Map<AuthKey, PasswordAuthentication> passwordAuthentications = null;
protected Hashtable mPasswordAuthentications = null;
/**
* The hastable that keeps track of the Authenticators.
*/
protected Hashtable mAuthenticators = null;
/**
* Creates a SimpleAuthenticator.
*/
/** The hastable that keeps track of the Authenticators. */
protected Map<PasswordAuthenticator, AuthenticatorFilter> authenticators = null;
/** Creates a SimpleAuthenticator. */
private SimpleAuthenticator() {
mPasswordAuthentications = new Hashtable();
mAuthenticators = new Hashtable();
passwordAuthentications = new HashMap<AuthKey, PasswordAuthentication>();
authenticators = new HashMap<PasswordAuthenticator, AuthenticatorFilter>();
}
/**
* Gets the SimpleAuthenticator instance and registers it through the
* Gets the SimpleAuthenticator instance and registers it through the
* Authenticator.setDefault(). If there is no current instance
* of the SimpleAuthenticator in the VM, one is created. This method will
* try to figure out if the setDefault() succeeded (a hack), and will
* try to figure out if the setDefault() succeeded (a hack), and will
* return null if it was not able to register the instance as default.
*
* @return The single instance of this class, or null, if another
* Authenticator is allready registered as default.
* @return The single instance of this class, or null, if another
* Authenticator is allready registered as default.
*/
public static synchronized SimpleAuthenticator getInstance() {
if (!sInitialized) {
// Create an instance
sInstance = new SimpleAuthenticator();
if (!sInitialized) {
// Create an instance
sInstance = new SimpleAuthenticator();
// Try to set default (this may quietly fail...)
Authenticator.setDefault(sInstance);
// Try to set default (this may quietly fail...)
Authenticator.setDefault(sInstance);
// A hack to figure out if we really did set the authenticator
PasswordAuthentication pa =
Authenticator.requestPasswordAuthentication(null, FOURTYTWO,
null, null, MAGIC);
// A hack to figure out if we really did set the authenticator
PasswordAuthentication pa = Authenticator.requestPasswordAuthentication(null, FOURTYTWO, null, null, MAGIC);
// If this test returns false, we didn't succeed, so we set the
// instance back to null.
if (pa == null || !MAGIC.equals(pa.getUserName()) ||
!("" + FOURTYTWO).equals(new String(pa.getPassword())))
sInstance = null;
// If this test returns false, we didn't succeed, so we set the
// instance back to null.
if (pa == null || !MAGIC.equals(pa.getUserName()) || !("" + FOURTYTWO).equals(new String(pa.getPassword()))) {
sInstance = null;
}
// Done
sInitialized = true;
}
// Done
sInitialized = true;
}
return sInstance;
return sInstance;
}
/**
* Gets the PasswordAuthentication for the request. Called when password
* Gets the PasswordAuthentication for the request. Called when password
* authorization is needed.
*
* @return The PasswordAuthentication collected from the user, or null if
* @return The PasswordAuthentication collected from the user, or null if
* none is provided.
*/
protected PasswordAuthentication getPasswordAuthentication() {
// Don't worry, this is just a hack to figure out if we were able
// to set this Authenticator through the setDefault method.
if (!sInitialized && MAGIC.equals(getRequestingScheme())
&& getRequestingPort() == FOURTYTWO)
return new PasswordAuthentication(MAGIC, ("" + FOURTYTWO)
.toCharArray());
/*
System.err.println("getPasswordAuthentication");
System.err.println(getRequestingSite());
System.err.println(getRequestingPort());
System.err.println(getRequestingProtocol());
System.err.println(getRequestingPrompt());
System.err.println(getRequestingScheme());
*/
// Don't worry, this is just a hack to figure out if we were able
// to set this Authenticator through the setDefault method.
if (!sInitialized && MAGIC.equals(getRequestingScheme()) && getRequestingPort() == FOURTYTWO) {
return new PasswordAuthentication(MAGIC, ("" + FOURTYTWO).toCharArray());
}
/*
System.err.println("getPasswordAuthentication");
System.err.println(getRequestingSite());
System.err.println(getRequestingPort());
System.err.println(getRequestingProtocol());
System.err.println(getRequestingPrompt());
System.err.println(getRequestingScheme());
*/
// TODO:
// Look for a more specific PasswordAuthenticatior before using
// Default:
//
// if (...)
// return pa.requestPasswordAuthentication(getRequestingSite(),
// getRequestingPort(),
// getRequestingProtocol(),
// getRequestingPrompt(),
// getRequestingScheme());
// TODO:
// Look for a more specific PasswordAuthenticatior before using
// Default:
//
// if (...)
// return pa.requestPasswordAuthentication(getRequestingSite(),
// getRequestingPort(),
// getRequestingProtocol(),
// getRequestingPrompt(),
// getRequestingScheme());
return (PasswordAuthentication)
mPasswordAuthentications.get(new AuthKey(getRequestingSite(),
getRequestingPort(),
getRequestingProtocol(),
getRequestingPrompt(),
getRequestingScheme()));
return passwordAuthentications.get(new AuthKey(getRequestingSite(),
getRequestingPort(),
getRequestingProtocol(),
getRequestingPrompt(),
getRequestingScheme()));
}
/**
* Registers a PasswordAuthentication with a given URL address.
*
*/
public PasswordAuthentication registerPasswordAuthentication(URL pURL,
PasswordAuthentication pPA) {
return registerPasswordAuthentication(NetUtil.createInetAddressFromURL(pURL),
pURL.getPort(),
pURL.getProtocol(),
null, // Prompt/Realm
BASIC,
pPA);
/** Registers a PasswordAuthentication with a given URL address. */
public PasswordAuthentication registerPasswordAuthentication(URL pURL, PasswordAuthentication pPA) {
return registerPasswordAuthentication(NetUtil.createInetAddressFromURL(pURL),
pURL.getPort(),
pURL.getProtocol(),
null, // Prompt/Realm
BASIC,
pPA);
}
/**
* Registers a PasswordAuthentication with a given net address.
*
*/
/** Registers a PasswordAuthentication with a given net address. */
public PasswordAuthentication registerPasswordAuthentication(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme, PasswordAuthentication pPA) {
/*
System.err.println("registerPasswordAuthentication");
System.err.println(pAddress);
System.err.println(pPort);
System.err.println(pProtocol);
System.err.println(pPrompt);
System.err.println(pScheme);
*/
public PasswordAuthentication registerPasswordAuthentication(
InetAddress pAddress, int pPort, String pProtocol,
String pPrompt, String pScheme, PasswordAuthentication pPA)
{
/*
System.err.println("registerPasswordAuthentication");
System.err.println(pAddress);
System.err.println(pPort);
System.err.println(pProtocol);
System.err.println(pPrompt);
System.err.println(pScheme);
*/
return (PasswordAuthentication)
mPasswordAuthentications.put(new AuthKey(pAddress, pPort,
pProtocol, pPrompt,
pScheme),
pPA);
return passwordAuthentications.put(new AuthKey(pAddress, pPort, pProtocol, pPrompt, pScheme), pPA);
}
/**
* Unregisters a PasswordAuthentication with a given URL address.
*
*/
/** Unregisters a PasswordAuthentication with a given URL address. */
public PasswordAuthentication unregisterPasswordAuthentication(URL pURL) {
return unregisterPasswordAuthentication(NetUtil.createInetAddressFromURL(pURL),
pURL.getPort(),
pURL.getProtocol(),
null,
BASIC);
return unregisterPasswordAuthentication(NetUtil.createInetAddressFromURL(pURL), pURL.getPort(), pURL.getProtocol(), null, BASIC);
}
/**
* Unregisters a PasswordAuthentication with a given net address.
*
*/
public PasswordAuthentication unregisterPasswordAuthentication(
InetAddress pAddress, int pPort, String pProtocol,
String pPrompt, String pScheme)
{
return (PasswordAuthentication)
mPasswordAuthentications.remove(new AuthKey(pAddress, pPort,
pProtocol, pPrompt,
pScheme));
/** Unregisters a PasswordAuthentication with a given net address. */
public PasswordAuthentication unregisterPasswordAuthentication(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme) {
return passwordAuthentications.remove(new AuthKey(pAddress, pPort, pProtocol, pPrompt, pScheme));
}
/**
* TODO: Registers a PasswordAuthenticator that can answer authentication
* requests.
*
*
* @see PasswordAuthenticator
*/
public void registerPasswordAuthenticator(PasswordAuthenticator pPA,
AuthenticatorFilter pFilter) {
mAuthenticators.put(pPA, pFilter);
public void registerPasswordAuthenticator(PasswordAuthenticator pPA, AuthenticatorFilter pFilter) {
authenticators.put(pPA, pFilter);
}
/**
* TODO: Unregisters a PasswordAuthenticator that can answer authentication
* requests.
*
*
* @see PasswordAuthenticator
*/
public void unregisterPasswordAuthenticator(PasswordAuthenticator pPA) {
mAuthenticators.remove(pPA);
authenticators.remove(pPA);
}
}
/**
* Utility class, used for caching the PasswordAuthentication objects.
* Everything but address may be null
*/
class AuthKey {
InetAddress mAddress = null;
int mPort = -1;
String mProtocol = null;
String mPrompt = null;
String mScheme = null;
AuthKey(InetAddress pAddress, int pPort, String pProtocol,
String pPrompt, String pScheme) {
if (pAddress == null)
throw new IllegalArgumentException("Address argument can't be null!");
InetAddress address = null;
int port = -1;
String protocol = null;
String prompt = null;
String scheme = null;
mAddress = pAddress;
mPort = pPort;
mProtocol = pProtocol;
mPrompt = pPrompt;
mScheme = pScheme;
AuthKey(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme) {
Validate.notNull(pAddress, "address");
// System.out.println("Created: " + this);
address = pAddress;
port = pPort;
protocol = pProtocol;
prompt = pPrompt;
scheme = pScheme;
// System.out.println("Created: " + this);
}
/**
* Creates a string representation of this object.
*/
/** Creates a string representation of this object. */
public String toString() {
return "AuthKey[" + mAddress + ":" + mPort + "/" + mProtocol + " \"" + mPrompt + "\" (" + mScheme + ")]";
return "AuthKey[" + address + ":" + port + "/" + protocol + " \"" + prompt + "\" (" + scheme + ")]";
}
public boolean equals(Object pObj) {
return (pObj instanceof AuthKey ? equals((AuthKey) pObj) : false);
return (pObj instanceof AuthKey && equals((AuthKey) pObj));
}
// Ahem.. Breaks the rule from Object.equals(Object):
@@ -302,25 +246,25 @@ class AuthKey {
// should return true.
public boolean equals(AuthKey pKey) {
// Maybe allow nulls, and still be equal?
return (mAddress.equals(pKey.mAddress)
&& (mPort == -1
|| pKey.mPort == -1
|| mPort == pKey.mPort)
&& (mProtocol == null
|| pKey.mProtocol == null
|| mProtocol.equals(pKey.mProtocol))
&& (mPrompt == null
|| pKey.mPrompt == null
|| mPrompt.equals(pKey.mPrompt))
&& (mScheme == null
|| pKey.mScheme == null
|| mScheme.equalsIgnoreCase(pKey.mScheme)));
// Maybe allow nulls, and still be equal?
return (address.equals(pKey.address)
&& (port == -1
|| pKey.port == -1
|| port == pKey.port)
&& (protocol == null
|| pKey.protocol == null
|| protocol.equals(pKey.protocol))
&& (prompt == null
|| pKey.prompt == null
|| prompt.equals(pKey.prompt))
&& (scheme == null
|| pKey.scheme == null
|| scheme.equalsIgnoreCase(pKey.scheme)));
}
public int hashCode() {
// There won't be too many pr address, will it? ;-)
return mAddress.hashCode();
// There won't be too many pr address, will it? ;-)
return address.hashCode();
}
}