Moved old obsolete stuff to sandbox.

This commit is contained in:
Harald Kuhr 2013-09-08 14:08:38 +02:00
parent 4c18c2a685
commit c5f1d8101b
13 changed files with 3161 additions and 3102 deletions

View File

@ -0,0 +1,202 @@
/*
* Copyright (c) 2013, 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.lang.DateUtil;
import com.twelvemonkeys.lang.StringUtil;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* HTTPUtil
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haraldk$
* @version $Id: HTTPUtil.java,v 1.0 08.09.13 13:57 haraldk Exp$
*/
public class HTTPUtil {
/**
* RFC 1123 date format, as recommended by RFC 2616 (HTTP/1.1), sec 3.3
* NOTE: All date formats are private, to ensure synchronized access.
*/
private static final SimpleDateFormat HTTP_RFC1123_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
static {
HTTP_RFC1123_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
}
/**
* RFC 850 date format, (almost) as described in RFC 2616 (HTTP/1.1), sec 3.3
* USE FOR PARSING ONLY (format is not 100% correct, to be more robust).
*/
private static final SimpleDateFormat HTTP_RFC850_FORMAT = new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss z", Locale.US);
/**
* ANSI C asctime() date format, (almost) as described in RFC 2616 (HTTP/1.1), sec 3.3.
* USE FOR PARSING ONLY (format is not 100% correct, to be more robust).
*/
private static final SimpleDateFormat HTTP_ASCTIME_FORMAT = new SimpleDateFormat("EEE MMM d HH:mm:ss yy", Locale.US);
private static long sNext50YearWindowChange = DateUtil.currentTimeDay();
static {
HTTP_RFC850_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
HTTP_ASCTIME_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.3:
// - HTTP/1.1 clients and caches SHOULD assume that an RFC-850 date
// which appears to be more than 50 years in the future is in fact
// in the past (this helps solve the "year 2000" problem).
update50YearWindowIfNeeded();
}
private static void update50YearWindowIfNeeded() {
// Avoid class synchronization
long next = sNext50YearWindowChange;
if (next < System.currentTimeMillis()) {
// Next check in one day
next += DateUtil.DAY;
sNext50YearWindowChange = next;
Date startDate = new Date(next - (50l * DateUtil.CALENDAR_YEAR));
//System.out.println("next test: " + new Date(next) + ", 50 year start: " + startDate);
synchronized (HTTP_RFC850_FORMAT) {
HTTP_RFC850_FORMAT.set2DigitYearStart(startDate);
}
synchronized (HTTP_ASCTIME_FORMAT) {
HTTP_ASCTIME_FORMAT.set2DigitYearStart(startDate);
}
}
}
/**
* Formats the time to a HTTP date, using the RFC 1123 format, as described
* in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3"
* >RFC 2616 (HTTP/1.1), sec. 3.3</a>.
*
* @param pTime the time
* @return a {@code String} representation of the time
*/
public static String formatHTTPDate(long pTime) {
return formatHTTPDate(new Date(pTime));
}
/**
* Formats the time to a HTTP date, using the RFC 1123 format, as described
* in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3"
* >RFC 2616 (HTTP/1.1), sec. 3.3</a>.
*
* @param pTime the time
* @return a {@code String} representation of the time
*/
public static String formatHTTPDate(Date pTime) {
synchronized (HTTP_RFC1123_FORMAT) {
return HTTP_RFC1123_FORMAT.format(pTime);
}
}
/**
* Parses a HTTP date string into a {@code long} representing milliseconds
* since January 1, 1970 GMT.
* <p>
* Use this method with headers that contain dates, such as
* {@code If-Modified-Since} or {@code Last-Modified}.
* <p>
* The date string may be in either RFC 1123, RFC 850 or ANSI C asctime()
* format, as described in
* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3"
* >RFC 2616 (HTTP/1.1), sec. 3.3</a>
*
* @param pDate the date to parse
*
* @return a {@code long} value representing the date, expressed as the
* number of milliseconds since January 1, 1970 GMT,
* @throws NumberFormatException if the date parameter is not parseable.
* @throws IllegalArgumentException if the date paramter is {@code null}
*/
public static long parseHTTPDate(String pDate) throws NumberFormatException {
return parseHTTPDateImpl(pDate).getTime();
}
/**
* ParseHTTPDate implementation
*
* @param pDate the date string to parse
*
* @return a {@code Date}
* @throws NumberFormatException if the date parameter is not parseable.
* @throws IllegalArgumentException if the date paramter is {@code null}
*/
private static Date parseHTTPDateImpl(final String pDate) throws NumberFormatException {
if (pDate == null) {
throw new IllegalArgumentException("date == null");
}
if (StringUtil.isEmpty(pDate)) {
throw new NumberFormatException("Invalid HTTP date: \"" + pDate + "\"");
}
DateFormat format;
if (pDate.indexOf('-') >= 0) {
format = HTTP_RFC850_FORMAT;
update50YearWindowIfNeeded();
}
else if (pDate.indexOf(',') < 0) {
format = HTTP_ASCTIME_FORMAT;
update50YearWindowIfNeeded();
}
else {
format = HTTP_RFC1123_FORMAT;
// NOTE: RFC1123 always uses 4-digit years
}
Date date;
try {
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (format) {
date = format.parse(pDate);
}
}
catch (ParseException e) {
NumberFormatException nfe = new NumberFormatException("Invalid HTTP date: \"" + pDate + "\"");
nfe.initCause(e);
throw nfe;
}
if (date == null) {
throw new NumberFormatException("Invalid HTTP date: \"" + pDate + "\"");
}
return date;
}
}

