AI 147127: am: CL 147126 am: CL 147121 Fixes for tests in the luni module.
  There are still some tests that are failing in the cts host. This CL will fix most of them in the luni module.
  Original author: ursg
  Merged from: //branches/cupcake/...
  Original author: android-build

Automated import of CL 147127
diff --git a/libcore/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java b/libcore/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java
index 3cd26e8..8abfa1d 100644
--- a/libcore/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java
+++ b/libcore/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java
@@ -172,7 +172,6 @@
         method = "getOutputStream",
         args = {}
     )
-    @BrokenTest("openConnection seems to return null, wrong config?")
     public void testGetOutputStream() throws Exception {
         // Regression for HARMONY-482
         MockServer httpServer =
@@ -204,7 +203,6 @@
         method = "usingProxy",
         args = {}
     )
-    @KnownFailure("Not implemented")
     public void testUsingProxy() throws Exception {
         // Regression for HARMONY-570
         MockServer server = new MockServer("server");
@@ -251,7 +249,6 @@
         method = "usingProxy",
         args = {}
     )
-    @KnownFailure("Not implemented")
     public void testUsingProxySelector() throws Exception {
         // Regression for HARMONY-570
         MockServer server = new MockServer("server");
@@ -307,7 +304,6 @@
             args = {}
         )
     })
-    @KnownFailure("Not umplemented")
     public void testProxyAuthorization() throws Exception {
         // Set up test Authenticator
         Authenticator.setDefault(new Authenticator() {
diff --git a/libcore/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java b/libcore/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java
index 9c50576..012cecc 100644
--- a/libcore/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java
+++ b/libcore/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java
@@ -159,7 +159,6 @@
         method = "setDefaultHostnameVerifier",
         args = {javax.net.ssl.HostnameVerifier.class}
     )
-    @KnownFailure("Handshake fails.")
     @AndroidOnly("we only have a .bks key store in the test resources")
     public void testHttpsConnection() throws Throwable {
         // set up the properties defining the default values needed by SSL stuff
@@ -218,7 +217,6 @@
             args = {int.class}
         )
     })
-    @KnownFailure("Handshake fails.")
     @AndroidOnly("we only have a .bks key store in the test resources")
     public void testHttpsConnection_Not_Found_Response() throws Throwable {
         // set up the properties defining the default values needed by SSL stuff
@@ -444,7 +442,6 @@
         method = "setHostnameVerifier",
         args = {javax.net.ssl.HostnameVerifier.class}
     )
-    @KnownFailure("Handshake fails.")
     @AndroidOnly("we only have a .bks key store in the test resources")
     public void testSetHostnameVerifier() throws Throwable {
         // setting up the properties pointing to the key/trust stores
@@ -494,7 +491,6 @@
         method = "setDoOutput",
         args = {boolean.class}
     )
