<commit_before>/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.apache.harmony.luni.tests.java.net;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.FileNameMap;
import java.net.HttpURLConnection;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.ProtocolException;
import java.net.SocketPermission;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.security.Permission;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import tests.support.Support_Configuration;
import tests.support.Support_HttpServer;
import tests.support.Support_HttpServerSocket;
import tests.support.Support_HttpTests;
import tests.support.Support_Jetty;
import tests.support.Support_PortManager;
import tests.support.Support_URLConnector;
import tests.support.resource.Support_Resources;

public class URLConnectionTest extends junit.framework.TestCase {

    static class MockURLConnection extends URLConnection {

        public MockURLConnection(URL url) {
            super(url);
        }

        @Override
        public void connect() {
            connected = true;
        }
    }

    static class NewHandler extends URLStreamHandler {
        protected URLConnection openConnection(URL u) throws IOException {
            return new HttpURLConnection(u) {
                @Override
                public void connect() throws IOException {
                    connected = true;
                }

                @Override
                public void disconnect() {
                    // do nothing
                }

                @Override
                public boolean usingProxy() {
                    return false;
                }
            };
        }
    }

    private static int port;

    static String getContentType(String fileName) throws IOException {
        String resourceName = "org/apache/harmony/luni/tests/" + fileName;
        URL url = ClassLoader.getSystemClassLoader().getResource(resourceName);
        assertNotNull("Cannot find test resource " + resourceName, url);
        return url.openConnection().getContentType();
    }

    URL url;

    URLConnection uc;

    protected void setUp() throws Exception {
        url = new URL("http://localhost:" + port + "/");
        uc = (HttpURLConnection) url.openConnection();
        port = Support_Jetty.startDefaultHttpServer();
    }

    protected void tearDown() {
        ((HttpURLConnection) uc).disconnect();
    }

    /**
     * @tests java.net.URLConnection#addRequestProperty(String, String)
     */
    public void test_addRequestProperty() throws MalformedURLException,
            IOException {

        MockURLConnection u = new MockURLConnection(new URL(
                "http://www.apache.org"));
        try {
            // Regression for HARMONY-604
            u.addRequestProperty(null, "someValue");
            fail("Expected NullPointerException");
        } catch (NullPointerException e) {
            // expected
        }

        u.connect();
        try {
            // state of connection is checked first
            // so no NPE in case of null 'field' param
            u.addRequestProperty(null, "someValue");
            fail("Expected IllegalStateException");
        } catch (IllegalStateException e) {
            // expected
        }
    }

    /**
     * @tests java.net.URLConnection#addRequestProperty(java.lang.String,java.lang.String)
     */
    public void test_addRequestPropertyLjava_lang_StringLjava_lang_String()
            throws IOException {
        uc.setRequestProperty("prop", "yo");
        uc.setRequestProperty("prop", "yo2");
        assertEquals("yo2", uc.getRequestProperty("prop"));
        Map<String, List<String>> map = uc.getRequestProperties();
        List<String> props = uc.getRequestProperties().get("prop");
        assertEquals(1, props.size());

        try {
            // the map should be unmodifiable
            map.put("hi", Arrays.asList(new String[] { "bye" }));
            fail("could modify map");
        } catch (UnsupportedOperationException e) {
            // Expected
        }
        try {
            // the list should be unmodifiable
            props.add("hi");
            fail("could modify list");
        } catch (UnsupportedOperationException e) {
            // Expected
        }

        File resources = Support_Resources.createTempFolder();
        Support_Resources.copyFile(resources, null, "hyts_att.jar");
        URL fUrl1 = new URL("jar:file:" + resources.getPath()
                + "/hyts_att.jar!/");
        JarURLConnection con1 = (JarURLConnection) fUrl1.openConnection();
        map = con1.getRequestProperties();
        assertNotNull(map);
        assertEquals(0, map.size());
        try {
            // the map should be unmodifiable
            map.put("hi", Arrays.asList(new String[] { "bye" }));
            fail();
        } catch (UnsupportedOperationException e) {
            // Expected
        }
    }

    /**
     * @tests java.net.URLConnection#getAllowUserInteraction()
     */
    public void test_getAllowUserInteraction() {
        uc.setAllowUserInteraction(false);
        assertFalse("getAllowUserInteraction should have returned false", uc
                .getAllowUserInteraction());

        uc.setAllowUserInteraction(true);
        assertTrue("getAllowUserInteraction should have returned true", uc
                .getAllowUserInteraction());
    }