View File

@ -0,0 +1,83 @@
/*
* Copyright (c) 2013, 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 org.junit.Test;
import static org.junit.Assert.*;
/**
* HTTPUtilTest
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haraldk$
* @version $Id: HTTPUtilTest.java,v 1.0 08.09.13 13:57 haraldk Exp$
*/
public class HTTPUtilTest {
@Test
public void testParseHTTPDateRFC1123() {
long time = HTTPUtil.parseHTTPDate("Sun, 06 Nov 1994 08:49:37 GMT");
assertEquals(784111777000l, time);
time = HTTPUtil.parseHTTPDate("Sunday, 06 Nov 1994 08:49:37 GMT");
assertEquals(784111777000l, time);
}
@Test
public void testParseHTTPDateRFC850() {
long time = HTTPUtil.parseHTTPDate("Sunday, 06-Nov-1994 08:49:37 GMT");
assertEquals(784111777000l, time);
time = HTTPUtil.parseHTTPDate("Sun, 06-Nov-94 08:49:37 GMT");
assertEquals(784111777000l, time);
// NOTE: This test will fail some time, around 2044,
// as the 50 year window will slide...
time = HTTPUtil.parseHTTPDate("Sunday, 06-Nov-94 08:49:37 GMT");
assertEquals(784111777000l, time);
time = HTTPUtil.parseHTTPDate("Sun, 06-Nov-94 08:49:37 GMT");
assertEquals(784111777000l, time);
}
@Test
public void testParseHTTPDateAsctime() {
long time = HTTPUtil.parseHTTPDate("Sun Nov 6 08:49:37 1994");
assertEquals(784111777000l, time);
time = HTTPUtil.parseHTTPDate("Sun Nov 6 08:49:37 94");
assertEquals(784111777000l, time);
}
@Test
public void testFormatHTTPDateRFC1123() {
long time = 784111777000l;
assertEquals("Sun, 06 Nov 1994 08:49:37 GMT", HTTPUtil.formatHTTPDate(time));
}
}

View File