-    @KnownFailure("Handshake fails.")
     @AndroidOnly("we only have a .bks key store in the test resources")
     public void test_doOutput() throws Throwable {
         // setting up the properties pointing to the key/trust stores
@@ -933,7 +929,7 @@
         if (store != null) {
             String ksFileName = "org/apache/harmony/luni/tests/key_store."
                     + KeyStore.getDefaultType().toLowerCase();
-            InputStream in = ClassLoader.getSystemClassLoader()
+            InputStream in = getClass().getClassLoader()
                     .getResourceAsStream(ksFileName);
             FileOutputStream out = new FileOutputStream(store);
             BufferedInputStream bufIn = new BufferedInputStream(in, 8192);
diff --git a/libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java b/libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java
index d7c6708..c9fba59 100644
--- a/libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java
+++ b/libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java
@@ -495,36 +495,23 @@
         method = "loadClass",
         args = {java.lang.String.class, boolean.class}
     )
-    public void test_loadClassLjava_lang_StringLZ() {
-        PackageClassLoader pcl = new PackageClassLoader();
+    public void test_loadClassLjava_lang_StringLZ() throws
+            IllegalAccessException, InstantiationException,
+            ClassNotFoundException {
+        PackageClassLoader pcl = new PackageClassLoader(
+                getClass().getClassLoader());
         String className = getClass().getPackage().getName() + ".A";
-        try {
-            Class<?> clazz = pcl.loadClass(className, false);
-            assertEquals(className, clazz.getName());
-            assertNotNull(clazz.newInstance());
-            
-        } catch (ClassNotFoundException e) {
-            fail("ClassNotFoundException was thrown.");
-        } catch (InstantiationException e) {
-            fail("InstantiationException was thrown.");
-        } catch (IllegalAccessException e) {
-            fail("IllegalAccessException was thrown.");
-        }
+
+        Class<?> clazz = pcl.loadClass(className, false);
+        assertEquals(className, clazz.getName());
+        assertNotNull(clazz.newInstance());
         
-        try {
-            Class<?> clazz = pcl.loadClass(className, true);
-            assertEquals(className, clazz.getName());
-            assertNotNull(clazz.newInstance());
+        clazz = pcl.loadClass(className, true);
+        assertEquals(className, clazz.getName());
+        assertNotNull(clazz.newInstance());
             
-        } catch (ClassNotFoundException e) {
-            fail("ClassNotFoundException was thrown.");
-        } catch (InstantiationException e) {
-            fail("InstantiationException was thrown.");
-        } catch (IllegalAccessException e) {
-            fail("IllegalAccessException was thrown.");
-        }
         try {
-            Class<?> clazz = pcl.loadClass("UnknownClass", false);
+            clazz = pcl.loadClass("UnknownClass", false);
             assertEquals("TestClass", clazz.getName());
             fail("ClassNotFoundException was not thrown.");
         } catch (ClassNotFoundException e) {
@@ -613,6 +600,7 @@
         method = "getSystemClassLoader",
         args = {}
     )
+    @BrokenTest("Infinite loop in classloader. Actually a known failure.")
     public void test_getSystemClassLoader() {
         // Test for method java.lang.ClassLoader
         // java.lang.ClassLoader.getSystemClassLoader()
@@ -761,7 +749,8 @@
     )
     @KnownFailure("PackageClassLoader.getPackage returns null.")
     public void test_getPackageLjava_lang_String() {
-        PackageClassLoader pcl = new PackageClassLoader();
+        PackageClassLoader pcl = new PackageClassLoader(
+                getClass().getClassLoader());
         
         String [] packageProperties = { "test.package", "title", "1.0", 
                 "Vendor", "Title", "1.1", "implementation vendor"};
@@ -800,7 +789,8 @@
             "expect exactly that. this tests works on the RI.")
     public void test_getPackages() {
         
-        PackageClassLoader pcl = new PackageClassLoader();
+        PackageClassLoader pcl = new PackageClassLoader(
+                getClass().getClassLoader());
         
         String [] packageProperties = { "test.package", "title", "1.0", 
                 "Vendor", "Title", "1.1", "implementation vendor"};
@@ -823,7 +813,7 @@
         Package [] packages = pcl.getPackages();
         assertTrue(packages.length != 0);
         
-        pcl = new PackageClassLoader();
+        pcl = new PackageClassLoader(getClass().getClassLoader());
         packages = pcl.getPackages();
         assertNotNull(packages);
         
@@ -911,7 +901,8 @@
     )
     public void test_definePackage() {
         
-        PackageClassLoader pcl = new PackageClassLoader();
+        PackageClassLoader pcl = new PackageClassLoader(
+                getClass().getClassLoader());
         
         String [] packageProperties = { "test.package", "title", "1.0", 
                 "Vendor", "Title", "1.1", "implementation vendor"};
@@ -977,7 +968,8 @@
     public void test_findClass(){
         
         try {
-            PackageClassLoader pcl = new PackageClassLoader();
+            PackageClassLoader pcl = new PackageClassLoader(
+                    getClass().getClassLoader());
             pcl.findClass(getClass().getPackage().getName() + ".A");
             fail("ClassNotFoundException was not thrown.");
         } catch(ClassNotFoundException cnfe) {
@@ -985,7 +977,8 @@
         } 
         
        try {
-           PackageClassLoader pcl = new PackageClassLoader();
+           PackageClassLoader pcl = new PackageClassLoader(
+                   getClass().getClassLoader());
            pcl.findClass("TestClass");
            fail("ClassNotFoundException was not thrown.");
        } catch(ClassNotFoundException cnfe) {
@@ -1001,7 +994,8 @@
     )
     @AndroidOnly("findLibrary method is not supported, it returns null.")
     public void test_findLibrary() {
-        PackageClassLoader pcl = new PackageClassLoader();
+        PackageClassLoader pcl = new PackageClassLoader(
+                getClass().getClassLoader());
         assertNull(pcl.findLibrary("libjvm.so"));
     }
     
@@ -1013,7 +1007,8 @@
     )
     @AndroidOnly("findResource method is not supported, it returns null.")    
     public void test_findResourceLjava_lang_String() {
-        assertNull(new PackageClassLoader().findResource("hyts_Foo.c"));
+        assertNull(new PackageClassLoader(
+                getClass().getClassLoader()).findResource("hyts_Foo.c"));
     }
 
     @TestTargetNew(
@@ -1025,7 +1020,8 @@
     @AndroidOnly("findResources method is not supported, it returns " +
             "empty Enumeration.")      
     public void test_findResourcesLjava_lang_String() throws IOException {
-        assertFalse(new PackageClassLoader().findResources("hyts_Foo.c").
+        assertFalse(new PackageClassLoader(
+                getClass().getClassLoader()).findResources("hyts_Foo.c").
                 hasMoreElements());
     }
     
@@ -1036,7 +1032,8 @@
         args = {java.lang.String.class}
     )    
     public void test_findSystemClass() {
-        PackageClassLoader pcl = new PackageClassLoader();
+        PackageClassLoader pcl = new PackageClassLoader(
+                getClass().getClassLoader());
         
         Class [] classes = { String.class, Integer.class, Object.class,
                 Object[].class };
@@ -1064,7 +1061,8 @@
        args = {java.lang.String.class }
     )
     public void test_findLoadedClass() {
-       PackageClassLoader pcl = new PackageClassLoader();
+       PackageClassLoader pcl = new PackageClassLoader(
+               getClass().getClassLoader());
        
        Class [] classes = { A.class, PublicTestClass.class,
                TestAnnotation.class, TestClass1.class };
@@ -1140,6 +1138,31 @@
 }
 
 class Ldr extends ClassLoader {
+
+    /*
+     * These bytes are the content of the file
+     * /org/apache/harmony/luni/tests/java/lang/A.class
+     */
+    byte[] classBytes = new byte[] { -54, -2, -70, -66, 0, 0, 0, 49, 0, 16, 7,
+            0, 2, 1, 0, 41, 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47,
+            104, 97, 114, 109, 111, 110, 121, 47, 108, 117, 110, 105, 47, 116,
+            101, 115, 116, 115, 47, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
+            65, 7, 0, 4, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
+            79, 98, 106, 101, 99, 116, 1, 0, 6, 60, 105, 110, 105, 116, 62, 1,
+            0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 10, 0, 3, 0, 9, 12, 0,
+            5, 0, 6, 1, 0, 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114,
+            84, 97, 98, 108, 101, 1, 0, 18, 76, 111, 99, 97, 108, 86, 97, 114,
+            105, 97, 98, 108, 101, 84, 97, 98, 108, 101, 1, 0, 4, 116, 104, 105,
+            115, 1, 0, 43, 76, 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47,
+            104, 97, 114, 109, 111, 110, 121, 47, 108, 117, 110, 105, 47, 116,
+            101, 115, 116, 115, 47, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
+            65, 59, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105, 108, 101, 1,
+            0, 20, 67, 108, 97, 115, 115, 76, 111, 97, 100, 101, 114, 84, 101,
+            115, 116, 46, 106, 97, 118, 97, 0, 32, 0, 1, 0, 3, 0, 0, 0, 0, 0, 1,
+            0, 0, 0, 5, 0, 6, 0, 1, 0, 7, 0, 0, 0, 47, 0, 1, 0, 1, 0, 0, 0, 5,
+            42, -73, 0, 8, -79, 0, 0, 0, 2, 0, 10, 0, 0, 0, 6, 0, 1, 0, 0, 4,
+            -128, 0, 11, 0, 0, 0, 12, 0, 1, 0, 0, 0, 5, 0, 12, 0, 13, 0, 0, 0,
+            1, 0, 14, 0, 0, 0, 2, 0, 15 };
     
     public static final int TEST_CASE_DEFINE_0 = 0;
     public static final int TEST_CASE_DEFINE_1 = 1;
@@ -1148,27 +1171,23 @@
     
     @SuppressWarnings("deprecation")
     public Class<?> define(int len, int testCase) throws Exception {
-        Package p = getClass().getPackage();
-        String path = p == null ? "" : p.getName().replace('.', File.separatorChar)
-                + File.separator;
-        InputStream is = getResourceAsStream(path + "A.class");
-        byte[] buf = new byte[512];
-        if(len < 0) len = is.read(buf);
+        
+        if(len < 0) len = classBytes.length;
         Class<?> clazz = null;
         String className = "org.apache.harmony.luni.tests.java.lang.A";
         switch(testCase) {
             case TEST_CASE_DEFINE_0:
-                clazz = defineClass(className, buf, 0, len);
+                clazz = defineClass(className, classBytes, 0, len);
                 break;
             case TEST_CASE_DEFINE_1:
-                clazz = defineClass(buf, 0, len);                
+                clazz = defineClass(classBytes, 0, len);                
                 break;
             case TEST_CASE_DEFINE_2:
-                clazz = defineClass(className, buf, 0, len, 
+                clazz = defineClass(className, classBytes, 0, len, 
                         getClass().getProtectionDomain());
                 break;
             case TEST_CASE_DEFINE_3:
-                ByteBuffer bb = ByteBuffer.wrap(buf);
+                ByteBuffer bb = ByteBuffer.wrap(classBytes);
                 clazz = defineClass(className, 
                         bb, getClass().getProtectionDomain());                
                 break;
@@ -1187,6 +1206,10 @@
         super();
     }
 
+    public PackageClassLoader(ClassLoader parent) {
+        super(parent);
+    }
+
     public Package definePackage(String name,
             String specTitle,
             String specVersion,
diff --git a/libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java b/libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java
index 7a6c505..08e90bd 100644
--- a/libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java
+++ b/libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java
@@ -16,7 +16,6 @@
 
 package org.apache.harmony.luni.tests.java.net;
 
-import dalvik.annotation.BrokenTest;
 import dalvik.annotation.KnownFailure;
 import dalvik.annotation.TestLevel;
 import dalvik.annotation.TestTargetClass;
@@ -26,6 +25,9 @@
 import junit.framework.TestCase;
 
 import tests.support.Support_Configuration;
+import tests.support.Support_PortManager;
+import tests.support.Support_TestWebData;
+import tests.support.Support_TestWebServer;
 import tests.support.resource.Support_Resources;
 
 import java.io.BufferedReader;
@@ -56,8 +58,11 @@
 import java.net.URLStreamHandler;
 import java.net.UnknownServiceException;
 import java.security.Permission;
+import java.text.DateFormat;
+import java.text.ParseException;
 import java.util.Arrays;
 import java.util.Calendar;
+import java.util.Date;
 import java.util.GregorianCalendar;
 import java.util.List;
 import java.util.Map;
@@ -371,7 +376,8 @@
     URLConnection uc;
 
     URLConnection uc2;
-    
+
+    Support_TestWebServer server;
     
     @Override
     public void setUp() throws Exception {
@@ -379,10 +385,12 @@
         
 //        ftpURL = new URL(Support_Configuration.testFTPURL);
        
-        
-        url = new URL(Support_Configuration.hTTPURLgoogle);
+        port = Support_PortManager.getNextPort();
+        server = new Support_TestWebServer();
+        server.initServer(port, false);
+        url = new URL("http://localhost:" + port + "/test1");
         uc = url.openConnection();
-        url2 =  new URL(Support_Configuration.hTTPURLyahoo);
+        url2 =  new URL("http://localhost:" + port + "/test2");
         uc2 = url2.openConnection();
         
         fileURL = createTempHelloWorldFile();
@@ -393,14 +401,12 @@
         
         gifURLCon = openGifURLConnection();
         gifURL = gifURLCon.getURL();
-        
-        port = 80;
-        
     }
 
     @Override
     public void tearDown()throws Exception {
         super.tearDown();
+        server.close();
         ((HttpURLConnection) uc).disconnect();
         ((HttpURLConnection) uc2).disconnect();
 //        if (((FtpURLConnection) ftpURLCon).getInputStream() !=  null) {
@@ -704,11 +710,10 @@
         args = {}
     )
     public void test_getContentLength() {
-        assertEquals(testString.getBytes().length, fileURLCon.getContentLength());
-        assertEquals("getContentLength failed: " + uc.getContentLength(), -1,
-                uc.getContentLength());
-        
-        assertEquals(-1, uc2.getContentLength());
+        assertEquals(testString.getBytes().length,
+                fileURLCon.getContentLength());
+        assertEquals(Support_TestWebData.test1.length, uc.getContentLength());
+        assertEquals(Support_TestWebData.test2.length, uc2.getContentLength());
         
         assertNotNull(jarURLCon.getContentLength());
         assertNotNull(gifURLCon.getContentLength());
@@ -725,14 +730,14 @@
     )
     public void test_getContentType() throws IOException, MalformedURLException {
         
-        assertTrue("getContentType failed: " + fileURLCon.getContentType(), fileURLCon
-                .getContentType().contains("text/plain"));
+        assertTrue("getContentType failed: " + fileURLCon.getContentType(),
+                fileURLCon.getContentType().contains("text/plain"));
         
         URLConnection htmlFileCon = openHTMLFile();
         String contentType = htmlFileCon.getContentType();
         if (contentType != null) {
             assertTrue(contentType.equalsIgnoreCase("text/html"));
-            }
+        }
         
         
         /*
@@ -754,19 +759,16 @@
      */
     @TestTargetNew(
         level = TestLevel.COMPLETE,
-        notes = "From harmony branch.",
+        notes = "From harmony branch. URLConnection.getDate crashes in cases " +
+                "where the returned expiration date doesn't seems to be " +
+                "parsable. The RI just returns 0.",
         method = "getDate",
         args = {}
     )
     public void test_getDate() {
         // should be greater than 930000000000L which represents the past
-        if (uc.getDate() == 0) {
-            System.out
-                    .println("WARNING: server does not support 'Date', in test_getDate");
-        } else {
-            assertTrue("getDate gave wrong date: " + uc.getDate(),
+        assertTrue("getDate gave wrong date: " + uc.getDate(),
                     uc.getDate() > 930000000000L);
-        }
     }
 
     /**
@@ -848,7 +850,7 @@
         ),
         @TestTargetNew(
             level = TestLevel.COMPLETE,
-            notes = "From harmony branch. test fails: throws undocumented exception IllegalAccessException.",
+            notes = "From harmony branch.",
             method = "setDefaultUseCaches",
             args = {boolean.class}
         )
@@ -877,17 +879,16 @@
                 .getDefaultUseCaches());
         
         // subsequent connections should have default value
-        URL url3 =  new URL(Support_Configuration.hTTPURLyahoo);
+        URL url3 =  new URL("http://localhost:" + port + "/test2");
         URLConnection uc3 = url3.openConnection();
         assertFalse(uc3.getUseCaches());
         
-        // test if uc does not chash but uc2 does
+        // test if uc does not cache but uc2 does
         isGetCalled = false;
         isPutCalled = false;
         
         // test uc
         uc.setDoOutput(true);
-        
         assertFalse(isGetCalled);
         uc.connect();
         assertFalse(isGetCalled);
@@ -898,9 +899,6 @@
         
         os.close();
         
-        isGetCalled = false;
-        isPutCalled = false;
-        
         //uc2 should be unaffected
         uc2.setDoOutput(true);
         assertFalse(isGetCalled);
@@ -995,26 +993,22 @@
      */
     @TestTargetNew(
         level = TestLevel.COMPLETE,
-        notes = "From harmony branch.",
+        notes = "From harmony branch. URLConnection.getExpiration crashes in " +
+                "cases where the returned expiration date doesn't seems to " +
+                "be parsable. The RI just returns 0.",
         method = "getExpiration",
         args = {}
     )
-    @KnownFailure("URLConnection.getExpiration crashes because the returned" +
-            " expiration date doesn't seems to be parsable.")
     public void test_getExpiration() throws IOException {
-        URL url3 = new URL(Support_Configuration.hTTPURLwExpiration);
-        URLConnection uc3 = url3.openConnection();
         
         uc.connect();
         // should be unknown
         assertEquals("getExpiration returned wrong expiration", 0, uc
                 .getExpiration());
         
-        uc3.connect();
-        assertTrue("getExpiration returned wrong expiration", uc3
-                .getExpiration() > 0);
-        
-        ((HttpURLConnection) uc3).disconnect();
+        uc2.connect();
+        assertTrue("getExpiration returned wrong expiration: " + uc2
+                .getExpiration(), uc2.getExpiration() > 0);
     }
 
     /**
@@ -1069,34 +1063,37 @@
      */
     @TestTargetNew(
         level = TestLevel.COMPLETE,
-        notes = "From harmony branch.",
+        notes = "",
         method = "getHeaderFieldDate",
         args = {java.lang.String.class, long.class}
     )
+    @KnownFailure("getHeaderFieldDate on Content-Length throws an exception."
+            + " The RI just returns the default value")
     public void test_getHeaderFieldDateLjava_lang_StringJ() {
+        Support_TestWebData params = Support_TestWebData.testParams[0];
 
-        if (uc2.getHeaderFieldDate("Date", 22L) == 22L) {
-            System.out
-                    .println("WARNING: Server does not support 'Date', test_getHeaderFieldDateLjava_lang_StringJ not run");
-            return;
-        }
-        
-        if (uc2.getIfModifiedSince() > 0) {
-        
-        long time = uc2.getHeaderFieldDate("Last-Modified", 0);
-        assertTrue(time > 0);
-        /*
-          assertEquals("Wrong date: ", time,
-                Support_Configuration.URLConnectionLastModified);
-        */        
-        }
-        
-        long defaultTime;
-        
-        if (uc.getIfModifiedSince() == 0) {
-            defaultTime = uc.getHeaderFieldDate("Last-Modified", 0);
-            assertEquals(defaultTime,0);
-        }
+        long hf;
+        hf = uc.getHeaderFieldDate("Content-Encoding", Long.MIN_VALUE);
+        assertEquals("Long value returned for header field 'Content-Encoding':",
+                Long.MIN_VALUE, hf);
+        hf = uc.getHeaderFieldDate("Content-Length", Long.MIN_VALUE);
+        assertEquals("Long value returned for header field 'Content-Length': ",
+                Long.MIN_VALUE, hf);
+        hf = uc.getHeaderFieldDate("Content-Type", Long.MIN_VALUE);
+        assertEquals("Long value returned for header field 'Content-Type': ",
+                Long.MIN_VALUE, hf);
+        hf = uc.getHeaderFieldDate("content-type", Long.MIN_VALUE);
+        assertEquals("Long value returned for header field 'content-type': ",
+                Long.MIN_VALUE, hf);
+        hf = uc.getHeaderFieldDate("Date", Long.MIN_VALUE);
+        assertTrue("Wrong value returned for header field 'Date': " + hf,
+                new Date().getTime() - hf < 5000);
+        hf = uc.getHeaderFieldDate("SERVER", Long.MIN_VALUE);
+        assertEquals("Long value returned for header field 'SERVER': ",
+                Long.MIN_VALUE, hf);
+        hf = uc.getHeaderFieldDate("Last-Modified", Long.MIN_VALUE);
+        assertEquals("Long value returned for header field 'Last-Modified': ",
+                Long.MIN_VALUE, hf);
     }
 
     /**
@@ -1167,34 +1164,29 @@
         method = "getHeaderFieldInt",
         args = {java.lang.String.class, int.class}
     )
-    public void test_getHeaderFieldInt() throws IOException {
-        String header;
-        URL url3 = new URL(Support_Configuration.hTTPURLwExpiration);
-        URLConnection uc3 = url3.openConnection();
-        
+    public void test_getHeaderFieldInt() throws IOException, ParseException {
+        Support_TestWebData params = Support_TestWebData.testParams[1];
+
         int hf = 0;
-        hf = uc2.getHeaderFieldInt("Content-Encoding",Integer.MIN_VALUE);
+        hf = uc2.getHeaderFieldInt("Content-Encoding", Integer.MIN_VALUE);
         assertEquals(Integer.MIN_VALUE, hf);
-        hf = uc2.getHeaderFieldInt("Content-Length",Integer.MIN_VALUE);
+        hf = uc2.getHeaderFieldInt("Content-Length", Integer.MIN_VALUE);
+        assertEquals(params.testLength, hf);
+        hf = uc2.getHeaderFieldInt("Content-Type", Integer.MIN_VALUE);
         assertEquals(Integer.MIN_VALUE, hf);
-        hf = uc2.getHeaderFieldInt("Content-Type",Integer.MIN_VALUE);
+        hf = uc2.getHeaderFieldInt("Date", Integer.MIN_VALUE);
         assertEquals(Integer.MIN_VALUE, hf);
-        hf = uc2.getHeaderFieldInt("Date",Integer.MIN_VALUE);
+        hf = uc2.getHeaderFieldInt("Expires", Integer.MIN_VALUE);
         assertEquals(Integer.MIN_VALUE, hf);
-        long exp = uc3.getHeaderFieldDate("Expires", 0);
-        assertTrue(exp > 0);
-        hf = uc2.getHeaderFieldInt("SERVER",Integer.MIN_VALUE);
+        hf = uc2.getHeaderFieldInt("SERVER", Integer.MIN_VALUE);
         assertEquals(Integer.MIN_VALUE, hf);
-        hf = uc2.getHeaderFieldInt("Last-Modified",Integer.MIN_VALUE);
+        hf = uc2.getHeaderFieldInt("Last-Modified", Integer.MIN_VALUE);
         assertEquals(Integer.MIN_VALUE, hf);
-        hf = uc2.getHeaderFieldInt("accept-ranges",Integer.MIN_VALUE);
+        hf = uc2.getHeaderFieldInt("accept-ranges", Integer.MIN_VALUE);
         assertEquals(Integer.MIN_VALUE, hf);
-        hf = uc2.getHeaderFieldInt("DoesNotExist",Integer.MIN_VALUE);
+        hf = uc2.getHeaderFieldInt("DoesNotExist", Integer.MIN_VALUE);
         assertEquals(Integer.MIN_VALUE, hf);
-        hf = uc2.getHeaderFieldInt("Age",Integer.MIN_VALUE);
-        assertFalse(hf == Integer.MIN_VALUE);
         
-        ((HttpURLConnection) uc3).disconnect();
     }
 
     /**
@@ -1206,64 +1198,31 @@
         method = "getHeaderField",
         args = {java.lang.String.class}
     )
-    @BrokenTest("Flaky due to third party servers used to do the test.")
     public void test_getHeaderFieldLjava_lang_String() {
+        Support_TestWebData params = Support_TestWebData.testParams[0];
+
         String hf;
-        int hfDefault;
         hf = uc.getHeaderField("Content-Encoding");
-        if (hf != null) {
-            assertNull(
-                    "Wrong value returned for header field 'Content-Encoding': "
-                            + hf, hf);
-        }
+        assertNull("String value returned for header field 'Content-Encoding':",
+                hf);
         hf = uc.getHeaderField("Content-Length");
-        if (hf != null) {
-            assertEquals(
-                    "Wrong value returned for header field 'Content-Length': ",
-                    "25", hf);
-        }
+        assertEquals("Wrong value returned for header field 'Content-Length': ",
+                String.valueOf(params.testLength), hf);
         hf = uc.getHeaderField("Content-Type");
-        if (hf != null) {
-            assertTrue("Wrong value returned for header field 'Content-Type': "
-                    + hf, hf.contains("text/html"));
-        }
+        assertEquals("Wrong value returned for header field 'Content-Type': ",
+                params.testType, hf);
         hf = uc.getHeaderField("content-type");
-        if (hf != null) {
-            assertTrue("Wrong value returned for header field 'content-type': "
-                    + hf, hf.contains("text/html"));
-        }
+        assertEquals("Wrong value returned for header field 'content-type': ",
+                params.testType, hf);
         hf = uc.getHeaderField("Date");
-        if (hf != null) {
-            assertTrue("Wrong value returned for header field 'Date': " + hf,
-                    Integer.parseInt(hf.substring(hf.length() - 17,
-                            hf.length() - 13)) >= 1999);
-        }
-        hf = uc.getHeaderField("Expires");
-        if (hf != null) {
-            assertNull(
-                    "Wrong value returned for header field 'Expires': " + hf,
-                    hf);
-        }
+        assertTrue("Wrong string value returned for header field 'Date': "
+                + hf, hf.length() > 20);
         hf = uc.getHeaderField("SERVER");
-        assertNotNull(hf);
+        assertEquals("Wrong value returned for header field 'SERVER': ",
+                "TestWebServer" + port, hf);
         hf = uc.getHeaderField("Last-Modified");
-        if (hf != null) {
-            assertTrue(
-                    "No valid header field "
-                            + hf,
-                    Long.parseLong(hf) > 930000000000L);
-        }
-        hf = uc.getHeaderField("accept-ranges");
-        if (hf != null) {
-            assertTrue(
-                    "Wrong value returned for header field 'accept-ranges': "
-                            + hf, hf.equals("bytes"));
-        }
-        hf = uc.getHeaderField("DoesNotExist");
-        if (hf != null) {
-            assertNull("Wrong value returned for header field 'DoesNotExist': "
-                    + hf, hf);
-        }
+        assertNull("Wrong string value returned for 'Last-Modified': "
+                + hf, hf);
     }
 
     /**
@@ -1273,11 +1232,13 @@
      */
     @TestTargetNew(
         level = TestLevel.COMPLETE,
-        notes = "From harmony branch.",
+        notes = "",
         method = "getHeaderFields",
         args = {}
     )
     public void test_getHeaderFields() throws IOException, ClassNotFoundException, URISyntaxException {
+        Support_TestWebData params = Support_TestWebData.testParams[1];
+
         try {
             uc2.getInputStream();
         } catch (IOException e) {
@@ -1287,20 +1248,23 @@
         Map<String, List<String>> headers = uc2.getHeaderFields();
         assertNotNull(headers);
 
-        // 'content-type' is most likely to appear
         List<String> list = headers.get("content-type");
         if (list == null) {
             list = headers.get("Content-Type");
         }
+        if (list == null) {
+            list = headers.get("Content-type");
+        }
+
         assertNotNull(list);
         String contentType = (String) list.get(0);
-        assertNotNull(contentType);
+        assertEquals(params.testType, contentType);
 
         // there should be at least 2 headers
-        assertTrue("Not more than one header in URL connection",headers.size() > 1);
+        assertTrue("Not more than one header in URL connection",
+                headers.size() > 1);
         
-        JarURLConnection con1 = openJarURLConnection();
-        headers = con1.getHeaderFields();
+        headers = jarURLCon.getHeaderFields();
         assertNotNull(headers);
         assertEquals(0, headers.size());
 
@@ -1355,17 +1319,19 @@
     )
     public void test_getOutputStream() throws IOException {
         String posted = "this is a test";
-        uc.setDoOutput(true);
-        uc.connect();
+        URLConnection uc3 = new URL(Support_Configuration.hTTPURLgoogle)
+                .openConnection();
+        uc3.setDoOutput(true);
+        uc3.connect();
 
-        BufferedWriter w = new BufferedWriter(new OutputStreamWriter(uc
+        BufferedWriter w = new BufferedWriter(new OutputStreamWriter(uc3
                 .getOutputStream()), posted.getBytes().length);
 
         w.write(posted);
         w.flush();
         w.close();
 
-        int code = ((HttpURLConnection) uc).getResponseCode();
+        int code = ((HttpURLConnection) uc3).getResponseCode();
 
 
         // writing to url not allowed
@@ -1405,7 +1371,7 @@
         assertTrue("Permission of wrong type: " + p.toString(),
                 p instanceof java.net.SocketPermission);
         assertTrue("Permission has wrong name: " + p.getName(), p.getName()
-                .contains("google.com:" + port));
+                .contains("localhost:" + port));
 
         URL fileUrl = new URL("file:myfile");
         Permission perm = new FilePermission("myfile", "read");
@@ -1640,37 +1606,29 @@
      */
     @TestTargetNew(
         level = TestLevel.COMPLETE,
-        notes = "test fails at UTF-8 stage. Test from harmony branch",
+        notes = "",
         method = "guessContentTypeFromStream",
         args = {java.io.InputStream.class}
     )
-    @BrokenTest("MIME type application xml is not supported: only text html."+
-            " Should be implemented if compatibility is required. The RI" +
-            " on the other hand doesn't recognise the '<head' tag.")
+    @KnownFailure("'<?xml' recognised as text/html instead of application/xml")
     public void test_guessContentTypeFromStreamLjava_io_InputStream()
             throws IOException {
-        String[] headers = new String[] { "<html>", "<head>", " <head ",
-                "<body", "<BODY ", //"<!DOCTYPE html",
-                "<?xml " };
-        String[] expected = new String[] { "text/html","text/html", "text/html",
-                "text/html","text/html", "application/xml" };
+        assertContentTypeEquals("ASCII", "text/html", "<html>");
+        assertContentTypeEquals("ASCII", "text/html", "<head>");
+        assertContentTypeEquals("ASCII", "text/html", "<head ");
+        assertContentTypeEquals("ASCII", "text/html", "<body");
+        assertContentTypeEquals("ASCII", "text/html", "<BODY ");
+        assertContentTypeEquals("ASCII", "application/xml", "<?xml ");
 
-        String[] encodings = new String[] { "ASCII", "UTF-8", 
-                //"UTF-16BE", not supported
-                //"UTF-16LE", not supported
-                //"UTF-32BE", not supported encoding
-                //"UTF-32LE" not supported encoding
-                };
-        for (int i = 0; i < headers.length; i++) {
-            for (String enc : encodings) {
-                ByteArrayOutputStream bos = new ByteArrayOutputStream();
-                String encodedString = new String(headers[i].getBytes(), enc);
-                InputStream is = new ByteArrayInputStream(encodedString.getBytes());
-                String mime = URLConnection.guessContentTypeFromStream(is);
-                assertEquals("checking " + headers[i] + " with " + enc,
-                        expected[i], mime);
-            }
-        }
+        assertContentTypeEquals("UTF-8", "text/html", "<html>");
+        assertContentTypeEquals("UTF-8", "text/html", "<head>");
+        assertContentTypeEquals("UTF-8", "text/html", "<head ");
+        assertContentTypeEquals("UTF-8", "text/html", "<body");
+        assertContentTypeEquals("UTF-8", "text/html", "<BODY ");
+        assertContentTypeEquals("UTF-8", "application/xml", "<?xml ");
+        
+        //"UTF-16BE", "UTF-16LE", "UTF-32BE" and
+        //"UTF-32LE" are not supported
 
         // Try simple case
         try {
@@ -1691,74 +1649,16 @@
         }
         */
     }
-    
-//    /**
-//     * @throws IOException 
-//     * @throws IllegalAccessException 
-//     * @throws IllegalArgumentException 
-//     * @throws URISyntaxException 
-//     * @throws MalformedURLException
-//     * @tests {@link java.net.URLConnection#setContentHandlerFactory(java.net.ContentHandlerFactory)}
-//     */
-//    @TestTargetNew(
-//        level = TestLevel.SUFFICIENT,
-//        notes = "test adopted from ConentHandlerFactoryTest.",
-//        method = "setContentHandlerFactory",
-//        args = {java.net.ContentHandlerFactory.class}
-//    )
-//    public void testSetContentHandlerFactory() throws IOException,
-//            IllegalArgumentException, IllegalAccessException, URISyntaxException {
-//        String[] files = {
-//                "hyts_checkInput.txt", "hyts_htmltest.html"};
-//        ContentHandlerFactory factory = new TestContentHandlerFactory();
-//        Field contentHandlerFactoryField = null;
-//        int counter = 0;
-//
-//
-//        Field[] fields = URLConnection.class.getDeclaredFields();
-//
-//
-//        for (Field f : fields) {
-//            if (ContentHandlerFactory.class.equals(f.getType())) {
-//                counter++;
-//                contentHandlerFactoryField = f;
-//            }
-//        }
-//
-//        if (counter != 1) {
-//            fail("Error in test setup: not Factory found");
-//        }
-//
-//        contentHandlerFactoryField.setAccessible(true);
-//        ContentHandlerFactory old = (ContentHandlerFactory) contentHandlerFactoryField
-//                .get(null);
-//
-//        try {
-//            contentHandlerFactoryField.set(null, factory);
-//
-//            Vector<URL> urls = createContent(files);
-//            for (int i = 0; i < urls.size(); i++) {
-//                URLConnection urlCon = null;
-//                try {
-//                    urlCon = urls.elementAt(i).openConnection();
-//                    urlCon.setDoInput(true);
-//                    Object obj = urlCon.getContent();
-//                    if (obj instanceof String) {
-//                        String s = (String) obj;
-//                        assertTrue("Returned incorrect content for "
-//                                + urls.elementAt(i) + ": " + s, 
-//                                s.equals("ok"));
-//                    } else {
-//                        fail("Got wrong content handler");
-//                    }
-//                } catch (IOException e) {
-//                    fail("IOException was thrown for URL: "+ urls.elementAt(i).toURI().toString() +" " + e.toString());
-//                }
-//            }
-//        } finally {
-//            contentHandlerFactoryField.set(null, old);
-//        }
-//    }
+
+    void assertContentTypeEquals(String encoding, String expected,
+            String header) throws IOException {
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        String encodedString = new String(header.getBytes(), encoding);
+        InputStream is = new ByteArrayInputStream(encodedString.getBytes());
+        String mime = URLConnection.guessContentTypeFromStream(is);
+        assertEquals("checking '" + header + "' with " + encoding,
+                expected, mime);
+    }
 
     /**
      * @tests {@link java.net.URLConnection#setConnectTimeout(int)}
@@ -2018,7 +1918,6 @@
         method = "getInputStream",
         args = {}
       )
-    @BrokenTest("Flaky test due to the use of third party servers")
     public void testGetInputStream() throws IOException {
         fileURLCon.setDoInput(true);
         fileURLCon.connect();
@@ -2033,18 +1932,11 @@
 
         buf.close();
 
+        assertNotNull(uc.getInputStream());
 
-        ((HttpURLConnection) uc).disconnect();
+        ((HttpURLConnection) uc2).disconnect();
 
-        try {
-            uc.getInputStream();
-            fail("Exception expected");
-        } catch (IOException e) {
-            // ok
-        }
-
-        uc2.getInputStream();
-
+        assertNotNull(uc2.getInputStream());
 
     }
     
@@ -2133,58 +2025,4 @@
         // read content from file
         return sampleFile.toURL();
     }
-    
-//    /**
-//     * Method copied form ContentHandlerFactory
-//     */
-//    private Vector<URL> createContent(String [] files) {
-//        
-//        File resources = new File(System.getProperty("java.io.tmpdir"));
-//        
-//        String resPath = resources.toString();
-//        if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\')
-//            resPath = resPath.substring(1);
-//        
-//        Vector<URL> urls = new Vector<URL> ();
-//        
-//        for(String file:files) {
-//            Support_Resources.copyFile(resources, null, file);
-//            URL resourceURL;
-//            try {
-//                resourceURL = new URL("file:/" + resPath + "/"
-//                        + file);
-//                urls.add(resourceURL);
-//            } catch (MalformedURLException e) {
-//                fail("URL can be created for " + file);
-//            }
-//            
-//        }
-//        return urls;
-//    }
-//    
-//    public class TestContentHandler extends ContentHandler {
-//
-//        public Object getContent(URLConnection u) {
-//             
-//            return new String("ok");
-//        }
-//    }
-//    
-//
-//    public class TestContentHandlerFactory implements ContentHandlerFactory {
-//
-//        final String[] mimeTypes = {
-//                "text/plain", "application/xml", "image/gif", "application/zip"};
-//
-//        public ContentHandler createContentHandler(String mimetype) {
-//            boolean isAllowed = false;
-//            for (String mime : mimeTypes) {
-//                if (mime.equals(mimetype)) isAllowed = true;
-//            }
-//            if (isAllowed) {
-//                return new TestContentHandler();
-//            } else
-//                return null;
-//        }
-//    }
 }
diff --git a/libcore/luni/src/test/java/tests/api/java/io/PrintStreamTest.java b/libcore/luni/src/test/java/tests/api/java/io/PrintStreamTest.java
index ccc0bc1..2ec5feb 100644
--- a/libcore/luni/src/test/java/tests/api/java/io/PrintStreamTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/io/PrintStreamTest.java
@@ -29,6 +29,7 @@
 import java.util.IllegalFormatException;
 import java.util.Locale;
 
+import dalvik.annotation.KnownFailure;
 import dalvik.annotation.TestLevel;
 import dalvik.annotation.TestTargetClass;
 import dalvik.annotation.TestTargetNew;
@@ -986,6 +987,7 @@
         method = "format",
         args = {java.util.Locale.class, java.lang.String.class, java.lang.Object[].class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_formatLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
         PrintStream tobj;
 
@@ -1098,6 +1100,7 @@
         method = "printf",
         args = {java.util.Locale.class, java.lang.String.class, java.lang.Object[].class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_printfLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
         PrintStream tobj;
 
diff --git a/libcore/luni/src/test/java/tests/api/java/io/PrintWriterTest.java b/libcore/luni/src/test/java/tests/api/java/io/PrintWriterTest.java
index 2796e7b..c275525 100644
--- a/libcore/luni/src/test/java/tests/api/java/io/PrintWriterTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/io/PrintWriterTest.java
@@ -31,6 +31,7 @@
 
 import tests.support.Support_StringReader;
 import tests.support.Support_StringWriter;
+import dalvik.annotation.KnownFailure;
 import dalvik.annotation.TestLevel;
 import dalvik.annotation.TestTargetClass;
 import dalvik.annotation.TestTargetNew;
@@ -1106,6 +1107,7 @@
         method = "format",
         args = {java.util.Locale.class, java.lang.String.class, java.lang.Object[].class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_formatLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
         PrintWriter tobj;
 
@@ -1217,6 +1219,7 @@
         method = "printf",
         args = {java.util.Locale.class, java.lang.String.class, java.lang.Object[].class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_printfLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
         PrintWriter tobj;
 
diff --git a/libcore/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionCornerCases.java b/libcore/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionCornerCases.java
index a0af46e..31dfaa5 100644
--- a/libcore/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionCornerCases.java
+++ b/libcore/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionCornerCases.java
@@ -16,6 +16,7 @@
 
 package tests.api.java.lang.reflect;
 
+import dalvik.annotation.KnownFailure;
 import dalvik.annotation.TestTargets;
 import dalvik.annotation.TestLevel;
 import dalvik.annotation.TestTargetNew;
@@ -168,6 +169,8 @@
         )
     })
     @SuppressWarnings("unchecked")
+    @KnownFailure("Class MultipleBoundedWildcardUnEquality can not be found, "
+            + "maybe the wrong class loader is used to get the raw type?")
     public void testMultipleBoundedWildcardUnEquality() throws Exception {
         Class<? extends MultipleBoundedWildcardUnEquality> clazz = MultipleBoundedWildcardUnEquality.class;
 
@@ -237,6 +240,8 @@
         )
     })
     @SuppressWarnings("unchecked")
+    @KnownFailure("Class MultipleBoundedWildcardEquality can not be found, "
+            + "maybe the wrong class loader is used to get the raw type?")
     public void testMultipleBoundedWildcard() throws Exception {
         Class<? extends MultipleBoundedWildcardEquality> clazz = MultipleBoundedWildcardEquality.class;
 
diff --git a/libcore/luni/src/test/java/tests/api/java/lang/reflect/GenericTypesTest.java b/libcore/luni/src/test/java/tests/api/java/lang/reflect/GenericTypesTest.java
index d02a1ba..c9255b2 100644
--- a/libcore/luni/src/test/java/tests/api/java/lang/reflect/GenericTypesTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/lang/reflect/GenericTypesTest.java
@@ -16,6 +16,7 @@
 
 package tests.api.java.lang.reflect;
 
+import dalvik.annotation.KnownFailure;
 import dalvik.annotation.TestTargets;
 import dalvik.annotation.TestLevel;
 import dalvik.annotation.TestTargetNew;
@@ -200,6 +201,8 @@
         args = {}
     )
     @SuppressWarnings("unchecked")
+    @KnownFailure("Class GenericType can not be found, "
+            + "maybe the wrong class loader is used to get the raw type?")
     public void testSimpleInheritance() throws Exception {
         Class<? extends SimpleInheritance> clazz = SimpleInheritance.class;
         TypeVariable<Class> subTypeVariable = getTypeParameter(clazz);
diff --git a/libcore/luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java b/libcore/luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java
index adeb9e2..eaff7c8 100644
--- a/libcore/luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java
@@ -16,6 +16,7 @@
 
 package tests.api.java.lang.reflect;
 
+import dalvik.annotation.KnownFailure;
 import dalvik.annotation.TestTargets;
 import dalvik.annotation.TestLevel;
 import dalvik.annotation.TestTargetNew;
@@ -54,6 +55,8 @@
             args = {}
         )
     })
+    @KnownFailure("Class A can not be found, "
+            + "maybe the wrong class loader is used to get the raw type?")
     public void testStringParameterizedSuperClass() {
         Class<? extends B> clazz = B.class;
         Type genericSuperclass = clazz.getGenericSuperclass();
@@ -90,6 +93,8 @@
             args = {}
         )
     })
+    @KnownFailure("Class C can not be found, "
+            + "maybe the wrong class loader is used to get the raw type?")
     public void testTypeParameterizedSuperClass() {
         Class<? extends D> clazz = D.class;
         Type genericSuperclass = clazz.getGenericSuperclass();
diff --git a/libcore/luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java b/libcore/luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java
index 051d5b2..c2552a3 100644
--- a/libcore/luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java
@@ -89,7 +89,6 @@
         method = "getProxyClass",
         args = {java.lang.ClassLoader.class, java.lang.Class[].class}
     )
-    @KnownFailure("Needs investigation")
     public void test_getProxyClassLjava_lang_ClassLoader$Ljava_lang_Class() {
         Class proxy = Proxy.getProxyClass(Support_Proxy_I1.class
                 .getClassLoader(), new Class[] { Support_Proxy_I1.class });
diff --git a/libcore/luni/src/test/java/tests/api/java/net/DatagramSocketTest.java b/libcore/luni/src/test/java/tests/api/java/net/DatagramSocketTest.java
index 0fc121b..e0cc466 100644
--- a/libcore/luni/src/test/java/tests/api/java/net/DatagramSocketTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/net/DatagramSocketTest.java
@@ -158,7 +158,6 @@
         method = "DatagramSocket",
         args = {int.class}
     )
-    @KnownFailure("New DatagramSocket(1) doesn't throw an expected exception.")
     public void test_ConstructorI() {
         // Test for method java.net.DatagramSocket(int)
         try {
diff --git a/libcore/luni/src/test/java/tests/api/java/net/ResponseCacheTest.java b/libcore/luni/src/test/java/tests/api/java/net/ResponseCacheTest.java
index c64fd82..8aeb820 100644
--- a/libcore/luni/src/test/java/tests/api/java/net/ResponseCacheTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/net/ResponseCacheTest.java
@@ -16,12 +16,14 @@
 
 package tests.api.java.net;
 
-import dalvik.annotation.BrokenTest;
+import dalvik.annotation.KnownFailure;
 import dalvik.annotation.TestTargetClass; 
 import dalvik.annotation.TestTargets;
 import dalvik.annotation.TestLevel;
 import dalvik.annotation.TestTargetNew;
 
+import java.io.File;
+import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
@@ -35,24 +37,17 @@
 import java.net.URL;
 import java.net.URLConnection;
 import java.security.Permission;
+import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 
 import junit.framework.TestCase;
 
-import tests.support.Support_Configuration;
+import tests.support.Support_PortManager;
+import tests.support.Support_TestWebData;
+import tests.support.Support_TestWebServer;
 
-@TestTargetClass(
-    value = ResponseCache.class,
-    untestedMethods = {
-        @TestTargetNew(
-            level = TestLevel.NOT_FEASIBLE,
-            notes = "put method is not tested completely",
-            method = "put",
-            args = {java.net.URI.class, java.net.URLConnection.class}
-        )
-    }
-)
+@TestTargetClass(value = ResponseCache.class)
 public class ResponseCacheTest extends TestCase {
 
     
@@ -160,15 +155,13 @@
         level = TestLevel.COMPLETE,
         notes = "",
         method = "get",
-        args = {java.net.URI.class, java.lang.String.class, java.util.Map.class}
+        args = {URI.class, String.class, Map.class}
     )
-    @BrokenTest("This test fails on both RI and android. Also only getting " +
-            "from the cache is tested. The put method is not tested.")
-    public void test_get_put() throws Exception {
-        
-        URL url  = new URL("http://" + 
-                Support_Configuration.SpecialInetTestAddress);
-        ResponseCache.setDefault(new TestResponseCache());
+    public void test_get() throws Exception {
+        String uri = "http://localhost/";
+        URL url  = new URL(uri);
+        TestResponseCache cache = new TestResponseCache(uri, true);
+        ResponseCache.setDefault(cache);
         HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
         httpCon.setUseCaches(true);
         httpCon.connect();
@@ -177,17 +170,65 @@
         } catch(Exception e) {}
         
         InputStream is = httpCon.getInputStream();
-        byte [] array = new byte [10];
+        byte[] array = new byte [10];
         is.read(array);
+        assertEquals(url.toURI(), cache.getWasCalled);
         assertEquals("Cache test", new String(array));
-
-        try {
-            Thread.sleep(5000);
-        } catch(Exception e) {}
         is.close();
         httpCon.disconnect();
+
     }
 
+    @TestTargetNew(
+        level = TestLevel.COMPLETE,
+        notes = "",
+        method = "put",
+        args = {URI.class, URLConnection.class}
+    )
+    @KnownFailure("the call to put is made with a wrong uri."
+            + " The RI calls with http://localhost:<port>/test1,"
+            + " but android only calls with http://localhost:<port>")
+    public void test_put() throws Exception {
+        // Create test ResponseCache
+        TestResponseCache cache = new TestResponseCache(
+                "http://localhost/not_cached", false);
+        ResponseCache.setDefault(cache);
+
+        // Start Server
+        int port = Support_PortManager.getNextPort();
+        Support_TestWebServer s = new Support_TestWebServer();
+        try {
+            s.initServer(port, 10000, false);
+            Thread.currentThread().sleep(2500);
+    
+            // Create connection to server
+            URL url  = new URL("http://localhost:" + port + "/test1");
+            HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
+            httpCon.setUseCaches(true);
+            httpCon.connect();
+            Thread.currentThread().sleep(2500);
+    
+            // Check that a call to the cache was made.
+            assertEquals(url.toURI(), cache.getWasCalled);
+            // Make the HttpConnection get the content. It should try to
+            // put it into the cache.
+            httpCon.getContent();
+            // Check if put was called
+            assertEquals(url.toURI(), cache.putWasCalled);
+    
+            // get the 
+            InputStream is = httpCon.getInputStream();
+    
+            byte[] array = new byte[Support_TestWebData.test1.length];
+            is.read(array);
+            assertTrue(Arrays.equals(Support_TestWebData.tests[0], array));
+            is.close();
+            httpCon.disconnect();
+        } finally {
+            s.close();
+        }
+    }
+    
     /*
      * MockResponseCache for testSetDefault(ResponseCache)
      */
@@ -240,56 +281,61 @@
             is = getClass().getResourceAsStream("/" + path + "/" + filename);
         }
 
-        public InputStream getBody() throws IOException {
+        @Override
+        public InputStream getBody() {
            return is;
         }
 
-         public Map getHeaders() throws IOException {
+        @Override
+         public Map getHeaders() {
            return null;
          }
     }
-    
+
     class TestCacheRequest extends CacheRequest {
-        
-        public TestCacheRequest(String filename,
-                            Map<String, List<String>> rspHeaders) {
-        }
-        public OutputStream getBody() throws IOException {
+
+        @Override
+        public OutputStream getBody() {
             return null;
         }
 
+        @Override
         public void abort() {
         }
     }
     
     class TestResponseCache extends ResponseCache {
-        
-        URI uri1 = null;    
-    
-        public CacheResponse get(URI uri, String rqstMethod, Map rqstHeaders)
-                throws IOException {
-          try {
-            uri1  = new URI("http://" + 
-                    Support_Configuration.SpecialInetTestAddress);
-          } catch (URISyntaxException e) {
-          }  
-          if (uri.equals(uri1)) {
-            return new TestCacheResponse("file1.cache");
-          }
-          return null;
+
+        URI uri1 = null;
+        boolean testGet = false;
+
+        public URI getWasCalled = null;
+        public URI putWasCalled = null;
+
+        TestResponseCache(String uri, boolean testGet) {
+            try {
+                uri1  = new URI(uri);            
+            } catch (URISyntaxException e) {
+            }
+            this.testGet = testGet;
         }
 
-       public CacheRequest put(URI uri, URLConnection conn)
-              throws IOException {
-           try {
-               uri1  = new URI("http://www.google.com");
-             } catch (URISyntaxException e) {
-             }  
-          if (uri.equals(uri1)) {
-              return new TestCacheRequest("file2.cache",
-                          conn.getHeaderFields());
-          }
-          return null;
+        @Override
+        public CacheResponse get(URI uri, String rqstMethod, Map rqstHeaders) {
+            getWasCalled = uri;
+            if (testGet && uri.equals(uri1)) {
+                return new TestCacheResponse("file1.cache");
+            }
+            return null;
+        }
+
+        @Override
+        public CacheRequest put(URI uri, URLConnection conn) {
+            putWasCalled = uri;
+            if (!testGet && uri.equals(uri1)) {
+                return new TestCacheRequest();
+            }
+            return null;
         }
     }
 }
\ No newline at end of file
diff --git a/libcore/luni/src/test/java/tests/api/java/net/URLClassLoaderTest.java b/libcore/luni/src/test/java/tests/api/java/net/URLClassLoaderTest.java
index 2b8e33f..2e3baae 100644
--- a/libcore/luni/src/test/java/tests/api/java/net/URLClassLoaderTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/net/URLClassLoaderTest.java
@@ -17,20 +17,26 @@
 
 package tests.api.java.net;
 
-import dalvik.annotation.BrokenTest; 
-import dalvik.annotation.TestTargetClass; 
-import dalvik.annotation.TestTargets;
+import dalvik.annotation.BrokenTest;
+import dalvik.annotation.SideEffect;
 import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
 import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
+import org.apache.harmony.security.tests.support.TestCertUtils;
+
+import tests.support.Support_Configuration;
+import tests.support.Support_PortManager;
+import tests.support.Support_TestWebData;
+import tests.support.Support_TestWebServer;
+import tests.support.resource.Support_Resources;
 
 import java.io.File;
-import java.io.FilePermission;
+import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.net.DatagramSocket;
 import java.net.MalformedURLException;
-import java.net.SocketException;
-import java.net.URI;
 import java.net.URL;
 import java.net.URLClassLoader;
 import java.net.URLStreamHandler;
@@ -38,21 +44,24 @@
 import java.security.CodeSource;
 import java.security.Permission;
 import java.security.PermissionCollection;
-import java.security.Permissions;
 import java.security.cert.Certificate;
+import java.util.ArrayList;
 import java.util.Enumeration;
-import java.util.NoSuchElementException;
-import java.util.StringTokenizer;
+import java.util.List;
 import java.util.Vector;
 import java.util.jar.Manifest;
 
-import org.apache.harmony.luni.util.InvalidJarIndexException;
-import org.apache.harmony.security.tests.support.TestCertUtils;
-
-import tests.support.Support_Configuration;
-import tests.support.resource.Support_Resources;
-
-@TestTargetClass(URLClassLoader.class) 
+@TestTargetClass(
+    value = URLClassLoader.class,
+    untestedMethods = {
+        @TestTargetNew(
+            level = TestLevel.NOT_NECESSARY,
+            notes = "findClass uses defineClass which is not implemented",
+            method = "findClass",
+            args = {java.lang.String.class}
+        )
+    }
+)
 public class URLClassLoaderTest extends junit.framework.TestCase {
 
     class BogusClassLoader extends ClassLoader {
@@ -169,36 +178,52 @@
      * @tests java.net.URLClassLoader#findResources(java.lang.String)
      */
     @TestTargetNew(
-        level = TestLevel.SUFFICIENT,
-        notes = "IOException checking missed.",
+        level = TestLevel.COMPLETE,
+        notes = "IOException checking missing. "
+            + "A test case that loads a resource from a webserver is missing.",
         method = "findResources",
         args = {java.lang.String.class}
     )
-    @BrokenTest("web address used from support doesn't work anymore")
-    public void test_findResourcesLjava_lang_String() throws IOException {
-        Enumeration res = null;
+    @SideEffect("Support_TestWebServer requires isolation.")
+    public void test_findResourcesLjava_lang_String() throws Exception {
+        Enumeration<URL> res = null;
         String[] resValues = { "This is a test resource file.",
-                "This is a resource from a subdir" };
+                "This is a resource from a subdir"};
+
+        String tmp = System.getProperty("java.io.tmpdir") + "/";
+
+        File tmpDir = new File(tmp);
+        File test1 = new File(tmp + "test0");
+        test1.deleteOnExit();
+        FileOutputStream out = new FileOutputStream(test1);
+        out.write(resValues[0].getBytes());
+        out.flush();
+        out.close();
+
+        File subDir = new File(tmp + "subdir/");
+        subDir.mkdir();
+        File test2 = new File(tmp + "subdir/test0");
+        test2.deleteOnExit();
+        out = new FileOutputStream(test2);
+        out.write(resValues[1].getBytes());
+        out.flush();
+        out.close();
 
         URL[] urls = new URL[2];
-        urls[0] = new URL(Support_Resources.getResourceURL("/"));
-        urls[1] = new URL(Support_Resources.getResourceURL("/subdir1/"));
+        urls[0] = new URL("file://" + tmpDir.getAbsolutePath() + "/");
+        urls[1] = new URL("file://" + subDir.getAbsolutePath() + "/");
+
         ucl = new URLClassLoader(urls);
-        res = ucl.findResources("RESOURCE.TXT");
+        res = ucl.findResources("test0");
         assertNotNull("Failed to locate resources", res);
 
         int i = 0;
         while (res.hasMoreElements()) {
-            StringBuffer sb = new StringBuffer();
-            InputStream is = ((URL) res.nextElement()).openStream();
-            int c;
-            while ((c = is.read()) != -1) {
-                sb.append((char) c);
-            }
+            StringBuffer sb = getResContent(res.nextElement());
             assertEquals("Returned incorrect resource/or in wrong order",
                     resValues[i++], sb.toString());
         }
-        assertTrue("Incorrect number of resources returned: " + i, i == 2);
+        assertEquals("Incorrect number of resources returned", 2, i);
     }
 
     /**
@@ -426,195 +451,49 @@
             return super.getPermissions(codesource);
         }
     }
-    
-    /**
-     * @throws ClassNotFoundException
-     * @throws IOException
-     * @tests java.net.URLClassLoader#findClass(java.lang.String)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "findClass",
-        args = {java.lang.String.class}
-    )
-    @BrokenTest("")
-    public void test_findClassLjava_lang_String()
-            throws ClassNotFoundException, IOException {
-        File resources = Support_Resources.createTempFolder();
-        String resPath = resources.toString();
-        if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\') {
-            resPath = resPath.substring(1);
-        }
-
-        java.net.URL[] urls = new java.net.URL[1];
-        java.net.URLClassLoader ucl = null;
-        boolean classFound;
-        boolean exception;
-        boolean goodException;
-        Enumeration en;
-        boolean resourcesFound;
-        Support_Resources.copyFile(resources, "JarIndex", "hyts_11.jar");
-        Support_Resources.copyFile(resources, "JarIndex", "hyts_12.jar");
-        Support_Resources.copyFile(resources, "JarIndex", "hyts_13.jar");
-        Support_Resources.copyFile(resources, "JarIndex", "hyts_14.jar");
-        urls[0] = new URL("file:/" + resPath + "/JarIndex/hyts_11.jar");
-        ucl = URLClassLoader.newInstance(urls, null);
-        URL resURL = ucl.findResource("Test.txt");
-        URL reference = new URL("jar:file:/" + resPath.replace('\\', '/')
-                + "/JarIndex/hyts_14.jar!/Test.txt");
-        assertTrue("Resource not found: " + resURL + " ref: " + reference,
-                resURL.equals(reference));
-
-        Class c = Class.forName("cpack.CNothing", true, ucl);
-        assertNotNull(c);
-
-        Support_Resources.copyFile(resources, "JarIndex", "hyts_21.jar");
-        Support_Resources.copyFile(resources, "JarIndex", "hyts_22.jar");
-        Support_Resources.copyFile(resources, "JarIndex", "hyts_23.jar");
-        urls[0] = new URL("file:/" + resPath + "/JarIndex/hyts_21.jar");
-        ucl = URLClassLoader.newInstance(urls, null);
-        en = ucl.findResources("bpack/");
-
-        try {
-            resourcesFound = true;
-            URL url1 = (URL) en.nextElement();
-            URL url2 = (URL) en.nextElement();
-            System.out.println(url1);
-            System.out.println(url2);
-            resourcesFound = resourcesFound
-                    && url1.equals(new URL("jar:file:/"
-                            + resPath.replace('\\', '/')
-                            + "/JarIndex/hyts_22.jar!/bpack/"));
-            resourcesFound = resourcesFound
-                    && url2.equals(new URL("jar:file:/"
-                            + resPath.replace('\\', '/')
-                            + "/JarIndex/hyts_23.jar!/bpack/"));
-            if (en.hasMoreElements()) {
-                resourcesFound = false;
-            }
-        } catch (NoSuchElementException e) {
-            resourcesFound = false;
-        }
-        assertTrue("Resources not found (1)", resourcesFound);
-
-        Class c2 = Class.forName("bpack.Homer", true, ucl);
-        assertNotNull(c2);
-
-        try {
-            Class.forName("bpack.Bart", true, ucl);
-            fail("InvalidJarIndexException should be thrown");
-        } catch (RuntimeException e) {
-            e.printStackTrace();
-            // expected
-        }
-
-        try {
-            Class.forName("Main4", true, ucl);
-            fail("ClassNotFoundException should be thrown");
-        } catch (ClassNotFoundException e) {
-            // Expected
-        }
-
-        Support_Resources.copyFile(resources, "JarIndex", "hyts_22-new.jar");
-        urls[0] = new URL("file:/" + resPath + "/JarIndex/hyts_22-new.jar");
-        ucl = URLClassLoader.newInstance(urls, null);
-        assertNotNull("Cannot find resource", ucl.findResource("cpack/"));
-        Support_Resources.copyFile(resources, "JarIndex", "hyts_11.jar");
-        urls[0] = new URL("file:/" + resPath + "/JarIndex/hyts_31.jar");
-        ucl = URLClassLoader.newInstance(urls, null);
-
-        try {
-            Class.forName("cpack.Mock", true, ucl);
-            fail("ClassNotFoundException should be thrown");
-        } catch (ClassNotFoundException e) {
-            // Expected
-        }
-
-        // testing circular reference
-        Support_Resources.copyFile(resources, "JarIndex", "hyts_41.jar");
-        Support_Resources.copyFile(resources, "JarIndex", "hyts_42.jar");
-        urls[0] = new URL("file:/" + resPath + "/JarIndex/hyts_41.jar");
-        ucl = URLClassLoader.newInstance(urls, null);
-        en = ucl.findResources("bpack/");
-        resourcesFound = resourcesFound
-                && ((URL) en.nextElement()).equals(new URL("jar:file:/"
-                        + resPath.replace('\\', '/')
-                        + "/JarIndex/hyts_42.jar!/bpack/"));
-        assertTrue("Resources not found (2)", resourcesFound);
-        assertFalse("No more resources expected", en.hasMoreElements());
-       
-        // Regression test for HARMONY-2357.
-        try {
-            URLClassLoaderExt cl = new URLClassLoaderExt(new URL[557]);
-            cl.findClass("0");
-            fail("NullPointerException should be thrown");
-        } catch (NullPointerException npe) {
-            // Expected
-        }
-
-        // Regression test for HARMONY-2871.
-        URLClassLoader cl = new URLClassLoader(new URL[] { new URL("file:/foo.jar") });
-
-        try {
-            Class.forName("foo.Foo", false, cl);
-        } catch (Exception ex) {
-            // Don't care
-        }
-
-        try {
-            Class.forName("foo.Foo", false, cl);
-            fail("NullPointerException should be thrown");
-        } catch (ClassNotFoundException cnfe) {
-            // Expected
-        }
-    }
 
     /**
      * @tests java.net.URLClassLoader#findResource(java.lang.String)
      */
     @TestTargetNew(
-        level = TestLevel.COMPLETE,
+        level = TestLevel.PARTIAL_COMPLETE,
         notes = "",
         method = "findResource",
         args = {java.lang.String.class}
     )
-    @BrokenTest("web address used from support doesn't work anymore")
-    public void test_findResourceLjava_lang_String()
-            throws MalformedURLException {
-        URL res = null;
+    @SideEffect("Support_TestWebServer requires isolation.")
+    public void test_findResourceLjava_lang_String() throws Exception {
+        int port = Support_PortManager.getNextPort();
+        File tmp = File.createTempFile("test", ".txt");
 
-        URL[] urls = new URL[2];
-        urls[0] = new URL("http://" + Support_Configuration.HomeAddress);
-        urls[1] = new URL(Support_Resources.getResourceURL("/"));
-        ucl = new URLClassLoader(urls);
-        res = ucl.findResource("RESOURCE.TXT");
-        assertNotNull("Failed to locate resource", res);
+        Support_TestWebServer server = new Support_TestWebServer();
+        try {    
 
-        StringBuffer sb = new StringBuffer();
-        try {
-            java.io.InputStream is = res.openStream();
-
-            int c;
-            while ((c = is.read()) != -1) {
-                sb.append((char) c);
-            }
-            is.close();
-        } catch (IOException e) {
+            server.initServer(port, tmp.getAbsolutePath(), "text/html");
+    
+            URL[] urls = { new URL("http://localhost:" + port + "/") };
+            ucl = new URLClassLoader(urls);
+            URL res = ucl.findResource("test1");
+            assertNotNull("Failed to locate resource", res);
+    
+            StringBuffer sb = getResContent(res);
+            assertEquals("Returned incorrect resource", new String(Support_TestWebData.test1),
+                    sb.toString());
+        } finally {
+            server.close();
         }
-        assertTrue("Returned incorrect resource", !sb.toString().equals(
-                "This is a test resource file"));
     }
     
     @TestTargets({
         @TestTargetNew(
-            level = TestLevel.COMPLETE,
+            level = TestLevel.PARTIAL,
             notes = "Checks getResource, indirectly checks findResource",
+            clazz = ClassLoader.class,
             method = "getResource",
             args = {java.lang.String.class}
         ),
         @TestTargetNew(
-            level = TestLevel.COMPLETE,
+            level = TestLevel.PARTIAL_COMPLETE,
             notes = "Checks getResource, indirectly checks findResource",
             method = "findResource",
             args = {java.lang.String.class}
@@ -681,39 +560,75 @@
      * Regression for Harmony-2237 
      */
     @TestTargetNew(
-        level = TestLevel.PARTIAL,
+        level = TestLevel.PARTIAL_COMPLETE,
         notes = "Regression test",
         method = "findResource",
         args = {java.lang.String.class}
     )
-    public void test_getResource() throws Exception {        
-        URLClassLoader urlLoader = getURLClassLoader();
-        assertNull(urlLoader.findResource("XXX")); //$NON-NLS-1$
+    @SideEffect("Support_TestWebServer requires isolation.")
+    public void test_findResource_String() throws Exception {
+        File tempFile1 = File.createTempFile("textFile", ".txt");
+        tempFile1.createNewFile();
+        tempFile1.deleteOnExit();
+        File tempFile2 = File.createTempFile("jarFile", ".jar");
+        tempFile2.delete();
+        tempFile2.deleteOnExit();
+
+        Support_TestWebServer server = new Support_TestWebServer();
+        int port = Support_PortManager.getNextPort();
+        try {
+            server.initServer(port, false);
+    
+            String tempPath1 = tempFile1.getParentFile().getAbsolutePath() + "/";
+            InputStream is = getClass().getResourceAsStream(
+                    "/tests/resources/hyts_patch.jar");
+            Support_Resources.copyLocalFileto(tempFile2, is);
+            String tempPath2 = tempFile2.getAbsolutePath();
+            String tempPath3 = "http://localhost:" + port + "/";
+            URLClassLoader urlLoader = getURLClassLoader(tempPath1, tempPath2);
+            assertNull("Found inexistant resource",
+                    urlLoader.findResource("XXX")); //$NON-NLS-1$
+            assertNotNull("Couldn't find resource from directory",
+                    urlLoader.findResource(tempFile1.getName())); //$NON-NLS-1$
+            assertNotNull("Couldn't find resource from jar",
+                    urlLoader.findResource("Blah.txt")); //$NON-NLS-1$
+            urlLoader = getURLClassLoader(tempPath1, tempPath2, tempPath3);
+            assertNotNull("Couldn't find resource from web",
+                    urlLoader.findResource("test1")); //$NON-NLS-1$
+            assertNull("Found inexistant resource from web",
+                    urlLoader.findResource("test3")); //$NON-NLS-1$
+        } finally {
+            server.close();
+        }
     }
 
-    private static URLClassLoader getURLClassLoader() {
-        String classPath = System.getProperty("java.class.path");
-        StringTokenizer tok = new StringTokenizer(classPath, File.pathSeparator);
-        Vector<URL> urlVec = new Vector<URL>();
-        String resPackage = Support_Resources.RESOURCE_PACKAGE;
-        try {
-            while (tok.hasMoreTokens()) {
-                String path = tok.nextToken();
-                String url;
-                if (new File(path).isDirectory())
-                    url = "file:" + path + resPackage + "subfolder/";
-                else
-                    url = "jar:file:" + path + "!" + resPackage + "subfolder/";
-                urlVec.addElement(new URL(url));
+    private static URLClassLoader getURLClassLoader(String... classPath)
+            throws MalformedURLException {
+        List<URL> urlList = new ArrayList<URL>();
+        for (String path : classPath) {
+            String url;
+            File f = new File(path);
+            if (f.isDirectory()) {
+                url = "file:" + path;
+            } else if (path.startsWith("http")) {
+                url = path;
+            } else {
+                url = "jar:file:" + path + "!/";
             }
-        } catch (MalformedURLException e) {
-            // do nothing
+            urlList.add(new URL(url));
         }
-        URL[] urls = new URL[urlVec.size()];
-        for (int i = 0; i < urlVec.size(); i++) {
-            urls[i] = urlVec.elementAt(i);
-        }            
-        URLClassLoader loader = new URLClassLoader(urls);
-        return loader;
+        return new URLClassLoader(urlList.toArray(new URL[urlList.size()]));
+    }
+
+    private StringBuffer getResContent(URL res) throws IOException {
+        StringBuffer sb = new StringBuffer();
+        InputStream is = res.openStream();
+   
+        int c;
+        while ((c = is.read()) != -1) {
+            sb.append((char) c);
+        }
+        is.close();
+        return sb;
     }
 }
diff --git a/libcore/luni/src/test/java/tests/api/java/util/CalendarTest.java b/libcore/luni/src/test/java/tests/api/java/util/CalendarTest.java
index 34f4f3d..c414f64 100644
--- a/libcore/luni/src/test/java/tests/api/java/util/CalendarTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/util/CalendarTest.java
@@ -17,6 +17,7 @@
 
 package tests.api.java.util;
 
+import dalvik.annotation.KnownFailure;
 import dalvik.annotation.TestTargetNew;
 import dalvik.annotation.TestTargets;
 import dalvik.annotation.TestLevel;
@@ -899,6 +900,7 @@
             args = {}
         )
     })
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_getFirstDayOfWeek() {
         Calendar cal = Calendar.getInstance();
 
@@ -915,6 +917,7 @@
         method = "getInstance",
         args = {java.util.Locale.class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_getInstanceLjava_util_Locale() {
         Calendar cal1 = Calendar.getInstance(Locale.FRANCE);
         Locale.setDefault(Locale.FRANCE);
@@ -931,7 +934,7 @@
         method = "getInstance",
         args = {java.util.TimeZone.class}
     )
-    public void testget_InstanceLjava_util_TimeZone() {
+    public void test_get_InstanceLjava_util_TimeZone() {
         Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("GMT-6"));
         Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("GMT+1"));
         assertNotSame(cal1.getTimeZone().getRawOffset(), cal2.getTimeZone().getRawOffset());
@@ -943,6 +946,7 @@
         method = "getInstance",
         args = {java.util.TimeZone.class, java.util.Locale.class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_getInstanceLjava_util_TimeZoneLjava_util_Locale() {
         Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("GMT-6"), Locale.FRANCE);
         Locale.setDefault(Locale.FRANCE);
@@ -961,6 +965,7 @@
         method = "getMinimalDaysInFirstWeek",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_getMinimalDaysInFirstWeek() {
         Calendar cal = Calendar.getInstance();
         assertTrue(cal.getMinimalDaysInFirstWeek()==1);
@@ -1006,6 +1011,7 @@
         method = "hashCode",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_hashCode() {
         Calendar cal1 = Calendar.getInstance();
         Locale.setDefault(Locale.FRANCE);
diff --git a/libcore/luni/src/test/java/tests/api/java/util/FormatterTest.java b/libcore/luni/src/test/java/tests/api/java/util/FormatterTest.java
index 1b8fda1..1d6a4bb 100644
--- a/libcore/luni/src/test/java/tests/api/java/util/FormatterTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/util/FormatterTest.java
@@ -267,7 +267,6 @@
         method = "Formatter",
         args = {java.lang.String.class}
     )
-    @KnownFailure("The Exception is not thrown on linux if the user is root")
     public void test_ConstructorLjava_lang_String() throws IOException {
         Formatter f = null;
         try {
@@ -314,7 +313,6 @@
         method = "Formatter",
         args = {java.lang.String.class, java.lang.String.class}
     )
-    @KnownFailure("The Exception is not thrown on linux if the user is root")
     public void test_ConstructorLjava_lang_StringLjava_lang_String()
             throws IOException {
         Formatter f = null;
@@ -376,7 +374,6 @@
         method = "Formatter",
         args = {java.lang.String.class, java.lang.String.class, java.util.Locale.class}
     )
-    @KnownFailure("The Exception is not thrown on linux if the user is root")
     public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_util_Locale()
             throws IOException {
         Formatter f = null;
@@ -448,7 +445,6 @@
         method = "Formatter",
         args = {java.io.File.class}
     )
-    @KnownFailure("The Exception is not thrown on linux if the user is root")
     public void test_ConstructorLjava_io_File() throws IOException {
         Formatter f = null;
         try {
@@ -495,7 +491,6 @@
         method = "Formatter",
         args = {java.io.File.class, java.lang.String.class}
     )
-    @KnownFailure("The Exception is not thrown on linux if the user is root")
     public void test_ConstructorLjava_io_FileLjava_lang_String()
             throws IOException {
         Formatter f = null;
@@ -569,7 +564,6 @@
         method = "Formatter",
         args = {java.io.File.class, java.lang.String.class, java.util.Locale.class}
     )
-    @KnownFailure("The Exception is not thrown on linux if the user is root")
     public void test_ConstructorLjava_io_FileLjava_lang_StringLjava_util_Locale()
             throws IOException {
         Formatter f = null;
@@ -1765,6 +1759,7 @@
         method = "format",
         args = {java.lang.String.class, java.lang.Object[].class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_formatLjava_lang_String$Ljava_lang_Object_ByteShortIntegerLongConversionD() {
         final Object[][] triple = { 
                 { 0,                "%d",                  "0" }, 
@@ -2029,6 +2024,7 @@
         args = {java.lang.String.class, java.lang.Object[].class}
     )
     @AndroidOnly("ICU data is different from RI data")
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_formatLjava_lang_String$Ljava_lang_Object_DateTimeConversion() {
         /*
          * Implementation note: For a millisecond date based on Long.MAX_VALUE,
@@ -2801,11 +2797,12 @@
      */
     @TestTargetNew(
         level = TestLevel.PARTIAL_COMPLETE,
-        notes = "Doesn't verify IllegalFormatException, FormatterClosedException.",
+        notes = "Flaky! results. differs if debugger is attached." +
+                "Unchecked IllegalFormatException, FormatterClosedException.",
         method = "format",
         args = {java.lang.String.class, java.lang.Object[].class}
     )
-    // Flaky! results. differs if debugger is attached.
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_formatLjava_lang_String$LBigInteger() {
         final Object[][] tripleD = {
                 {new BigInteger("123456789012345678901234567890"),          "%d",       "123456789012345678901234567890"}, //$NON-NLS-2$
@@ -2908,6 +2905,7 @@
         method = "format",
         args = {java.lang.String.class, java.lang.Object[].class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_formatLjava_lang_String$Ljava_lang_Object_BigIntegerPaddingConversion() {
         Formatter f = null;
 
@@ -4613,7 +4611,8 @@
         method = "format",
         args = {java.util.Locale.class, java.lang.String.class, java.lang.Object[].class}
     )
-    public void test_formatLjava_util_LocaleLjava_lang_StringLjava_lang_Object$() {
+    @KnownFailure("Some locales were removed last minute in cupcake")
+    public void test_formatLjava_util_LocaleLjava_lang_StringLjava_lang_Object() {
         Double val = new Double(3.14);
         Calendar cal = Calendar.getInstance();
         Formatter fLoc = null;
diff --git a/libcore/luni/src/test/java/tests/api/java/util/GregorianCalendarTest.java b/libcore/luni/src/test/java/tests/api/java/util/GregorianCalendarTest.java
index 6d2ef74..c5ccde1 100644
--- a/libcore/luni/src/test/java/tests/api/java/util/GregorianCalendarTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/util/GregorianCalendarTest.java
@@ -148,6 +148,7 @@
         method = "GregorianCalendar",
         args = {java.util.Locale.class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_ConstructorLjava_util_Locale() {
         // Test for method java.util.GregorianCalendar(java.util.Locale)
         Date date = new Date();
diff --git a/libcore/luni/src/test/java/tests/api/java/util/LocaleTest.java b/libcore/luni/src/test/java/tests/api/java/util/LocaleTest.java
index 82f1145..d45c5be 100644
--- a/libcore/luni/src/test/java/tests/api/java/util/LocaleTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/util/LocaleTest.java
@@ -17,6 +17,7 @@
 
 package tests.api.java.util;
 
+import dalvik.annotation.KnownFailure;
 import dalvik.annotation.TestTargetNew;
 import dalvik.annotation.TestTargets;
 import dalvik.annotation.TestLevel;
@@ -257,6 +258,7 @@
         method = "getDisplayCountry",
         args = {java.util.Locale.class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_getDisplayCountryLjava_util_Locale() {
         // Test for method java.lang.String
         // java.util.Locale.getDisplayCountry(java.util.Locale)
@@ -294,6 +296,7 @@
         method = "getDisplayLanguage",
         args = {java.util.Locale.class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_getDisplayLanguageLjava_util_Locale() {
         // Test for method java.lang.String
         // java.util.Locale.getDisplayLanguage(java.util.Locale)
@@ -326,6 +329,7 @@
         method = "getDisplayName",
         args = {java.util.Locale.class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_getDisplayNameLjava_util_Locale() {
         // Test for method java.lang.String
         // java.util.Locale.getDisplayName(java.util.Locale)
diff --git a/libcore/luni/src/test/java/tests/api/java/util/ScannerTest.java b/libcore/luni/src/test/java/tests/api/java/util/ScannerTest.java
index fe7a4cf..84f41d6 100644
--- a/libcore/luni/src/test/java/tests/api/java/util/ScannerTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/util/ScannerTest.java
@@ -1120,6 +1120,7 @@
         method = "nextInt",
         args = {int.class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_nextIntI() throws IOException {
         s = new Scanner("123 456");
         assertEquals(123, s.nextInt(10));
@@ -1334,6 +1335,7 @@
         method = "nextInt",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_nextInt() throws IOException {
         s = new Scanner("123 456");
         assertEquals(123, s.nextInt());
@@ -1728,6 +1730,7 @@
         method = "nextFloat",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_nextFloat() throws IOException {
         s = new Scanner("123 45\u0666. 123.4 .123 ");
         s.useLocale(Locale.ENGLISH);
@@ -2143,6 +2146,7 @@
         method = "nextShort",
         args = {int.class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_nextShortI() throws IOException {
         s = new Scanner("123 456");
         assertEquals(123, s.nextShort(10));
@@ -2300,6 +2304,7 @@
         method = "nextShort",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_nextShort() throws IOException {
         s = new Scanner("123 456");
         assertEquals(123, s.nextShort());
@@ -2460,6 +2465,7 @@
         method = "nextLong",
         args = {int.class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_nextLongI() throws IOException {
         s = new Scanner("123 456");
         assertEquals(123, s.nextLong(10));
@@ -2617,6 +2623,7 @@
         method = "nextLong",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_nextLong() throws IOException {
         s = new Scanner("123 456");
         assertEquals(123, s.nextLong());
@@ -3713,6 +3720,7 @@
         method = "hasNextInt",
         args = {int.class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_hasNextIntI() throws IOException {
         s = new Scanner("123 456");
         assertEquals(123, s.nextInt(10));
@@ -3945,6 +3953,7 @@
         method = "hasNextInt",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_hasNextInt() throws IOException {
         s = new Scanner("123 456");
         assertTrue(s.hasNextInt());
@@ -4132,6 +4141,7 @@
         method = "hasNextFloat",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_hasNextFloat() throws IOException {
         s = new Scanner("123 45\u0666. 123.4 .123 ");
         s.useLocale(Locale.ENGLISH);
@@ -4277,6 +4287,7 @@
         method = "hasNextShort",
         args = {int.class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_hasNextShortI() throws IOException {
         s = new Scanner("123 456");
         assertTrue(s.hasNextShort(10));
@@ -4453,6 +4464,7 @@
         method = "hasNextShort",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_hasNextShort() throws IOException {
         s = new Scanner("123 456");
         assertTrue(s.hasNextShort());
@@ -4680,6 +4692,7 @@
         method = "hasNextLong",
         args = {int.class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_hasNextLongI() throws IOException {
         s = new Scanner("123 456");
         assertTrue(s.hasNextLong(10));
@@ -4897,6 +4910,7 @@
         method = "hasNextLong",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_hasNextLong() throws IOException {
         s = new Scanner("123 456");
         assertTrue(s.hasNextLong());
@@ -5083,6 +5097,7 @@
         method = "hasNextDouble",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_hasNextDouble() throws IOException {
         s = new Scanner("123 45\u0666. 123.4 .123 ");
         s.useLocale(Locale.ENGLISH);
@@ -5196,6 +5211,7 @@
         method = "hasNextBigDecimal",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_hasNextBigDecimal() throws IOException {
         s = new Scanner("123 45\u0666. 123.4 .123 ");
         s.useLocale(Locale.ENGLISH);
@@ -6328,6 +6344,7 @@
         method = "nextDouble",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_nextDouble() throws IOException {
         s = new Scanner("123 45\u0666. 123.4 .123 ");
         s.useLocale(Locale.ENGLISH);
@@ -6420,6 +6437,7 @@
         method = "nextBigDecimal",
         args = {}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_nextBigDecimal() throws IOException {
         s = new Scanner("123 45\u0666. 123.4 .123 ");
         s.useLocale(Locale.ENGLISH);
diff --git a/libcore/luni/src/test/java/tests/api/java/util/TimeZoneTest.java b/libcore/luni/src/test/java/tests/api/java/util/TimeZoneTest.java
index 4637f10..891e9b8 100644
--- a/libcore/luni/src/test/java/tests/api/java/util/TimeZoneTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/util/TimeZoneTest.java
@@ -304,6 +304,7 @@
         method = "getDisplayName",
         args = {java.util.Locale.class}
     )
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_getDisplayNameLjava_util_Locale() {
         TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
         assertEquals("Pacific Standard Time", tz.getDisplayName(new Locale("US")));
@@ -330,6 +331,7 @@
         args = {boolean.class, int.class, java.util.Locale.class}
     )
     @AndroidOnly("fail on RI. See comment below")
+    @KnownFailure("Some locales were removed last minute in cupcake")
     public void test_getDisplayNameZILjava_util_Locale() {
         TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
         assertEquals("PST",                   tz.getDisplayName(false, 0, Locale.US));
diff --git a/libcore/support/src/test/java/tests/support/Support_HttpConstants.java b/libcore/support/src/test/java/tests/support/Support_HttpConstants.java
new file mode 100644
index 0000000..e99bdc1
--- /dev/null
+++ b/libcore/support/src/test/java/tests/support/Support_HttpConstants.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.support;
+
+interface Support_HttpConstants {
+    /** 2XX: generally "OK" */
+    public static final int HTTP_OK = 200;
+    public static final int HTTP_CREATED = 201;
+    public static final int HTTP_ACCEPTED = 202;
+    public static final int HTTP_NOT_AUTHORITATIVE = 203;
+    public static final int HTTP_NO_CONTENT = 204;
+    public static final int HTTP_RESET = 205;
+    public static final int HTTP_PARTIAL = 206;
+
+    /** 3XX: relocation/redirect */
+    public static final int HTTP_MULT_CHOICE = 300;
+    public static final int HTTP_MOVED_PERM = 301;
+    public static final int HTTP_MOVED_TEMP = 302;
+    public static final int HTTP_SEE_OTHER = 303;
+    public static final int HTTP_NOT_MODIFIED = 304;
+    public static final int HTTP_USE_PROXY = 305;
+
+    /** 4XX: client error */
+    public static final int HTTP_BAD_REQUEST = 400;
+    public static final int HTTP_UNAUTHORIZED = 401;
+    public static final int HTTP_PAYMENT_REQUIRED = 402;
+    public static final int HTTP_FORBIDDEN = 403;
+    public static final int HTTP_NOT_FOUND = 404;
+    public static final int HTTP_BAD_METHOD = 405;
+    public static final int HTTP_NOT_ACCEPTABLE = 406;
+    public static final int HTTP_PROXY_AUTH = 407;
+    public static final int HTTP_CLIENT_TIMEOUT = 408;
+    public static final int HTTP_CONFLICT = 409;
+    public static final int HTTP_GONE = 410;
+    public static final int HTTP_LENGTH_REQUIRED = 411;
+    public static final int HTTP_PRECON_FAILED = 412;
+    public static final int HTTP_ENTITY_TOO_LARGE = 413;
+    public static final int HTTP_REQ_TOO_LONG = 414;
+    public static final int HTTP_UNSUPPORTED_TYPE = 415;
+
+    /** 5XX: server error */
+    public static final int HTTP_SERVER_ERROR = 500;
+    public static final int HTTP_INTERNAL_ERROR = 501;
+    public static final int HTTP_BAD_GATEWAY = 502;
+    public static final int HTTP_UNAVAILABLE = 503;
+    public static final int HTTP_GATEWAY_TIMEOUT = 504;
+    public static final int HTTP_VERSION = 505;
+
+    /** Method IDs */
+    public static final int UNKNOWN_METHOD = 0;
+    public static final int GET_METHOD = 1;
+    public static final int HEAD_METHOD = 2;
+    public static final int POST_METHOD = 3;
+
+    public static final String[] requestHeaders = {
+        "cache-control",
+        "connection",
+        "date",
+        "pragma",
+        "trailer",
+        "transfer-encoding",
+        "upgrade",
+        "via",
+        "warning",
+        "accept",
+        "accept-charset",
+        "accept-encoding",
+        "accept-language",
+        "authorization",
+        "expect",
+        "from",
+        "host",
+        "if-match",
+        "if-modified-since",
+        "if-none-match",
+        "if-range",
+        "if-unmodified-since",
+        "max-forwards",
+        "proxy-authentication",
+        "range",
+        "referer",
+        "te",
+        "user-agent",
+        "keep-alive",
+        "allow",
+        "content-encoding",
+        "content-language",
+        "content-length",
+        "content-location",
+        "content-md5",
+        "content-range",
+        "content-type",
+        "expires",
+        "last-modified",
+        "location",
+        "server"
+
+    };
+
+    public static final int REQ_UNKNOWN = -1;
+    public static final int REQ_CACHE_CONTROL = 0;
+    public static final int REQ_CONNECTION = 1;
+    public static final int REQ_DATE = 2;
+    public static final int REQ_PRAGMA = 3;
+    public static final int REQ_TRAILER = 4;
+    public static final int REQ_TRANSFER_ENCODING = 5;
+    public static final int REQ_UPGRADE = 6;
+    public static final int REQ_VIA = 7;
+    public static final int REQ_WARNING = 8;
+    public static final int REQ_ACCEPT = 9;
+    public static final int REQ_ACCEPT_CHARSET = 10;
+    public static final int REQ_ACCEPT_ENCODING = 11;
+    public static final int REQ_ACCEPT_LANGUAGE = 12;
+    public static final int REQ_AUTHORIZATION = 13;
+    public static final int REQ_EXPECT = 14;
+    public static final int REQ_FROM = 15;
+    public static final int REQ_HOST = 16;
+    public static final int REQ_IF_MATCH = 17;
+    public static final int REQ_IF_MODIFIED_SINCE = 18;
+    public static final int REQ_IF_NONE_MATCH = 19;
+    public static final int REQ_IF_RANGE = 20;
+    public static final int REQ_IF_UNMODIFIED_SINCE = 21;
+    public static final int REQ_MAX_FORWARDS = 22;
+    public static final int REQ_PROXY_AUTHENTICATION = 23;
+    public static final int REQ_RANGE = 24;
+    public static final int REQ_REFERER = 25;
+    public static final int REQ_TE = 26;
+    public static final int REQ_USER_AGENT = 27;
+    public static final int REQ_KEEP_ALIVE = 28;
+    public static final int REQ_ALLOW = 29;
+    public static final int REQ_CONTENT_ENCODING = 30;
+    public static final int REQ_CONTENT_LANGUAGE = 31;
+    public static final int REQ_CONTENT_LENGTH = 32;
+    public static final int REQ_CONTENT_LOCATION = 33;
+    public static final int REQ_CONTENT_MD5 = 34;
+    public static final int REQ_CONTENT_RANGE = 35;
+    public static final int REQ_CONTENT_TYPE = 36;
+    public static final int REQ_EXPIRES = 37;
+    public static final int REQ_LAST_MODIFIED = 38;
+    public static final int REQ_LOCATION = 39;
+    public static final int REQ_SERVER = 40;
+
+}
diff --git a/libcore/support/src/test/java/tests/support/Support_TestWebData.java b/libcore/support/src/test/java/tests/support/Support_TestWebData.java
new file mode 100644
index 0000000..6f414ea
--- /dev/null
+++ b/libcore/support/src/test/java/tests/support/Support_TestWebData.java
@@ -0,0 +1,197 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.support;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Date;
+
+/**
+ * Represents test data used by the Request API tests
+ */
+public class Support_TestWebData {
+
+  /*
+   * Simple Html body
+   * <html>
+   * <body>
+   * <h1>Hello World!</h1>
+   * </body>
+   * </html>
+   */
+  public final static byte[] test1 = {
+    (byte)0x3c, (byte)0x68, (byte)0x74, (byte)0x6d,
+    (byte)0x6c, (byte)0x3e, (byte)0x0a, (byte)0x3c,
+    (byte)0x62, (byte)0x6f, (byte)0x64, (byte)0x79,
+    (byte)0x3e, (byte)0x0a, (byte)0x3c, (byte)0x68,
+    (byte)0x31, (byte)0x3e, (byte)0x48, (byte)0x65,
+    (byte)0x6c, (byte)0x6c, (byte)0x6f, (byte)0x20,
+    (byte)0x57, (byte)0x6f, (byte)0x72, (byte)0x6c,
+    (byte)0x64, (byte)0x21, (byte)0x3c, (byte)0x2f,
+    (byte)0x68, (byte)0x31, (byte)0x3e, (byte)0x0a,
+    (byte)0x3c, (byte)0x2f, (byte)0x62, (byte)0x6f,
+    (byte)0x64, (byte)0x79, (byte)0x3e, (byte)0x0a,
+    (byte)0x3c, (byte)0x2f, (byte)0x68, (byte)0x74,
+    (byte)0x6d, (byte)0x6c, (byte)0x3e, (byte)0x0a
+  };
+
+  /*
+   * Simple Html body
+   * <html>
+   * <body>
+   * <h1>Hello World!</h1>
+   * </body>
+   * </html>
+   */
+  public final static byte[] test2 = {
+    (byte)0x3c, (byte)0x68, (byte)0x74, (byte)0x6d,
+    (byte)0x6c, (byte)0x3e, (byte)0x0a, (byte)0x3c,
+    (byte)0x62, (byte)0x6f, (byte)0x64, (byte)0x79,
+    (byte)0x3e, (byte)0x0a, (byte)0x3c, (byte)0x68,
+    (byte)0x31, (byte)0x3e, (byte)0x48, (byte)0x65,
+    (byte)0x6c, (byte)0x6c, (byte)0x6f, (byte)0x20,
+    (byte)0x57, (byte)0x6f, (byte)0x72, (byte)0x6c,
+    (byte)0x64, (byte)0x21, (byte)0x3c, (byte)0x2f,
+    (byte)0x68, (byte)0x31, (byte)0x3e, (byte)0x0a,
+    (byte)0x3c, (byte)0x2f, (byte)0x62, (byte)0x6f,
+    (byte)0x64, (byte)0x79, (byte)0x3e, (byte)0x0a,
+    (byte)0x3c, (byte)0x2f, (byte)0x68, (byte)0x74,
+    (byte)0x6d, (byte)0x6c, (byte)0x3e, (byte)0x0a
+  };
+
+  // string for test request post body
+  public final static String postContent = "user=111";
+  
+  // Array of all test data
+  public final static byte[][] tests = {
+    test1,
+    test2
+  };
+
+  /**
+   * List of static test cases for use with test server
+   */
+  public static Support_TestWebData[] testParams = {
+    new Support_TestWebData(52, 14000000, "test1", "text/html", false, 0),
+    new Support_TestWebData(52, 14000002, "test2", "unknown/unknown", false,
+            new Date().getTime() + 100000)
+  };
+
+  /**
+   * List of response strings for use by the test server
+   */
+  public static String[] testServerResponse = {
+    "Redirecting 301",
+    "Redirecting 302",
+    "Redirecting 303",
+    "Redirecting 307"
+  };
+
+  // Redirection indices into testServerResponse
+  public final static int REDIRECT_301 = 0;
+  public final static int REDIRECT_302 = 1;
+  public final static int REDIRECT_303 = 2;
+  public final static int REDIRECT_307 = 3;
+
+  /**
+   * Creates a data package with information used by the server when responding
+   * to requests
+   */
+  Support_TestWebData(int length, int lastModified, String name, String type, boolean isDir, long expDate) {
+    testLength = length;
+    testLastModified = lastModified;
+    testName = name;
+    testType = type;
+    testDir = isDir;
+    testExp = expDate;
+  }
+
+  /**
+   * Creates a data package with information used by the server when responding
+   * to requests
+   */
+  private Support_TestWebData(String path, String type) {
+    File file = new File(path);
+    testLength = file.length();
+    testLastModified = file.lastModified();
+    testName = file.getName();
+    testType = type;
+    testDir = file.isDirectory();
+    ByteArrayOutputStream out = new ByteArrayOutputStream();
+    FileInputStream in = null;
+    try {
+        in = new FileInputStream(file);
+        while (in.available() > 0) {
+            out.write(in.read());
+        }
+        in.close();
+        out.flush();
+        test0Data = out.toByteArray();
+        out.close();
+        test0DataAvailable = true;
+        return;
+    } catch (Exception e) {
+        // ignore
+        e.printStackTrace();
+    } finally {
+        try {
+            if (in != null) {
+                in.close();
+            }
+            if (out != null) {
+                out.close();
+            }
+        } catch (IOException e) {
+            // ignore
+        }
+    }
+  }
+
+  public static void initDynamicTestWebData(String path, String type) {
+      test0Params = new Support_TestWebData(path, type);
+  }
+
+  // Length of test entity body
+  public long testLength;
+
+  // Last modified date value (milliseconds)
+  public long testLastModified;
+
+  // Test identification name
+  public String testName;
+
+  // The MIME type to assume for this test
+  public String testType;
+
+  // The expiration date
+  public long testExp;
+
+  // Indicates if this is a directory or not
+  public boolean testDir;
+
+  // Indicate if test0 data has bin initialized
+  public static boolean test0DataAvailable = false;
+
+  // test0 data
+  public static byte[] test0Data;
+
+  // test0 parameters
+  public static Support_TestWebData test0Params;
+}
diff --git a/libcore/support/src/test/java/tests/support/Support_TestWebServer.java b/libcore/support/src/test/java/tests/support/Support_TestWebServer.java
new file mode 100644
index 0000000..8ee7248
--- /dev/null
+++ b/libcore/support/src/test/java/tests/support/Support_TestWebServer.java
@@ -0,0 +1,942 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.support;
+
+import java.io.*;
+import java.lang.Thread;
+import java.net.*;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.*;
+import java.util.logging.Logger;
+
+/**
+ * TestWebServer is a simulated controllable test server that
+ * can respond to requests from HTTP clients.
+ *
+ * The server can be controlled to change how it reacts to any
+ * requests, and can be told to simulate various events (such as
+ * network failure) that would happen in a real environment.
+ */
+public class Support_TestWebServer implements Support_HttpConstants {
+
+    /* static class data/methods */
+
+    /* The ANDROID_LOG_TAG */
+    private final static String LOGTAG = "httpsv";
+
+    /* Where worker threads stand idle */
+    Vector threads = new Vector();
+
+    /* List of all active worker threads */
+    Vector activeThreads = new Vector();
+
+    /* timeout on client connections */
+    int timeout = 0;
+
+    /* max # worker threads */
+    int workers = 5;
+
+    /* Default port for this server to listen on */
+    final static int DEFAULT_PORT = 8080;
+
+    /* Default socket timeout value */
+    final static int DEFAULT_TIMEOUT = 5000;
+
+    /* Version string (configurable) */
+    protected String HTTP_VERSION_STRING = "HTTP/1.1";
+
+    /* Indicator for whether this server is configured as a HTTP/1.1
+     * or HTTP/1.0 server
+     */
+    private boolean http11 = true;
+
+    /* The thread handling new requests from clients */
+    private AcceptThread acceptT;
+
+    /* timeout on client connections */
+    int mTimeout;
+
+    /* Server port */
+    int mPort;
+
+    /* Switch on/off logging */
+    boolean mLog = false;
+
+    /* If set, this will keep connections alive after a request has been
+     * processed.
+     */
+    boolean keepAlive = true;
+
+    /* If set, this will cause response data to be sent in 'chunked' format */
+    boolean chunked = false;
+
+    /* If set, this will indicate a new redirection host */
+    String redirectHost = null;
+
+    /* If set, this indicates the reason for redirection */
+    int redirectCode = -1;
+
+    /* Set the number of connections the server will accept before shutdown */
+    int acceptLimit = 100;
+
+    /* Count of number of accepted connections */
+    int acceptedConnections = 0;
+
+    public Support_TestWebServer() {
+    }
+
+    /**
+     * Initialize a new server with default port and timeout.
+     * @param log Set true if you want trace output
+     */
+    public void initServer(boolean log) throws Exception {
+        initServer(DEFAULT_PORT, DEFAULT_TIMEOUT, log);
+    }
+
+    /**
+     * Initialize a new server with default timeout.
+     * @param port Sets the server to listen on this port
+     * @param log Set true if you want trace output
+     */
+    public void initServer(int port, boolean log) throws Exception {
+        initServer(port, DEFAULT_TIMEOUT, log);
+    }
+
+    /**
+     * Initialize a new server with default timeout and disabled log.
+     * @param port Sets the server to listen on this port
+     * @param servePath the path to the dynamic web test data
+     * @param contentType the type of the dynamic web test data
+     */
+    public void initServer(int port, String servePath, String contentType)
+            throws Exception {
+        Support_TestWebData.initDynamicTestWebData(servePath, contentType);
+        initServer(port, DEFAULT_TIMEOUT, false);
+    }
+
+    /**
+     * Initialize a new server with default port and timeout.
+     * @param port Sets the server to listen on this port
+     * @param timeout Indicates the period of time to wait until a socket is
+     *                closed
+     * @param log Set true if you want trace output
+     */
+    public void initServer(int port, int timeout, boolean log) throws Exception {
+        mPort = port;
+        mTimeout = timeout;
+        mLog = log;
+        keepAlive = true;
+
+        if (acceptT == null) {
+            acceptT = new AcceptThread();
+            acceptT.init();
+            acceptT.start();
+        }
+    }
+
+    /**
+     * Print to the log file (if logging enabled)
+     * @param s String to send to the log
+     */
+    protected void log(String s) {
+        if (mLog) {
+            Logger.global.fine(s);
+        }
+    }
+
+    /**
+     * Set the server to be an HTTP/1.0 or HTTP/1.1 server.
+     * This should be called prior to any requests being sent
+     * to the server.
+     * @param set True for the server to be HTTP/1.1, false for HTTP/1.0
+     */
+    public void setHttpVersion11(boolean set) {
+        http11 = set;
+        if (set) {
+            HTTP_VERSION_STRING = "HTTP/1.1";
+        } else {
+            HTTP_VERSION_STRING = "HTTP/1.0";
+        }
+    }
+
+    /**
+     * Call this to determine whether server connection should remain open
+     * @param value Set true to keep connections open after a request
+     *              completes
+     */
+    public void setKeepAlive(boolean value) {
+        keepAlive = value;
+    }
+
+    /**
+     * Call this to indicate whether chunked data should be used
+     * @param value Set true to make server respond with chunk encoded
+     *              content data.
+     */
+    public void setChunked(boolean value) {
+        chunked = value;
+    }
+
+    /**
+     * Call this to specify the maximum number of sockets to accept
+     * @param limit The number of sockets to accept
+     */
+    public void setAcceptLimit(int limit) {
+        acceptLimit = limit;
+    }
+
+    /**
+     * Call this to indicate redirection port requirement.
+     * When this value is set, the server will respond to a request with
+     * a redirect code with the Location response header set to the value
+     * specified.
+     * @param redirect The location to be redirected to
+     * @param redirectCode The code to send when redirecting
+     */
+    public void setRedirect(String redirect, int code) {
+        redirectHost = redirect;
+        redirectCode = code;
+        log("Server will redirect output to "+redirect+" code "+code);
+    }
+
+    /**
+     * Cause the thread accepting connections on the server socket to close
+     */
+    public void close() {
+        /* Stop the Accept thread */
+        if (acceptT != null) {
+            log("Closing AcceptThread"+acceptT);
+            acceptT.close();
+            acceptT = null;
+        }
+    }
+    /**
+     * The AcceptThread is responsible for initiating worker threads
+     * to handle incoming requests from clients.
+     */
+    class AcceptThread extends Thread {
+
+        ServerSocket ss = null;
+        boolean running = false;
+
+        public void init() {
+            // Networking code doesn't support ServerSocket(port) yet
+            InetSocketAddress ia = new InetSocketAddress(mPort);
+            while (true) {
+                try {
+                    ss = new ServerSocket();
+                    // Socket timeout functionality is not available yet
+                    //ss.setSoTimeout(5000);
+                    ss.setReuseAddress(true);
+                    ss.bind(ia);
+                    break;
+                } catch (IOException e) {
+                    log("IOException in AcceptThread.init()");                    
+                    // wait and retry
+                    try {
+                        Thread.sleep(1000);
+                    } catch (InterruptedException e1) {
+                        e1.printStackTrace();
+                    }
+                }
+            }
+        }
+
+        /**
+         * Main thread responding to new connections
+         */
+        public synchronized void run() {
+            running = true;
+            try {
+                while (running) {
+                    // Log.d(LOGTAG, "TestWebServer run() calling accept()");
+                    Socket s = ss.accept();
+                    acceptedConnections++;
+                    if (acceptedConnections >= acceptLimit) {
+                        running = false;
+                    }
+
+                    Worker w = null;
+                    synchronized (threads) {
+                        if (threads.isEmpty()) {
+                            Worker ws = new Worker();
+                            ws.setSocket(s);
+                            activeThreads.addElement(ws);
+                            (new Thread(ws, "additional worker")).start();
+                        } else {
+                            w = (Worker) threads.elementAt(0);
+                            threads.removeElementAt(0);
+                            w.setSocket(s);
+                        }
+                    }
+                }
+            } catch (SocketException e) {
+                log("SocketException in AcceptThread: probably closed during accept");
+                running = false;
+            } catch (IOException e) {
+                log("IOException in AcceptThread");
+                running = false;
+            }
+            log("AcceptThread terminated" + this);
+        }
+
+        // Close this socket
+        public void close() {
+            try {
+                running = false;
+                /* Stop server socket from processing further. Currently
+                   this does not cause the SocketException from ss.accept
+                   therefore the acceptLimit functionality has been added
+                   to circumvent this limitation */
+                ss.close();
+
+                // Stop worker threads from continuing
+                for (Enumeration e = activeThreads.elements(); e.hasMoreElements();) {
+                    Worker w = (Worker)e.nextElement();
+                    w.close();
+                }
+                activeThreads.clear();
+
+            } catch (IOException e) {
+                /* We are shutting down the server, so we expect
+                 * things to die. Don't propagate.
+                 */
+                log("IOException caught by server socket close");
+            }
+        }
+    }
+
+    // Size of buffer for reading from the connection
+    final static int BUF_SIZE = 2048;
+
+    /* End of line byte sequence */
+    static final byte[] EOL = {(byte)'\r', (byte)'\n' };
+
+    /**
+     * The worker thread handles all interactions with a current open
+     * connection. If pipelining is turned on, this will allow this
+     * thread to continuously operate on numerous requests before the
+     * connection is closed.
+     */
+    class Worker implements Support_HttpConstants, Runnable {
+
+        /* buffer to use to hold request data */
+        byte[] buf;
+
+        /* Socket to client we're handling */
+        private Socket s;
+
+        /* Reference to current request method ID */
+        private int requestMethod;
+
+        /* Reference to current requests test file/data */
+        private String testID;
+
+        /* Reference to test number from testID */
+        private int testNum;
+
+        /* Reference to whether new request has been initiated yet */
+        private boolean readStarted;
+
+        /* Indicates whether current request has any data content */
+        private boolean hasContent = false;
+
+        boolean running = false;
+
+        /* Request headers are stored here */
+        private Hashtable<String, String> headers = new Hashtable<String, String>();
+
+        /* Create a new worker thread */
+        Worker() {
+            buf = new byte[BUF_SIZE];
+            s = null;
+        }
+
+        /**
+         * Called by the AcceptThread to unblock this Worker to process
+         * a request.
+         * @param s The socket on which the connection has been made
+         */
+        synchronized void setSocket(Socket s) {
+            this.s = s;
+            notify();
+        }
+
+        /**
+         * Called by the accept thread when it's closing. Potentially unblocks
+         * the worker thread to terminate properly
+         */
+        synchronized void close() {
+            running = false;
+            notify();
+        }
+
+        /**
+         * Main worker thread. This will wait until a request has
+         * been identified by the accept thread upon which it will
+         * service the thread.
+         */
+        public synchronized void run() {
+            running = true;
+            while(running) {
+                if (s == null) {
+                    /* nothing to do */
+                    try {
+                        log(this+" Moving to wait state");
+                        wait();
+                    } catch (InterruptedException e) {
+                        /* should not happen */
+                        continue;
+                    }
+                    if (!running) break;
+                }
+                try {
+                    handleClient();
+                } catch (Exception e) {
+                    log("Exception during handleClient in the TestWebServer: "
+                            + e.getMessage());
+                }
+                /* go back in wait queue if there's fewer
+                 * than numHandler connections.
+                 */
+                s = null;
+                Vector pool = threads;
+                synchronized (pool) {
+                    if (pool.size() >= workers) {
+                        /* too many threads, exit this one */
+                        activeThreads.remove(this);
+                        return;
+                    } else {
+                        pool.addElement(this);
+                    }
+                }
+            }
+            log(this+" terminated");
+        }
+
+        /**
+         * Zero out the buffer from last time
+         */
+        private void clearBuffer() {
+            for (int i = 0; i < BUF_SIZE; i++) {
+                buf[i] = 0;
+            }
+        }
+
+        /**
+         * Utility method to read a line of data from the input stream
+         * @param is Inputstream to read
+         * @return number of bytes read
+         */
+        private int readOneLine(InputStream is) {
+
+            int read = 0;
+
+            clearBuffer();
+            try {
+                log("Reading one line: started ="+readStarted+" avail="+is.available());
+                StringBuilder log = new StringBuilder();
+                while ((!readStarted) || (is.available() > 0)) {
+                    int data = is.read();
+                    // We shouldn't get EOF but we need tdo check
+                    if (data == -1) {
+                        log("EOF returned");
+                        return -1;
+                    }
+
+                    buf[read] = (byte)data;
+
+                    log.append((char)data);
+
+                    readStarted = true;
+                    if (buf[read++]==(byte)'\n') {
+                        log(log.toString());
+                        return read;
+                    }
+                }
+            } catch (IOException e) {
+                log("IOException from readOneLine");
+            }
+            return read;
+        }
+
+        /**
+         * Read a chunk of data
+         * @param is Stream from which to read data
+         * @param length Amount of data to read
+         * @return number of bytes read
+         */
+        private int readData(InputStream is, int length) {
+            int read = 0;
+            int count;
+            // At the moment we're only expecting small data amounts
+            byte[] buf = new byte[length];
+
+            try {
+                while (is.available() > 0) {
+                    count = is.read(buf, read, length-read);
+                    read += count;
+                }
+            } catch (IOException e) {
+                log("IOException from readData");
+            }
+            return read;
+        }
+
+        /**
+         * Read the status line from the input stream extracting method
+         * information.
+         * @param is Inputstream to read
+         * @return number of bytes read
+         */
+        private int parseStatusLine(InputStream is) {
+            int index;
+            int nread = 0;
+
+            log("Parse status line");
+            // Check for status line first
+            nread = readOneLine(is);
+            // Bomb out if stream closes prematurely
+            if (nread == -1) {
+                requestMethod = UNKNOWN_METHOD;
+                return -1;
+            }
+
+            if (buf[0] == (byte)'G' &&
+                buf[1] == (byte)'E' &&
+                buf[2] == (byte)'T' &&
+                buf[3] == (byte)' ') {
+                requestMethod = GET_METHOD;
+                log("GET request");
+                index = 4;
+            } else if (buf[0] == (byte)'H' &&
+                       buf[1] == (byte)'E' &&
+                       buf[2] == (byte)'A' &&
+                       buf[3] == (byte)'D' &&
+                       buf[4] == (byte)' ') {
+                requestMethod = HEAD_METHOD;
+                log("HEAD request");
+                index = 5;
+            } else if (buf[0] == (byte)'P' &&
+                       buf[1] == (byte)'O' &&
+                       buf[2] == (byte)'S' &&
+                       buf[3] == (byte)'T' &&
+                       buf[4] == (byte)' ') {
+                requestMethod = POST_METHOD;
+                log("POST request");
+                index = 5;
+            } else {
+                // Unhandled request
+                requestMethod = UNKNOWN_METHOD;
+                return -1;
+            }
+
+            // A valid method we understand
+            if (requestMethod > UNKNOWN_METHOD) {
+                // Read file name
+                int i = index;
+                while (buf[i] != (byte)' ') {
+                    // There should be HTTP/1.x at the end
+                    if ((buf[i] == (byte)'\n') || (buf[i] == (byte)'\r')) {
+                        requestMethod = UNKNOWN_METHOD;
+                        return -1;
+                    }
+                    i++;
+                }
+
+                testID = new String(buf, 0, index, i-index);
+                if (testID.startsWith("/")) {
+                    testID = testID.substring(1);
+                }
+
+                return nread;
+            }
+            return -1;
+        }
+
+        /**
+         * Read a header from the input stream
+         * @param is Inputstream to read
+         * @return number of bytes read
+         */
+        private int parseHeader(InputStream is) {
+            int index = 0;
+            int nread = 0;
+            log("Parse a header");
+            // Check for status line first
+            nread = readOneLine(is);
+            // Bomb out if stream closes prematurely
+            if (nread == -1) {
+                requestMethod = UNKNOWN_METHOD;
+                return -1;
+            }
+            // Read header entry 'Header: data'
+            int i = index;
+            while (buf[i] != (byte)':') {
+                // There should be an entry after the header
+
+                if ((buf[i] == (byte)'\n') || (buf[i] == (byte)'\r')) {
+                    return UNKNOWN_METHOD;
+                }
+                i++;
+            }
+
+            String headerName = new String(buf, 0, i);
+            i++; // Over ':'
+            while (buf[i] == ' ') {
+                i++;
+            }
+            String headerValue = new String(buf, i, nread-1);
+
+            headers.put(headerName, headerValue);
+            return nread;
+        }
+
+        /**
+         * Read all headers from the input stream
+         * @param is Inputstream to read
+         * @return number of bytes read
+         */
+        private int readHeaders(InputStream is) {
+            int nread = 0;
+            log("Read headers");
+            // Headers should be terminated by empty CRLF line
+            while (true) {
+                int headerLen = 0;
+                headerLen = parseHeader(is);
+                if (headerLen == -1)
+                    return -1;
+                nread += headerLen;
+                if (headerLen <= 2) {
+                    return nread;
+                }
+            }
+        }
+
+        /**
+         * Read content data from the input stream
+         * @param is Inputstream to read
+         * @return number of bytes read
+         */
+        private int readContent(InputStream is) {
+            int nread = 0;
+            log("Read content");
+            String lengthString = headers.get(requestHeaders[REQ_CONTENT_LENGTH]);
+            int length = new Integer(lengthString).intValue();
+
+            // Read content
+            length = readData(is, length);
+            return length;
+        }
+
+        /**
+         * The main loop, reading requests.
+         */
+        void handleClient() throws IOException {
+            InputStream is = new BufferedInputStream(s.getInputStream());
+            PrintStream ps = new PrintStream(s.getOutputStream());
+            int nread = 0;
+
+            /* we will only block in read for this many milliseconds
+             * before we fail with java.io.InterruptedIOException,
+             * at which point we will abandon the connection.
+             */
+            s.setSoTimeout(mTimeout);
+            s.setTcpNoDelay(true);
+
+            do {
+                nread = parseStatusLine(is);
+                if (requestMethod != UNKNOWN_METHOD) {
+
+                    // If status line found, read any headers
+                    nread = readHeaders(is);
+
+                    // Then read content (if any)
+                    // TODO handle chunked encoding from the client
+                    if (headers.get(requestHeaders[REQ_CONTENT_LENGTH]) != null) {
+                        nread = readContent(is);
+                    }
+                } else {
+                    if (nread > 0) {
+                        /* we don't support this method */
+                        ps.print(HTTP_VERSION_STRING + " " + HTTP_BAD_METHOD +
+                                 " unsupported method type: ");
+                        ps.write(buf, 0, 5);
+                        ps.write(EOL);
+                        ps.flush();
+                    } else {
+                    }
+                    if (!keepAlive || nread <= 0) {
+                        headers.clear();
+                        readStarted = false;
+
+                        log("SOCKET CLOSED");
+                        s.close();
+                        return;
+                    }
+                }
+
+                // Reset test number prior to outputing data
+                testNum = -1;
+
+                // Write out the data
+                printStatus(ps);
+                printHeaders(ps);
+
+                // Write line between headers and body
+                psWriteEOL(ps);
+
+                // Write the body
+                if (redirectCode == -1) {
+                    switch (requestMethod) {
+                        case GET_METHOD:
+                            if ((testNum < -1) || (testNum > Support_TestWebData.tests.length - 1)) {
+                                send404(ps);
+                            } else {
+                                sendFile(ps);
+                            }
+                            break;
+                        case HEAD_METHOD:
+                            // Nothing to do
+                            break;
+                        case POST_METHOD:
+                            // Post method write body data
+                            if ((testNum > 0) || (testNum < Support_TestWebData.tests.length - 1)) {
+                                sendFile(ps);
+                            }
+
+                            break;
+                        default:
+                            break;
+                    }
+                } else { // Redirecting
+                    switch (redirectCode) {
+                        case 301:
+                            // Seems 301 needs a body by neon (although spec
+                            // says SHOULD).
+                            psPrint(ps, Support_TestWebData.testServerResponse[Support_TestWebData.REDIRECT_301]);
+                            break;
+                        case 302:
+                            //
+                            psPrint(ps, Support_TestWebData.testServerResponse[Support_TestWebData.REDIRECT_302]);
+                            break;
+                        case 303:
+                            psPrint(ps, Support_TestWebData.testServerResponse[Support_TestWebData.REDIRECT_303]);
+                            break;
+                        case 307:
+                            psPrint(ps, Support_TestWebData.testServerResponse[Support_TestWebData.REDIRECT_307]);
+                            break;
+                        default:
+                            break;
+                    }
+                }
+
+                ps.flush();
+
+                // Reset for next request
+                readStarted = false;
+                headers.clear();
+
+            } while (keepAlive);
+
+            log("SOCKET CLOSED");
+            s.close();
+        }
+
+        // Print string to log and output stream
+        void psPrint(PrintStream ps, String s) throws IOException {
+            log(s);
+            ps.print(s);
+        }
+
+        // Print bytes to log and output stream
+        void psWrite(PrintStream ps, byte[] bytes, int len) throws IOException {
+            log(new String(bytes));
+            ps.write(bytes, 0, len);
+        }
+
+        // Print CRLF to log and output stream
+        void psWriteEOL(PrintStream ps) throws IOException {
+            log("CRLF");
+            ps.write(EOL);
+        }
+
+
+        // Print status to log and output stream
+        void printStatus(PrintStream ps) throws IOException {
+            // Handle redirects first.
+            if (redirectCode != -1) {
+                log("REDIRECTING TO "+redirectHost+" status "+redirectCode);
+                psPrint(ps, HTTP_VERSION_STRING + " " + redirectCode +" Moved permanently");
+                psWriteEOL(ps);
+                psPrint(ps, "Location: " + redirectHost);
+                psWriteEOL(ps);
+                return;
+            }
+
+
+            if (testID.startsWith("test")) {
+                testNum = Integer.valueOf(testID.substring(4))-1;
+            }
+
+            if ((testNum < -1) || (testNum > Support_TestWebData.tests.length - 1)) {
+                psPrint(ps, HTTP_VERSION_STRING + " " + HTTP_NOT_FOUND + " not found");
+                psWriteEOL(ps);
+            }  else {
+                psPrint(ps, HTTP_VERSION_STRING + " " + HTTP_OK+" OK");
+                psWriteEOL(ps);
+            }
+
+            log("Status sent");
+        }
+        /**
+         * Create the server response and output to the stream
+         * @param ps The PrintStream to output response headers and data to
+         */
+        void printHeaders(PrintStream ps) throws IOException {
+            if ((testNum < -1) || (testNum > Support_TestWebData.tests.length - 1)) {
+                // 404 status already sent
+                return;
+            }
+            SimpleDateFormat df = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss");
+
+            psPrint(ps,"Server: TestWebServer"+mPort);
+            psWriteEOL(ps);
+            psPrint(ps, "Date: " + df.format(new Date()));
+            psWriteEOL(ps);
+            psPrint(ps, "Connection: " + ((keepAlive) ? "Keep-Alive" : "Close"));
+            psWriteEOL(ps);
+
+            // Yuk, if we're not redirecting, we add the file details
+            if (redirectCode == -1) {
+
+                if (testNum == -1) {
+                    if (!Support_TestWebData.test0DataAvailable) {
+                        log("testdata was not initilaized");
+                        return;
+                    }
+                    if (chunked) {
+                        psPrint(ps, "Transfer-Encoding: chunked");
+                    } else {
+                        psPrint(ps, "Content-length: "
+                                + Support_TestWebData.test0Data.length);
+                    }
+                    psWriteEOL(ps);
+
+                    psPrint(ps, "Last Modified: " + (new Date(
+                            Support_TestWebData.test0Params.testLastModified)));
+                    psWriteEOL(ps);
+
+                    psPrint(ps, "Content-type: "
+                            + Support_TestWebData.test0Params.testType);
+                    psWriteEOL(ps);
+
+                    if (Support_TestWebData.testParams[testNum].testExp > 0) {
+                        long exp;
+                        exp = Support_TestWebData.testParams[testNum].testExp;
+                        psPrint(ps, "expires: "
+                                + df.format(exp) + " GMT");
+                        psWriteEOL(ps);
+                    }
+                } else if (!Support_TestWebData.testParams[testNum].testDir) {
+                    if (chunked) {
+                        psPrint(ps, "Transfer-Encoding: chunked");
+                    } else {
+                        psPrint(ps, "Content-length: "+Support_TestWebData.testParams[testNum].testLength);
+                    }
+                    psWriteEOL(ps);
+
+                    psPrint(ps,"Last Modified: " + (new
+                                                    Date(Support_TestWebData.testParams[testNum].testLastModified)));
+                    psWriteEOL(ps);
+
+                    psPrint(ps, "Content-type: " + Support_TestWebData.testParams[testNum].testType);
+                    psWriteEOL(ps);
+
+                    if (Support_TestWebData.testParams[testNum].testExp > 0) {
+                        long exp;
+                        exp = Support_TestWebData.testParams[testNum].testExp;
+                        psPrint(ps, "expires: "
+                                + df.format(exp) + " GMT");
+                        psWriteEOL(ps);
+                    }
+                } else {
+                    psPrint(ps, "Content-type: text/html");
+                    psWriteEOL(ps);
+                }
+            } else {
+                // Content-length of 301, 302, 303, 307 are the same.
+                psPrint(ps, "Content-length: "+(Support_TestWebData.testServerResponse[Support_TestWebData.REDIRECT_301]).length());
+                psWriteEOL(ps);
+                psWriteEOL(ps);
+            }
+            log("Headers sent");
+
+        }
+
+        /**
+         * Sends the 404 not found message
+         * @param ps The PrintStream to write to
+         */
+        void send404(PrintStream ps) throws IOException {
+            ps.println("Not Found\n\n"+
+                       "The requested resource was not found.\n");
+        }
+
+        /**
+         * Sends the data associated with the headers
+         * @param ps The PrintStream to write to
+         */
+        void sendFile(PrintStream ps) throws IOException {
+            // For now just make a chunk with the whole of the test data
+            // It might be worth making this multiple chunks for large
+            // test data to test multiple chunks.
+            if (testNum == -1) {
+                if (!Support_TestWebData.test0DataAvailable) {
+                    log("testdata was not initilaized");
+                    return;
+                }
+                int dataSize = Support_TestWebData.test0Data.length;
+                if (chunked) {
+                    psPrint(ps, Integer.toHexString(dataSize));
+                    psWriteEOL(ps);
+                    psWrite(ps, Support_TestWebData.test0Data, dataSize);
+                    psWriteEOL(ps);
+                    psPrint(ps, "0");
+                    psWriteEOL(ps);
+                    psWriteEOL(ps);
+                } else {
+                    psWrite(ps, Support_TestWebData.test0Data, dataSize);
+                }
+            } else {
+                int dataSize = Support_TestWebData.tests[testNum].length;
+                if (chunked) {
+                    psPrint(ps, Integer.toHexString(dataSize));
+                    psWriteEOL(ps);
+                    psWrite(ps, Support_TestWebData.tests[testNum], dataSize);
+                    psWriteEOL(ps);
+                    psPrint(ps, "0");
+                    psWriteEOL(ps);
+                    psWriteEOL(ps);
+                } else {
+                    psWrite(ps, Support_TestWebData.tests[testNum], dataSize);
+                }
+            }
+        }
+    }
+}