    /**
     * @tests java.net.URLConnection#getContent()
     */
    public void test_getContent() throws IOException {
        byte[] ba = new byte[600];
        ((InputStream) uc.getContent()).read(ba, 0, 600);
        String s = new String(ba);
        assertTrue("Incorrect content returned",
                s.indexOf("Hello OneHandler") > 0);
    }

    /**
     * @tests java.net.URLConnection#getContent(Class[])
     */
    public void test_getContent_LjavalangClass() throws IOException {
        byte[] ba = new byte[600];

        try {
            ((InputStream) uc.getContent(null)).read(ba, 0, 600);
            fail("should throw NullPointerException");
        } catch (NullPointerException e) {
            // expected
        }

        try {
            ((InputStream) uc.getContent(new Class[] {})).read(ba, 0, 600);
            fail("should throw NullPointerException");
        } catch (NullPointerException e) {
            // expected
        }

        try {
            ((InputStream) uc.getContent(new Class[] { Class.class })).read(ba,
                    0, 600);
            fail("should throw NullPointerException");
        } catch (NullPointerException e) {
            // expected
        }
    }

    /**
     * @tests java.net.URLConnection#getContentEncoding()
     */
    public void test_getContentEncoding() {
        // should not be known for a file
        assertNull("getContentEncoding failed: " + uc.getContentEncoding(), uc
                .getContentEncoding());
    }

    /**
     * @tests java.net.URLConnection#getContentLength()
     */
    public void test_getContentLength() throws IOException {
        assertEquals("getContentLength failed: " + uc.getContentLength(), 25,
                uc.getContentLength());
    }

    /**
     * @tests java.net.URLConnection#getContentType()
     */
    public void test_getContentType() throws IOException {
        // should not be known for a file
        assertTrue("getContentType failed: " + uc.getContentType(), uc
                .getContentType().contains("text/html"));

        File resources = Support_Resources.createTempFolder();
        Support_Resources.copyFile(resources, null, "Harmony.GIF");
        URL url = new URL("file:/" + resources.toString() + "/Harmony.GIF");
        URLConnection conn = url.openConnection();
        assertEquals("type not GIF", "image/gif", conn.getContentType());
    }

    /**
     * @tests java.net.URLConnection#getContentType()
     */
    public void test_getContentType_regression() throws IOException {
        // Regression for HARMONY-4699
        assertEquals(getContentType("test.rtf"), "application/rtf");
        assertEquals(getContentType("test.java"), "text/plain");
        // RI would return "content/unknown"
        assertEquals(getContentType("test.doc"), "application/msword");
        assertEquals(getContentType("test.htx"), "text/html");
        assertEquals(getContentType("test.xml"), "application/xml");
        assertEquals(getContentType("."), "text/plain");
    }