@ -1,59 +0,0 @@
package com.twelvemonkeys.net;
import junit.framework.TestCase;
/**
* NetUtilTestCase
* <p/>
* <!-- To change this template use Options | File Templates. -->
* <!-- Created by IntelliJ IDEA. -->
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/net/NetUtilTestCase.java#1 $
*/
public class NetUtilTestCase extends TestCase {
public void setUp() throws Exception {
super.setUp();
}
public void tearDown() throws Exception {
super.tearDown();
}
public void testParseHTTPDateRFC1123() {
long time = NetUtil.parseHTTPDate("Sun, 06 Nov 1994 08:49:37 GMT");
assertEquals(784111777000l, time);
time = NetUtil.parseHTTPDate("Sunday, 06 Nov 1994 08:49:37 GMT");
assertEquals(784111777000l, time);
}
public void testParseHTTPDateRFC850() {
long time = NetUtil.parseHTTPDate("Sunday, 06-Nov-1994 08:49:37 GMT");
assertEquals(784111777000l, time);
time = NetUtil.parseHTTPDate("Sun, 06-Nov-94 08:49:37 GMT");
assertEquals(784111777000l, time);
// NOTE: This test will fail some time, around 2044,
// as the 50 year window will slide...
time = NetUtil.parseHTTPDate("Sunday, 06-Nov-94 08:49:37 GMT");
assertEquals(784111777000l, time);
time = NetUtil.parseHTTPDate("Sun, 06-Nov-94 08:49:37 GMT");
assertEquals(784111777000l, time);
}
public void testParseHTTPDateAsctime() {
long time = NetUtil.parseHTTPDate("Sun Nov 6 08:49:37 1994");
assertEquals(784111777000l, time);
time = NetUtil.parseHTTPDate("Sun Nov 6 08:49:37 94");
assertEquals(784111777000l, time);
}
public void testFormatHTTPDateRFC1123() {
long time = 784111777000l;
assertEquals("Sun, 06 Nov 1994 08:49:37 GMT", NetUtil.formatHTTPDate(time));
}
}

View File

@ -1,46 +1,45 @@
/*
* 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 java.net.*;
/**
* Interface for filtering Authenticator requests, used by the
* SimpleAuthenticator.
*
* @see SimpleAuthenticator
* @see java.net.Authenticator
*
* @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);
}
/*
* 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 java.net.*;
/**
* Interface for filtering Authenticator requests, used by the
* SimpleAuthenticator.
*
* @see SimpleAuthenticator
* @see java.net.Authenticator
*
* @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);
}

View File

@ -1,144 +1,143 @@
/*
* 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);
}
}
/*
* 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);
}
}
}

View File

@ -1,45 +1,45 @@
/*
* 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 java.net.*;
/**
* Interface fro PasswordAuthenticators used by SimpleAuthenticator.
*
* @see SimpleAuthenticator
* @see java.net.Authenticator
*
* @author Harald Kuhr (haraldk@iconmedialab.no)
*
* @version 1.0
*/
public interface PasswordAuthenticator {
public PasswordAuthentication requestPasswordAuthentication(InetAddress addr, int port, String protocol, String prompt, String scheme);
}
/*
* 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 java.net.*;
/**
* Interface fro PasswordAuthenticators used by SimpleAuthenticator.
*
* @see SimpleAuthenticator
* @see java.net.Authenticator
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
*
* @version 1.0
*/
public interface PasswordAuthenticator {
public PasswordAuthentication requestPasswordAuthentication(InetAddress addr, int port, String protocol, String prompt, String scheme);
}

View File

@ -1,270 +1,270 @@
/*
* 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.lang.Validate;
import java.net.Authenticator;
import java.net.InetAddress;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* A simple Authenticator implementation.
* Singleton class, obtain reference through the static
* {@code getInstance} method.
* <p/>
* <EM>After swearing, sweating, pulling my hair, banging my head repeatedly
* 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>
*
* @author Harald Kuhr (haraldk@iconmedialab.no)
* @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. */
private static boolean sInitialized = false;
// These are used for the identification hack.
private final static String MAGIC = "magic";
private final static int FOURTYTWO = 42;
/** Basic authentication scheme. */
public final static String BASIC = "Basic";
/** The hastable that keeps track of the PasswordAuthentications. */
protected Map<AuthKey, PasswordAuthentication> passwordAuthentications = null;
/** The hastable that keeps track of the Authenticators. */
protected Map<PasswordAuthenticator, AuthenticatorFilter> authenticators = null;
/** Creates a SimpleAuthenticator. */
private SimpleAuthenticator() {
passwordAuthentications = new HashMap<AuthKey, PasswordAuthentication>();
authenticators = new HashMap<PasswordAuthenticator, AuthenticatorFilter>();
}
/**
* 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
* 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.
*/
public static synchronized SimpleAuthenticator getInstance() {
if (!sInitialized) {
// Create an instance
sInstance = new SimpleAuthenticator();
// 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);
// 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;
}
return sInstance;
}
/**
* Gets the PasswordAuthentication for the request. Called when password
* authorization is needed.
*
* @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());
*/
// TODO:
// Look for a more specific PasswordAuthenticatior before using
// Default:
//
// if (...)
// return pa.requestPasswordAuthentication(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 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);
*/
return passwordAuthentications.put(new AuthKey(pAddress, pPort, pProtocol, pPrompt, pScheme), pPA);
}
/** Unregisters a PasswordAuthentication with a given URL address. */
public PasswordAuthentication unregisterPasswordAuthentication(URL pURL) {
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 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) {
authenticators.put(pPA, pFilter);
}
/**
* TODO: Unregisters a PasswordAuthenticator that can answer authentication
* requests.
*
* @see PasswordAuthenticator
*/
public void unregisterPasswordAuthenticator(PasswordAuthenticator pPA) {
authenticators.remove(pPA);
}
}
/**
* Utility class, used for caching the PasswordAuthentication objects.
* Everything but address may be null
*/
class AuthKey {
InetAddress address = null;
int port = -1;
String protocol = null;
String prompt = null;
String scheme = null;
AuthKey(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme) {
Validate.notNull(pAddress, "address");
address = pAddress;
port = pPort;
protocol = pProtocol;
prompt = pPrompt;
scheme = pScheme;
// System.out.println("Created: " + this);
}
/** Creates a string representation of this object. */
public String toString() {
return "AuthKey[" + address + ":" + port + "/" + protocol + " \"" + prompt + "\" (" + scheme + ")]";
}
public boolean equals(Object pObj) {
return (pObj instanceof AuthKey && equals((AuthKey) pObj));
}
// Ahem.. Breaks the rule from Object.equals(Object):
// It is transitive: for any reference values x, y, and z, if x.equals(y)
// returns true and y.equals(z) returns true, then x.equals(z)
// should return true.
public boolean equals(AuthKey pKey) {
// 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 address.hashCode();
}
}
/*
* 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.lang.Validate;
import java.net.Authenticator;
import java.net.InetAddress;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* A simple Authenticator implementation.
* Singleton class, obtain reference through the static
* {@code getInstance} method.
* <p/>
* <EM>After swearing, sweating, pulling my hair, banging my head repeatedly
* 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>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @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. */
private static boolean sInitialized = false;
// These are used for the identification hack.
private final static String MAGIC = "magic";
private final static int FOURTYTWO = 42;
/** Basic authentication scheme. */
public final static String BASIC = "Basic";
/** The hastable that keeps track of the PasswordAuthentications. */
protected Map<AuthKey, PasswordAuthentication> passwordAuthentications = null;
/** The hastable that keeps track of the Authenticators. */
protected Map<PasswordAuthenticator, AuthenticatorFilter> authenticators = null;
/** Creates a SimpleAuthenticator. */
private SimpleAuthenticator() {
passwordAuthentications = new HashMap<AuthKey, PasswordAuthentication>();
authenticators = new HashMap<PasswordAuthenticator, AuthenticatorFilter>();
}
/**
* 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
* 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.
*/
public static synchronized SimpleAuthenticator getInstance() {
if (!sInitialized) {
// Create an instance
sInstance = new SimpleAuthenticator();
// 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);
// 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;
}
return sInstance;
}
/**
* Gets the PasswordAuthentication for the request. Called when password
* authorization is needed.
*
* @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());
*/
// TODO:
// Look for a more specific PasswordAuthenticatior before using
// Default:
//
// if (...)
// return pa.requestPasswordAuthentication(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 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);
*/
return passwordAuthentications.put(new AuthKey(pAddress, pPort, pProtocol, pPrompt, pScheme), pPA);
}
/** Unregisters a PasswordAuthentication with a given URL address. */
public PasswordAuthentication unregisterPasswordAuthentication(URL pURL) {
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 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) {
authenticators.put(pPA, pFilter);
}
/**
* TODO: Unregisters a PasswordAuthenticator that can answer authentication
* requests.
*
* @see PasswordAuthenticator
*/
public void unregisterPasswordAuthenticator(PasswordAuthenticator pPA) {
authenticators.remove(pPA);
}
}
/**
* Utility class, used for caching the PasswordAuthentication objects.
* Everything but address may be null
*/
class AuthKey {
// TODO: Move this class to sandbox?
InetAddress address = null;
int port = -1;
String protocol = null;
String prompt = null;
String scheme = null;
AuthKey(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme) {
Validate.notNull(pAddress, "address");
address = pAddress;
port = pPort;
protocol = pProtocol;
prompt = pPrompt;
scheme = pScheme;
// System.out.println("Created: " + this);
}
/** Creates a string representation of this object. */
public String toString() {
return "AuthKey[" + address + ":" + port + "/" + protocol + " \"" + prompt + "\" (" + scheme + ")]";
}
public boolean equals(Object pObj) {
return (pObj instanceof AuthKey && equals((AuthKey) pObj));
}
// Ahem.. Breaks the rule from Object.equals(Object):
// It is transitive: for any reference values x, y, and z, if x.equals(y)
// returns true and y.equals(z) returns true, then x.equals(z)
// should return true.
public boolean equals(AuthKey pKey) {
// 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 address.hashCode();
}
}