    /**
     * @tests java.net.URLConnection#getDate()
     */
    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(),
                    uc.getDate() > 930000000000L);
        }
    }

    /**
     * @tests java.net.URLConnection#getDefaultAllowUserInteraction()
     */
    public void test_getDefaultAllowUserInteraction() {
        boolean oldSetting = URLConnection.getDefaultAllowUserInteraction();

        URLConnection.setDefaultAllowUserInteraction(false);
        assertFalse(
                "getDefaultAllowUserInteraction should have returned false",
                URLConnection.getDefaultAllowUserInteraction());

        URLConnection.setDefaultAllowUserInteraction(true);
        assertTrue("getDefaultAllowUserInteraction should have returned true",
                URLConnection.getDefaultAllowUserInteraction());

        URLConnection.setDefaultAllowUserInteraction(oldSetting);
    }

    /**
     * @tests java.net.URLConnection#getDefaultRequestProperty(java.lang.String)
     */
    @SuppressWarnings("deprecation")
    public void test_getDefaultRequestPropertyLjava_lang_String() {
        URLConnection.setDefaultRequestProperty("Shmoo", "Blah");
        assertNull("setDefaultRequestProperty should have returned: null",
                URLConnection.getDefaultRequestProperty("Shmoo"));

        URLConnection.setDefaultRequestProperty("Shmoo", "Boom");
        assertNull("setDefaultRequestProperty should have returned: null",
                URLConnection.getDefaultRequestProperty("Shmoo"));

        assertNull("setDefaultRequestProperty should have returned: null",
                URLConnection.getDefaultRequestProperty("Kapow"));

        URLConnection.setDefaultRequestProperty("Shmoo", null);
    }

    /**
     * @tests java.net.URLConnection#getDefaultUseCaches()
     */
    public void test_getDefaultUseCaches() {
        boolean oldSetting = uc.getDefaultUseCaches();

        uc.setDefaultUseCaches(false);
        assertFalse("getDefaultUseCaches should have returned false", uc
                .getDefaultUseCaches());

        uc.setDefaultUseCaches(true);
        assertTrue("getDefaultUseCaches should have returned true", uc
                .getDefaultUseCaches());

        uc.setDefaultUseCaches(oldSetting);
    }

    /**
     * @tests java.net.URLConnection#getDoInput()
     */
    public void test_getDoInput() {
        assertTrue("Should be set to true by default", uc.getDoInput());

        uc.setDoInput(true);
        assertTrue("Should have been set to true", uc.getDoInput());

        uc.setDoInput(false);
        assertFalse("Should have been set to false", uc.getDoInput());
    }

    /**
     * @tests java.net.URLConnection#getDoOutput()
     */
    public void test_getDoOutput() {
        assertFalse("Should be set to false by default", uc.getDoOutput());

        uc.setDoOutput(true);
        assertTrue("Should have been set to true", uc.getDoOutput());

        uc.setDoOutput(false);
        assertFalse("Should have been set to false", uc.getDoOutput());
    }

    /**
     * @tests java.net.URLConnection#getExpiration()
     */
    public void test_getExpiration() {
        // should be unknown
        assertEquals("getExpiration returned wrong expiration", 0, uc
                .getExpiration());
    }

    /**
     * @tests java.net.URLConnection#getFileNameMap()
     */
    public void test_getFileNameMap() {
        // Tests for the standard MIME types -- users may override these
        // in their JRE
        FileNameMap map = URLConnection.getFileNameMap();

        // These types are defaulted
        assertEquals("text/html", map.getContentTypeFor(".htm"));
        assertEquals("text/html", map.getContentTypeFor(".html"));
        assertEquals("text/plain", map.getContentTypeFor(".text"));
        assertEquals("text/plain", map.getContentTypeFor(".txt"));

        // These types come from the properties file
        assertEquals("application/pdf", map.getContentTypeFor(".pdf"));
        assertEquals("application/zip", map.getContentTypeFor(".zip"));

        URLConnection.setFileNameMap(new FileNameMap() {
            public String getContentTypeFor(String fileName) {
                return "Spam!";
            }
        });
        try {
            assertEquals("Incorrect FileNameMap returned", "Spam!",
                    URLConnection.getFileNameMap().getContentTypeFor(null));
        } finally {
            // unset the map so other tests don't fail
            URLConnection.setFileNameMap(null);
        }
        // RI fails since it does not support fileName that does not begin with
        // '.'
        assertEquals("image/gif", map.getContentTypeFor("gif"));
    }

    /**
     * @tests java.net.URLConnection#getHeaderFieldDate(java.lang.String, long)
     */
    public void test_getHeaderFieldDateLjava_lang_StringJ() {

        if (uc.getHeaderFieldDate("Date", 22L) == 22L) {
            System.out
                    .println("WARNING: Server does not support 'Date', test_getHeaderFieldDateLjava_lang_StringJ not run");
            return;
        }
        assertTrue("Wrong value returned: "
                + uc.getHeaderFieldDate("Date", 22L), uc.getHeaderFieldDate(
                "Date", 22L) > 930000000000L);

        long time = uc.getHeaderFieldDate("Last-Modified", 0);
        assertEquals("Wrong date: ", time,
                Support_Configuration.URLConnectionLastModified);
    }

    /**
     * @tests java.net.URLConnection#getHeaderField(int)
     */
    public void test_getHeaderFieldI() {
        int i = 0;
        String hf;
        boolean foundResponse = false;
        while ((hf = uc.getHeaderField(i++)) != null) {
            if (hf.equals(Support_Configuration.HomeAddressSoftware)) {
                foundResponse = true;
            }
        }
        assertTrue("Could not find header field containing \""
                + Support_Configuration.HomeAddressSoftware + "\"",
                foundResponse);

        i = 0;
        foundResponse = false;
        while ((hf = uc.getHeaderField(i++)) != null) {
            if (hf.equals(Support_Configuration.HomeAddressResponse)) {
                foundResponse = true;
            }
        }
        assertTrue("Could not find header field containing \""
                + Support_Configuration.HomeAddressResponse + "\"",
                foundResponse);
    }

    /**
     * @tests java.net.URLConnection#getHeaderFieldKey(int)
     */
    public void test_getHeaderFieldKeyI() {
        String hf;
        boolean foundResponse = false;
        for (int i = 0; i < 100; i++) {
            hf = uc.getHeaderFieldKey(i);
            if (hf != null && hf.toLowerCase().equals("content-type")) {
                foundResponse = true;
                break;
            }
        }
        assertTrue(
                "Could not find header field key containing \"content-type\"",
                foundResponse);
    }

    /**
     * @tests java.net.URLConnection#getHeaderField(java.lang.String)
     */
    public void test_getHeaderFieldLjava_lang_String() {
        String hf;
        hf = uc.getHeaderField("Content-Encoding");
        if (hf != null) {
            assertNull(
                    "Wrong value returned for header field 'Content-Encoding': "
                            + hf, hf);
        }
        hf = uc.getHeaderField("Content-Length");
        if (hf != null) {
            assertEquals(
                    "Wrong value returned for header field 'Content-Length': ",
                    "25", hf);
        }
        hf = uc.getHeaderField("Content-Type");
        if (hf != null) {
            assertTrue("Wrong value returned for header field 'Content-Type': "
                    + hf, hf.contains("text/html"));
        }
        hf = uc.getHeaderField("content-type");
        if (hf != null) {
            assertTrue("Wrong value returned for header field 'content-type': "
                    + hf, hf.contains("text/html"));
        }
        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);
        }
        hf = uc.getHeaderField("SERVER");
        if (hf != null) {
            assertTrue("Wrong value returned for header field 'SERVER': " + hf
                    + " (expected " + Support_Configuration.HomeAddressSoftware
                    + ")", hf.equals(Support_Configuration.HomeAddressSoftware));
        }
        hf = uc.getHeaderField("Last-Modified");
        if (hf != null) {
            assertTrue(
                    "Wrong value returned for header field 'Last-Modified': "
                            + hf,
                    hf
                            .equals(Support_Configuration.URLConnectionLastModifiedString));
        }
        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);
        }
    }

    /**
     * @tests java.net.URLConnection#getHeaderFields()
     */
    public void test_getHeaderFields() throws IOException {
        try {
            uc.getInputStream();
        } catch (IOException e) {
            fail();
        }

        Map<String, List<String>> headers = uc.getHeaderFields();
        assertNotNull(headers);

        // content-length should always appear
        List<String> list = headers.get("Content-Length");
        if (list == null) {
            list = headers.get("content-length");
        }
        assertNotNull(list);
        String contentLength = (String) list.get(0);
        assertNotNull(contentLength);

        // there should be at least 2 headers
        assertTrue(headers.size() > 1);
        File resources = Support_Resources.createTempFolder();
        Support_Resources.copyFile(resources, null, "hyts_att.jar");
        URL fUrl1 = new URL("jar:file:" + resources.getPath()
                + "/hyts_att.jar!/");
        JarURLConnection con1 = (JarURLConnection) fUrl1.openConnection();
        headers = con1.getHeaderFields();
        assertNotNull(headers);
        assertEquals(0, headers.size());
        try {
            // the map should be unmodifiable
            headers.put("hi", Arrays.asList(new String[] { "bye" }));
            fail("The map should be unmodifiable");
        } catch (UnsupportedOperationException e) {
            // Expected
        }
    }

    /**
     * @tests java.net.URLConnection#getIfModifiedSince()
     */
    public void test_getIfModifiedSince() {
        uc.setIfModifiedSince(200);
        assertEquals("Returned wrong ifModifiedSince value", 200, uc
                .getIfModifiedSince());
    }

    /**
     * @tests java.net.URLConnection#getInputStream()
     */
    public void test_getInputStream() throws IOException {
        InputStream is = uc.getInputStream();
        byte[] ba = new byte[600];
        is.read(ba, 0, 600);
        is.close();
        String s = new String(ba);
        assertTrue("Incorrect input stream read",
                s.indexOf("Hello OneHandler") > 0);

        // open an non-existent file
        URL url = new URL("http://localhost:" + port + "/fred-zz6.txt");
        is = url.openStream();
        assertTrue("available() less than 0", is.available() >= 0);
        is.close();

        // create a server socket
        Support_HttpServerSocket serversocket = new Support_HttpServerSocket();

        // create a client connector<commit_msg>Fix failures of test_getInputStream and test_getContent of URLConnectionTest for zOS<commit_after>/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.apache.harmony.luni.tests.java.net;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.FileNameMap;
import java.net.HttpURLConnection;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.ProtocolException;
import java.net.SocketPermission;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.security.Permission;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import org.apache.harmony.luni.util.Util;

import tests.support.Support_Configuration;
import tests.support.Support_HttpServer;
import tests.support.Support_HttpServerSocket;
import tests.support.Support_HttpTests;
import tests.support.Support_Jetty;
import tests.support.Support_PortManager;
import tests.support.Support_URLConnector;
import tests.support.resource.Support_Resources;

public class URLConnectionTest extends junit.framework.TestCase {

    static class MockURLConnection extends URLConnection {

        public MockURLConnection(URL url) {
            super(url);
        }

        @Override
        public void connect() {
            connected = true;
        }
    }

    static class NewHandler extends URLStreamHandler {
        protected URLConnection openConnection(URL u) throws IOException {
            return new HttpURLConnection(u) {
                @Override
                public void connect() throws IOException {
                    connected = true;
                }

                @Override
                public void disconnect() {
                    // do nothing
                }

                @Override
                public boolean usingProxy() {
                    return false;
                }
            };
        }
    }

    private static int port;

    static String getContentType(String fileName) throws IOException {
        String resourceName = "org/apache/harmony/luni/tests/" + fileName;
        URL url = ClassLoader.getSystemClassLoader().getResource(resourceName);
        assertNotNull("Cannot find test resource " + resourceName, url);
        return url.openConnection().getContentType();
    }

    URL url;

    URLConnection uc;

    protected void setUp() throws Exception {
        url = new URL("http://localhost:" + port + "/");
        uc = (HttpURLConnection) url.openConnection();
        port = Support_Jetty.startDefaultHttpServer();
    }

    protected void tearDown() {
        ((HttpURLConnection) uc).disconnect();
    }

    /**
     * @tests java.net.URLConnection#addRequestProperty(String, String)
     */
    public void test_addRequestProperty() throws MalformedURLException,
            IOException {

        MockURLConnection u = new MockURLConnection(new URL(
                "http://www.apache.org"));
        try {
            // Regression for HARMONY-604
            u.addRequestProperty(null, "someValue");
            fail("Expected NullPointerException");
        } catch (NullPointerException e) {
            // expected
        }

        u.connect();
        try {
            // state of connection is checked first
            // so no NPE in case of null 'field' param
            u.addRequestProperty(null, "someValue");
            fail("Expected IllegalStateException");
        } catch (IllegalStateException e) {
            // expected
        }
    }

    /**
     * @tests java.net.URLConnection#addRequestProperty(java.lang.String,java.lang.String)
     */
    public void test_addRequestPropertyLjava_lang_StringLjava_lang_String()
            throws IOException {
        uc.setRequestProperty("prop", "yo");
        uc.setRequestProperty("prop", "yo2");
        assertEquals("yo2", uc.getRequestProperty("prop"));
        Map<String, List<String>> map = uc.getRequestProperties();
        List<String> props = uc.getRequestProperties().get("prop");
        assertEquals(1, props.size());

        try {
            // the map should be unmodifiable
            map.put("hi", Arrays.asList(new String[] { "bye" }));
            fail("could modify map");
        } catch (UnsupportedOperationException e) {
            // Expected
        }
        try {
            // the list should be unmodifiable
            props.add("hi");
            fail("could modify list");
        } catch (UnsupportedOperationException e) {
            // Expected
        }

        File resources = Support_Resources.createTempFolder();
        Support_Resources.copyFile(resources, null, "hyts_att.jar");
        URL fUrl1 = new URL("jar:file:" + resources.getPath()
                + "/hyts_att.jar!/");
        JarURLConnection con1 = (JarURLConnection) fUrl1.openConnection();
        map = con1.getRequestProperties();
        assertNotNull(map);
        assertEquals(0, map.size());
        try {
            // the map should be unmodifiable
            map.put("hi", Arrays.asList(new String[] { "bye" }));
            fail();
        } catch (UnsupportedOperationException e) {
            // Expected
        }
    }

    /**
     * @tests java.net.URLConnection#getAllowUserInteraction()
     */
    public void test_getAllowUserInteraction() {
        uc.setAllowUserInteraction(false);
        assertFalse("getAllowUserInteraction should have returned false", uc
                .getAllowUserInteraction());

        uc.setAllowUserInteraction(true);
        assertTrue("getAllowUserInteraction should have returned true", uc
                .getAllowUserInteraction());
    }

    /**
     * @tests java.net.URLConnection#getContent()
     */
    public void test_getContent() throws IOException {
        byte[] ba = new byte[600];
        ((InputStream) uc.getContent()).read(ba, 0, 600);
        String s = Util.toUTF8String(ba);
        assertTrue("Incorrect content returned",
                s.indexOf("Hello OneHandler") > 0);
    }

    /**
     * @tests java.net.URLConnection#getContent(Class[])
     */
    public void test_getContent_LjavalangClass() throws IOException {
        byte[] ba = new byte[600];

        try {
            ((InputStream) uc.getContent(null)).read(ba, 0, 600);
            fail("should throw NullPointerException");
        } catch (NullPointerException e) {
            // expected
        }

        try {
            ((InputStream) uc.getContent(new Class[] {})).read(ba, 0, 600);
            fail("should throw NullPointerException");
        } catch (NullPointerException e) {
            // expected
        }

        try {
            ((InputStream) uc.getContent(new Class[] { Class.class })).read(ba,
                    0, 600);
            fail("should throw NullPointerException");
        } catch (NullPointerException e) {
            // expected
        }
    }

    /**
     * @tests java.net.URLConnection#getContentEncoding()
     */
    public void test_getContentEncoding() {
        // should not be known for a file
        assertNull("getContentEncoding failed: " + uc.getContentEncoding(), uc
                .getContentEncoding());
    }

    /**
     * @tests java.net.URLConnection#getContentLength()
     */
    public void test_getContentLength() throws IOException {
        assertEquals("getContentLength failed: " + uc.getContentLength(), 25,
                uc.getContentLength());
    }

    /**
     * @tests java.net.URLConnection#getContentType()
     */
    public void test_getContentType() throws IOException {
        // should not be known for a file
        assertTrue("getContentType failed: " + uc.getContentType(), uc
                .getContentType().contains("text/html"));

        File resources = Support_Resources.createTempFolder();
        Support_Resources.copyFile(resources, null, "Harmony.GIF");
        URL url = new URL("file:/" + resources.toString() + "/Harmony.GIF");
        URLConnection conn = url.openConnection();
        assertEquals("type not GIF", "image/gif", conn.getContentType());
    }

    /**
     * @tests java.net.URLConnection#getContentType()
     */
    public void test_getContentType_regression() throws IOException {
        // Regression for HARMONY-4699
        assertEquals(getContentType("test.rtf"), "application/rtf");
        assertEquals(getContentType("test.java"), "text/plain");
        // RI would return "content/unknown"
        assertEquals(getContentType("test.doc"), "application/msword");
        assertEquals(getContentType("test.htx"), "text/html");
        assertEquals(getContentType("test.xml"), "application/xml");
        assertEquals(getContentType("."), "text/plain");
    }

    /**
     * @tests java.net.URLConnection#getDate()
     */
    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(),
                    uc.getDate() > 930000000000L);
        }
    }

    /**
     * @tests java.net.URLConnection#getDefaultAllowUserInteraction()
     */
    public void test_getDefaultAllowUserInteraction() {
        boolean oldSetting = URLConnection.getDefaultAllowUserInteraction();

        URLConnection.setDefaultAllowUserInteraction(false);
        assertFalse(
                "getDefaultAllowUserInteraction should have returned false",
                URLConnection.getDefaultAllowUserInteraction());

        URLConnection.setDefaultAllowUserInteraction(true);
        assertTrue("getDefaultAllowUserInteraction should have returned true",
                URLConnection.getDefaultAllowUserInteraction());

        URLConnection.setDefaultAllowUserInteraction(oldSetting);
    }

    /**
     * @tests java.net.URLConnection#getDefaultRequestProperty(java.lang.String)
     */
    @SuppressWarnings("deprecation")
    public void test_getDefaultRequestPropertyLjava_lang_String() {
        URLConnection.setDefaultRequestProperty("Shmoo", "Blah");
        assertNull("setDefaultRequestProperty should have returned: null",
                URLConnection.getDefaultRequestProperty("Shmoo"));

        URLConnection.setDefaultRequestProperty("Shmoo", "Boom");
        assertNull("setDefaultRequestProperty should have returned: null",
                URLConnection.getDefaultRequestProperty("Shmoo"));

        assertNull("setDefaultRequestProperty should have returned: null",
                URLConnection.getDefaultRequestProperty("Kapow"));

        URLConnection.setDefaultRequestProperty("Shmoo", null);
    }

    /**
     * @tests java.net.URLConnection#getDefaultUseCaches()
     */
    public void test_getDefaultUseCaches() {
        boolean oldSetting = uc.getDefaultUseCaches();

        uc.setDefaultUseCaches(false);
        assertFalse("getDefaultUseCaches should have returned false", uc
                .getDefaultUseCaches());

        uc.setDefaultUseCaches(true);
        assertTrue("getDefaultUseCaches should have returned true", uc
                .getDefaultUseCaches());

        uc.setDefaultUseCaches(oldSetting);
    }

    /**
     * @tests java.net.URLConnection#getDoInput()
     */
    public void test_getDoInput() {
        assertTrue("Should be set to true by default", uc.getDoInput());

        uc.setDoInput(true);
        assertTrue("Should have been set to true", uc.getDoInput());

        uc.setDoInput(false);
        assertFalse("Should have been set to false", uc.getDoInput());
    }

    /**
     * @tests java.net.URLConnection#getDoOutput()
     */
    public void test_getDoOutput() {
        assertFalse("Should be set to false by default", uc.getDoOutput());

        uc.setDoOutput(true);
        assertTrue("Should have been set to true", uc.getDoOutput());

        uc.setDoOutput(false);
        assertFalse("Should have been set to false", uc.getDoOutput());
    }

    /**
     * @tests java.net.URLConnection#getExpiration()
     */
    public void test_getExpiration() {
        // should be unknown
        assertEquals("getExpiration returned wrong expiration", 0, uc
                .getExpiration());
    }

    /**
     * @tests java.net.URLConnection#getFileNameMap()
     */
    public void test_getFileNameMap() {
        // Tests for the standard MIME types -- users may override these
        // in their JRE
        FileNameMap map = URLConnection.getFileNameMap();

        // These types are defaulted
        assertEquals("text/html", map.getContentTypeFor(".htm"));
        assertEquals("text/html", map.getContentTypeFor(".html"));
        assertEquals("text/plain", map.getContentTypeFor(".text"));
        assertEquals("text/plain", map.getContentTypeFor(".txt"));

        // These types come from the properties file
        assertEquals("application/pdf", map.getContentTypeFor(".pdf"));
        assertEquals("application/zip", map.getContentTypeFor(".zip"));

        URLConnection.setFileNameMap(new FileNameMap() {
            public String getContentTypeFor(String fileName) {
                return "Spam!";
            }
        });
        try {
            assertEquals("Incorrect FileNameMap returned", "Spam!",
                    URLConnection.getFileNameMap().getContentTypeFor(null));
        } finally {
            // unset the map so other tests don't fail
            URLConnection.setFileNameMap(null);
        }
        // RI fails since it does not support fileName that does not begin with
        // '.'
        assertEquals("image/gif", map.getContentTypeFor("gif"));
    }

    /**
     * @tests java.net.URLConnection#getHeaderFieldDate(java.lang.String, long)
     */
    public void test_getHeaderFieldDateLjava_lang_StringJ() {

        if (uc.getHeaderFieldDate("Date", 22L) == 22L) {
            System.out
                    .println("WARNING: Server does not support 'Date', test_getHeaderFieldDateLjava_lang_StringJ not run");
            return;
        }
        assertTrue("Wrong value returned: "
                + uc.getHeaderFieldDate("Date", 22L), uc.getHeaderFieldDate(
                "Date", 22L) > 930000000000L);

        long time = uc.getHeaderFieldDate("Last-Modified", 0);
        assertEquals("Wrong date: ", time,
                Support_Configuration.URLConnectionLastModified);
    }

    /**
     * @tests java.net.URLConnection#getHeaderField(int)
     */
    public void test_getHeaderFieldI() {
        int i = 0;
        String hf;
        boolean foundResponse = false;
        while ((hf = uc.getHeaderField(i++)) != null) {
            if (hf.equals(Support_Configuration.HomeAddressSoftware)) {
                foundResponse = true;
            }
        }
        assertTrue("Could not find header field containing \""
                + Support_Configuration.HomeAddressSoftware + "\"",
                foundResponse);

        i = 0;
        foundResponse = false;
        while ((hf = uc.getHeaderField(i++)) != null) {
            if (hf.equals(Support_Configuration.HomeAddressResponse)) {
                foundResponse = true;
            }
        }
        assertTrue("Could not find header field containing \""
                + Support_Configuration.HomeAddressResponse + "\"",
                foundResponse);
    }

    /**
     * @tests java.net.URLConnection#getHeaderFieldKey(int)
     */
    public void test_getHeaderFieldKeyI() {
        String hf;
        boolean foundResponse = false;
        for (int i = 0; i < 100; i++) {
            hf = uc.getHeaderFieldKey(i);
            if (hf != null && hf.toLowerCase().equals("content-type")) {
                foundResponse = true;
                break;
            }
        }
        assertTrue(
                "Could not find header field key containing \"content-type\"",
                foundResponse);
    }

    /**
     * @tests java.net.URLConnection#getHeaderField(java.lang.String)
     */
    public void test_getHeaderFieldLjava_lang_String() {
        String hf;
        hf = uc.getHeaderField("Content-Encoding");
        if (hf != null) {
            assertNull(
                    "Wrong value returned for header field 'Content-Encoding': "
                            + hf, hf);
        }
        hf = uc.getHeaderField("Content-Length");
        if (hf != null) {
            assertEquals(
                    "Wrong value returned for header field 'Content-Length': ",
                    "25", hf);
        }
        hf = uc.getHeaderField("Content-Type");
        if (hf != null) {
            assertTrue("Wrong value returned for header field 'Content-Type': "
                    + hf, hf.contains("text/html"));
        }
        hf = uc.getHeaderField("content-type");
        if (hf != null) {
            assertTrue("Wrong value returned for header field 'content-type': "
                    + hf, hf.contains("text/html"));
        }
        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);
        }
        hf = uc.getHeaderField("SERVER");
        if (hf != null) {
            assertTrue("Wrong value returned for header field 'SERVER': " + hf
                    + " (expected " + Support_Configuration.HomeAddressSoftware
                    + ")", hf.equals(Support_Configuration.HomeAddressSoftware));
        }
        hf = uc.getHeaderField("Last-Modified");
        if (hf != null) {
            assertTrue(
                    "Wrong value returned for header field 'Last-Modified': "
                            + hf,
                    hf
                            .equals(Support_Configuration.URLConnectionLastModifiedString));
        }
        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);
        }
    }

    /**
     * @tests java.net.URLConnection#getHeaderFields()
     */
    public void test_getHeaderFields() throws IOException {
        try {
            uc.getInputStream();
        } catch (IOException e) {
            fail();
        }

        Map<String, List<String>> headers = uc.getHeaderFields();
        assertNotNull(headers);

        // content-length should always appear
        List<String> list = headers.get("Content-Length");
        if (list == null) {
            list = headers.get("content-length");
        }
        assertNotNull(list);
        String contentLength = (String) list.get(0);
        assertNotNull(contentLength);

        // there should be at least 2 headers
        assertTrue(headers.size() > 1);
        File resources = Support_Resources.createTempFolder();
        Support_Resources.copyFile(resources, null, "hyts_att.jar");
        URL fUrl1 = new URL("jar:file:" + resources.getPath()
                + "/hyts_att.jar!/");
        JarURLConnection con1 = (JarURLConnection) fUrl1.openConnection();
        headers = con1.getHeaderFields();
        assertNotNull(headers);
        assertEquals(0, headers.size());
        try {
            // the map should be unmodifiable
            headers.put("hi", Arrays.asList(new String[] { "bye" }));
            fail("The map should be unmodifiable");
        } catch (UnsupportedOperationException e) {
            // Expected
        }
    }

    /**
     * @tests java.net.URLConnection#getIfModifiedSince()
     */
    public void test_getIfModifiedSince() {
        uc.setIfModifiedSince(200);
        assertEquals("Returned wrong ifModifiedSince value", 200, uc
                .getIfModifiedSince());
    }

    /**
     * @tests java.net.URLConnection#getInputStream()
     */
    public void test_getInputStream() throws IOException {
        InputStream is = uc.getInputStream();
        byte[] ba = new byte[600];
        is.read(ba, 0, 600);
        is.close();
        String s = Util.toUTF8String(ba);
        assertTrue("Incorrect input stream read",
                s.indexOf("Hello OneHandler") > 0);

        // open an non-existent file
        URL url = new URL("http://localhost:" + port + "/fred-zz6.txt");
        is = url.openStream();
        assertTrue("available() less than 0", is.available() >= 0);
        is.close();

        // create a server socket
        Support_HttpServerSocket serversocket = new Support_HttpServerSocket();

        // create a client connector
{'fraction_non_alphanumeric': 0.1111763908347268, 'fraction_numerical': 0.0060107560898449855, 'mean_word_length': 2.2143375944218477, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 6, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6726634', 'n_tokens_mistral': 11798, 'n_tokens_neox': 11335, 'n_words': 2662}