View File

@ -29,7 +29,7 @@
package com.twelvemonkeys.servlet.cache;
import com.twelvemonkeys.lang.StringUtil;
import com.twelvemonkeys.net.NetUtil;
import com.twelvemonkeys.net.HTTPUtil;
import com.twelvemonkeys.servlet.ServletResponseStreamDelegate;
import javax.servlet.ServletOutputStream;
@ -212,7 +212,7 @@ class CacheResponseWrapper extends HttpServletResponseWrapper {
if (Boolean.FALSE.equals(cacheable)) {
super.setDateHeader(pName, pValue);
}
cachedResponse.setHeader(pName, NetUtil.formatHTTPDate(pValue));
cachedResponse.setHeader(pName, HTTPUtil.formatHTTPDate(pValue));
}
public void addDateHeader(String pName, long pValue) {
@ -220,7 +220,7 @@ class CacheResponseWrapper extends HttpServletResponseWrapper {
if (Boolean.FALSE.equals(cacheable)) {
super.addDateHeader(pName, pValue);
}
cachedResponse.addHeader(pName, NetUtil.formatHTTPDate(pValue));
cachedResponse.addHeader(pName, HTTPUtil.formatHTTPDate(pValue));
}
public void setHeader(String pName, String pValue) {

View File

@ -32,7 +32,7 @@ import com.twelvemonkeys.io.FileUtil;
import com.twelvemonkeys.lang.StringUtil;
import com.twelvemonkeys.lang.Validate;
import com.twelvemonkeys.net.MIMEUtil;
import com.twelvemonkeys.net.NetUtil;
import com.twelvemonkeys.net.HTTPUtil;
import com.twelvemonkeys.util.LRUHashMap;
import com.twelvemonkeys.util.NullMap;
@ -972,7 +972,7 @@ public class HTTPCache {
File cached = getCachedFile(pCacheURI, pRequest);
if (cached != null && cached.exists()) {
lastModified = cached.lastModified();
//// System.out.println(" ## HTTPCache ## Last-Modified is " + NetUtil.formatHTTPDate(lastModified) + ", using cachedFile.lastModified()");
//// System.out.println(" ## HTTPCache ## Last-Modified is " + HTTPUtil.formatHTTPDate(lastModified) + ", using cachedFile.lastModified()");
}
}
*/
@ -981,11 +981,11 @@ public class HTTPCache {
int maxAge = getIntHeader(response, HEADER_CACHE_CONTROL, "max-age");
if (maxAge == -1) {
expires = lastModified + defaultExpiryTime;
//// System.out.println(" ## HTTPCache ## Expires is " + NetUtil.formatHTTPDate(expires) + ", using lastModified + defaultExpiry");
//// System.out.println(" ## HTTPCache ## Expires is " + HTTPUtil.formatHTTPDate(expires) + ", using lastModified + defaultExpiry");
}
else {
expires = lastModified + (maxAge * 1000L); // max-age is seconds
//// System.out.println(" ## HTTPCache ## Expires is " + NetUtil.formatHTTPDate(expires) + ", using lastModified + maxAge");
//// System.out.println(" ## HTTPCache ## Expires is " + HTTPUtil.formatHTTPDate(expires) + ", using lastModified + maxAge");
}
}
/*
@ -997,7 +997,7 @@ public class HTTPCache {
// Expired?
if (expires < now) {
// System.out.println(" ## HTTPCache ## Content is stale (content expired: "
// + NetUtil.formatHTTPDate(expires) + " before " + NetUtil.formatHTTPDate(now) + ").");
// + HTTPUtil.formatHTTPDate(expires) + " before " + HTTPUtil.formatHTTPDate(now) + ").");
return true;
}
@ -1008,7 +1008,7 @@ public class HTTPCache {
File cached = getCachedFile(pCacheURI, pRequest);
if (cached != null && cached.exists()) {
lastModified = cached.lastModified();
//// System.out.println(" ## HTTPCache ## Last-Modified is " + NetUtil.formatHTTPDate(lastModified) + ", using cachedFile.lastModified()");
//// System.out.println(" ## HTTPCache ## Last-Modified is " + HTTPUtil.formatHTTPDate(lastModified) + ", using cachedFile.lastModified()");
}
}
*/
@ -1018,7 +1018,7 @@ public class HTTPCache {
//noinspection RedundantIfStatement
if (real != null && real.exists() && real.lastModified() > lastModified) {
// System.out.println(" ## HTTPCache ## Content is stale (new content"
// + NetUtil.formatHTTPDate(lastModified) + " before " + NetUtil.formatHTTPDate(real.lastModified()) + ").");
// + HTTPUtil.formatHTTPDate(lastModified) + " before " + HTTPUtil.formatHTTPDate(real.lastModified()) + ").");
return true;
}
@ -1082,7 +1082,7 @@ public class HTTPCache {
static long getDateHeader(final String pHeaderValue) {
long date = -1L;
if (pHeaderValue != null) {
date = NetUtil.parseHTTPDate(pHeaderValue);
date = HTTPUtil.parseHTTPDate(pHeaderValue);
}
return date;
}

View File

@ -29,7 +29,7 @@
package com.twelvemonkeys.servlet.cache;
import com.twelvemonkeys.io.FastByteArrayOutputStream;
import com.twelvemonkeys.net.NetUtil;
import com.twelvemonkeys.net.HTTPUtil;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@ -53,7 +53,7 @@ class WritableCachedResponseImpl implements WritableCachedResponse {
protected WritableCachedResponseImpl() {
cachedResponse = new CachedResponseImpl();
// Hmmm..
setHeader(HTTPCache.HEADER_CACHED_TIME, NetUtil.formatHTTPDate(System.currentTimeMillis()));
setHeader(HTTPCache.HEADER_CACHED_TIME, HTTPUtil.formatHTTPDate(System.currentTimeMillis()));
}
public CachedResponse getCachedResponse() {

View File

@ -1,6 +1,6 @@
package com.twelvemonkeys.servlet.cache;
import com.twelvemonkeys.net.NetUtil;
import com.twelvemonkeys.net.HTTPUtil;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
@ -644,7 +644,7 @@ public class HTTPCacheTestCase {
CacheResponse res = (CacheResponse) invocation.getArguments()[1];
res.setStatus(HttpServletResponse.SC_OK);
res.setHeader("Date", NetUtil.formatHTTPDate(System.currentTimeMillis()));
res.setHeader("Date", HTTPUtil.formatHTTPDate(System.currentTimeMillis()));
res.setHeader("Cache-Control", "public");
res.addHeader("X-Custom", "FOO");
res.addHeader("X-Custom", "BAR");
@ -1126,7 +1126,7 @@ public class HTTPCacheTestCase {
CacheResponse res = (CacheResponse) invocation.getArguments()[1];
res.setStatus(status);
res.setHeader("Date", NetUtil.formatHTTPDate(System.currentTimeMillis()));
res.setHeader("Date", HTTPUtil.formatHTTPDate(System.currentTimeMillis()));
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
for (String value : header.getValue()) {