0001: /*
0002: * Licensed to the Apache Software Foundation (ASF) under one or more
0003: * contributor license agreements. See the NOTICE file distributed with
0004: * this work for additional information regarding copyright ownership.
0005: * The ASF licenses this file to You under the Apache License, Version 2.0
0006: * (the "License"); you may not use this file except in compliance with
0007: * the License. You may obtain a copy of the License at
0008: *
0009: * http://www.apache.org/licenses/LICENSE-2.0
0010: *
0011: * Unless required by applicable law or agreed to in writing, software
0012: * distributed under the License is distributed on an "AS IS" BASIS,
0013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014: * See the License for the specific language governing permissions and
0015: * limitations under the License.
0016: */
0017:
0018: package org.apache.harmony.luni.tests.java.net;
0019:
0020: import java.io.ByteArrayInputStream;
0021: import java.io.ByteArrayOutputStream;
0022: import java.io.File;
0023: import java.io.FileNotFoundException;
0024: import java.io.FilePermission;
0025: import java.io.IOException;
0026: import java.io.InputStream;
0027: import java.io.OutputStream;
0028: import java.net.Authenticator;
0029: import java.net.FileNameMap;
0030: import java.net.HttpURLConnection;
0031: import java.net.JarURLConnection;
0032: import java.net.MalformedURLException;
0033: import java.net.PasswordAuthentication;
0034: import java.net.ProtocolException;
0035: import java.net.SocketPermission;
0036: import java.net.URL;
0037: import java.net.URLConnection;
0038: import java.net.URLStreamHandler;
0039: import java.security.Permission;
0040: import java.util.Arrays;
0041: import java.util.Calendar;
0042: import java.util.GregorianCalendar;
0043: import java.util.List;
0044: import java.util.Map;
0045: import java.util.TimeZone;
0046:
0047: import tests.support.Support_Configuration;
0048: import tests.support.Support_HttpServer;
0049: import tests.support.Support_HttpServerSocket;
0050: import tests.support.Support_HttpTests;
0051: import tests.support.Support_Jetty;
0052: import tests.support.Support_PortManager;
0053: import tests.support.Support_URLConnector;
0054: import tests.support.resource.Support_Resources;
0055:
0056: public class URLConnectionTest extends junit.framework.TestCase {
0057:
0058: static class MockURLConnection extends URLConnection {
0059:
0060: public MockURLConnection(URL url) {
0061: super (url);
0062: }
0063:
0064: @Override
0065: public void connect() {
0066: connected = true;
0067: }
0068: }
0069:
0070: static class NewHandler extends URLStreamHandler {
0071: protected URLConnection openConnection(URL u)
0072: throws IOException {
0073: return new HttpURLConnection(u) {
0074: @Override
0075: public void connect() throws IOException {
0076: connected = true;
0077: }
0078:
0079: @Override
0080: public void disconnect() {
0081: // do nothing
0082: }
0083:
0084: @Override
0085: public boolean usingProxy() {
0086: return false;
0087: }
0088: };
0089: }
0090: }
0091:
0092: private static int port;
0093:
0094: static String getContentType(String fileName) throws IOException {
0095: String resourceName = "org/apache/harmony/luni/tests/"
0096: + fileName;
0097: URL url = ClassLoader.getSystemClassLoader().getResource(
0098: resourceName);
0099: assertNotNull("Cannot find test resource " + resourceName, url);
0100: return url.openConnection().getContentType();
0101: }
0102:
0103: URL url;
0104:
0105: URLConnection uc;
0106:
0107: protected void setUp() throws Exception {
0108: url = new URL("http://localhost:" + port + "/");
0109: uc = (HttpURLConnection) url.openConnection();
0110: port = Support_Jetty.startDefaultHttpServer();
0111: }
0112:
0113: protected void tearDown() {
0114: ((HttpURLConnection) uc).disconnect();
0115: }
0116:
0117: /**
0118: * @tests java.net.URLConnection#addRequestProperty(String, String)
0119: */
0120: public void test_addRequestProperty() throws MalformedURLException,
0121: IOException {
0122:
0123: MockURLConnection u = new MockURLConnection(new URL(
0124: "http://www.apache.org"));
0125: try {
0126: // Regression for HARMONY-604
0127: u.addRequestProperty(null, "someValue");
0128: fail("Expected NullPointerException");
0129: } catch (NullPointerException e) {
0130: // expected
0131: }
0132:
0133: u.connect();
0134: try {
0135: // state of connection is checked first
0136: // so no NPE in case of null 'field' param
0137: u.addRequestProperty(null, "someValue");
0138: fail("Expected IllegalStateException");
0139: } catch (IllegalStateException e) {
0140: // expected
0141: }
0142: }
0143:
0144: /**
0145: * @tests java.net.URLConnection#addRequestProperty(java.lang.String,java.lang.String)
0146: */
0147: public void test_addRequestPropertyLjava_lang_StringLjava_lang_String()
0148: throws IOException {
0149: uc.setRequestProperty("prop", "yo");
0150: uc.setRequestProperty("prop", "yo2");
0151: assertEquals("yo2", uc.getRequestProperty("prop"));
0152: Map<String, List<String>> map = uc.getRequestProperties();
0153: List<String> props = uc.getRequestProperties().get("prop");
0154: assertEquals(1, props.size());
0155:
0156: try {
0157: // the map should be unmodifiable
0158: map.put("hi", Arrays.asList(new String[] { "bye" }));
0159: fail("could modify map");
0160: } catch (UnsupportedOperationException e) {
0161: // Expected
0162: }
0163: try {
0164: // the list should be unmodifiable
0165: props.add("hi");
0166: fail("could modify list");
0167: } catch (UnsupportedOperationException e) {
0168: // Expected
0169: }
0170:
0171: File resources = Support_Resources.createTempFolder();
0172: Support_Resources.copyFile(resources, null, "hyts_att.jar");
0173: URL fUrl1 = new URL("jar:file:" + resources.getPath()
0174: + "/hyts_att.jar!/");
0175: JarURLConnection con1 = (JarURLConnection) fUrl1
0176: .openConnection();
0177: map = con1.getRequestProperties();
0178: assertNotNull(map);
0179: assertEquals(0, map.size());
0180: try {
0181: // the map should be unmodifiable
0182: map.put("hi", Arrays.asList(new String[] { "bye" }));
0183: fail();
0184: } catch (UnsupportedOperationException e) {
0185: // Expected
0186: }
0187: }
0188:
0189: /**
0190: * @tests java.net.URLConnection#getAllowUserInteraction()
0191: */
0192: public void test_getAllowUserInteraction() {
0193: uc.setAllowUserInteraction(false);
0194: assertFalse(
0195: "getAllowUserInteraction should have returned false",
0196: uc.getAllowUserInteraction());
0197:
0198: uc.setAllowUserInteraction(true);
0199: assertTrue("getAllowUserInteraction should have returned true",
0200: uc.getAllowUserInteraction());
0201: }
0202:
0203: /**
0204: * @tests java.net.URLConnection#getContent()
0205: */
0206: public void test_getContent() throws IOException {
0207: byte[] ba = new byte[600];
0208: ((InputStream) uc.getContent()).read(ba, 0, 600);
0209: String s = new String(ba);
0210: assertTrue("Incorrect content returned", s
0211: .indexOf("Hello OneHandler") > 0);
0212: }
0213:
0214: /**
0215: * @tests java.net.URLConnection#getContent(Class[])
0216: */
0217: public void test_getContent_LjavalangClass() throws IOException {
0218: byte[] ba = new byte[600];
0219:
0220: try {
0221: ((InputStream) uc.getContent(null)).read(ba, 0, 600);
0222: fail("should throw NullPointerException");
0223: } catch (NullPointerException e) {
0224: // expected
0225: }
0226:
0227: try {
0228: ((InputStream) uc.getContent(new Class[] {})).read(ba, 0,
0229: 600);
0230: fail("should throw NullPointerException");
0231: } catch (NullPointerException e) {
0232: // expected
0233: }
0234:
0235: try {
0236: ((InputStream) uc.getContent(new Class[] { Class.class }))
0237: .read(ba, 0, 600);
0238: fail("should throw NullPointerException");
0239: } catch (NullPointerException e) {
0240: // expected
0241: }
0242: }
0243:
0244: /**
0245: * @tests java.net.URLConnection#getContentEncoding()
0246: */
0247: public void test_getContentEncoding() {
0248: // should not be known for a file
0249: assertNull("getContentEncoding failed: "
0250: + uc.getContentEncoding(), uc.getContentEncoding());
0251: }
0252:
0253: /**
0254: * @tests java.net.URLConnection#getContentLength()
0255: */
0256: public void test_getContentLength() throws IOException {
0257: assertEquals("getContentLength failed: "
0258: + uc.getContentLength(), 25, uc.getContentLength());
0259: }
0260:
0261: /**
0262: * @tests java.net.URLConnection#getContentType()
0263: */
0264: public void test_getContentType() throws IOException {
0265: // should not be known for a file
0266: assertTrue("getContentType failed: " + uc.getContentType(), uc
0267: .getContentType().contains("text/html"));
0268:
0269: File resources = Support_Resources.createTempFolder();
0270: Support_Resources.copyFile(resources, null, "Harmony.GIF");
0271: URL url = new URL("file:/" + resources.toString()
0272: + "/Harmony.GIF");
0273: URLConnection conn = url.openConnection();
0274: assertEquals("type not GIF", "image/gif", conn.getContentType());
0275: }
0276:
0277: /**
0278: * @tests java.net.URLConnection#getContentType()
0279: */
0280: public void test_getContentType_regression() throws IOException {
0281: // Regression for HARMONY-4699
0282: assertEquals(getContentType("test.rtf"), "application/rtf");
0283: assertEquals(getContentType("test.java"), "text/plain");
0284: // RI would return "content/unknown"
0285: assertEquals(getContentType("test.doc"), "application/msword");
0286: assertEquals(getContentType("test.htx"), "text/html");
0287: assertEquals(getContentType("test.xml"), "application/xml");
0288: assertEquals(getContentType("."), "text/plain");
0289: }
0290:
0291: /**
0292: * @tests java.net.URLConnection#getDate()
0293: */
0294: public void test_getDate() {
0295: // should be greater than 930000000000L which represents the past
0296: if (uc.getDate() == 0) {
0297: System.out
0298: .println("WARNING: server does not support 'Date', in test_getDate");
0299: } else {
0300: assertTrue("getDate gave wrong date: " + uc.getDate(), uc
0301: .getDate() > 930000000000L);
0302: }
0303: }
0304:
0305: /**
0306: * @tests java.net.URLConnection#getDefaultAllowUserInteraction()
0307: */
0308: public void test_getDefaultAllowUserInteraction() {
0309: boolean oldSetting = URLConnection
0310: .getDefaultAllowUserInteraction();
0311:
0312: URLConnection.setDefaultAllowUserInteraction(false);
0313: assertFalse(
0314: "getDefaultAllowUserInteraction should have returned false",
0315: URLConnection.getDefaultAllowUserInteraction());
0316:
0317: URLConnection.setDefaultAllowUserInteraction(true);
0318: assertTrue(
0319: "getDefaultAllowUserInteraction should have returned true",
0320: URLConnection.getDefaultAllowUserInteraction());
0321:
0322: URLConnection.setDefaultAllowUserInteraction(oldSetting);
0323: }
0324:
0325: /**
0326: * @tests java.net.URLConnection#getDefaultRequestProperty(java.lang.String)
0327: */
0328: @SuppressWarnings("deprecation")
0329: public void test_getDefaultRequestPropertyLjava_lang_String() {
0330: URLConnection.setDefaultRequestProperty("Shmoo", "Blah");
0331: assertNull(
0332: "setDefaultRequestProperty should have returned: null",
0333: URLConnection.getDefaultRequestProperty("Shmoo"));
0334:
0335: URLConnection.setDefaultRequestProperty("Shmoo", "Boom");
0336: assertNull(
0337: "setDefaultRequestProperty should have returned: null",
0338: URLConnection.getDefaultRequestProperty("Shmoo"));
0339:
0340: assertNull(
0341: "setDefaultRequestProperty should have returned: null",
0342: URLConnection.getDefaultRequestProperty("Kapow"));
0343:
0344: URLConnection.setDefaultRequestProperty("Shmoo", null);
0345: }
0346:
0347: /**
0348: * @tests java.net.URLConnection#getDefaultUseCaches()
0349: */
0350: public void test_getDefaultUseCaches() {
0351: boolean oldSetting = uc.getDefaultUseCaches();
0352:
0353: uc.setDefaultUseCaches(false);
0354: assertFalse("getDefaultUseCaches should have returned false",
0355: uc.getDefaultUseCaches());
0356:
0357: uc.setDefaultUseCaches(true);
0358: assertTrue("getDefaultUseCaches should have returned true", uc
0359: .getDefaultUseCaches());
0360:
0361: uc.setDefaultUseCaches(oldSetting);
0362: }
0363:
0364: /**
0365: * @tests java.net.URLConnection#getDoInput()
0366: */
0367: public void test_getDoInput() {
0368: assertTrue("Should be set to true by default", uc.getDoInput());
0369:
0370: uc.setDoInput(true);
0371: assertTrue("Should have been set to true", uc.getDoInput());
0372:
0373: uc.setDoInput(false);
0374: assertFalse("Should have been set to false", uc.getDoInput());
0375: }
0376:
0377: /**
0378: * @tests java.net.URLConnection#getDoOutput()
0379: */
0380: public void test_getDoOutput() {
0381: assertFalse("Should be set to false by default", uc
0382: .getDoOutput());
0383:
0384: uc.setDoOutput(true);
0385: assertTrue("Should have been set to true", uc.getDoOutput());
0386:
0387: uc.setDoOutput(false);
0388: assertFalse("Should have been set to false", uc.getDoOutput());
0389: }
0390:
0391: /**
0392: * @tests java.net.URLConnection#getExpiration()
0393: */
0394: public void test_getExpiration() {
0395: // should be unknown
0396: assertEquals("getExpiration returned wrong expiration", 0, uc
0397: .getExpiration());
0398: }
0399:
0400: /**
0401: * @tests java.net.URLConnection#getFileNameMap()
0402: */
0403: public void test_getFileNameMap() {
0404: // Tests for the standard MIME types -- users may override these
0405: // in their JRE
0406: FileNameMap map = URLConnection.getFileNameMap();
0407:
0408: // These types are defaulted
0409: assertEquals("text/html", map.getContentTypeFor(".htm"));
0410: assertEquals("text/html", map.getContentTypeFor(".html"));
0411: assertEquals("text/plain", map.getContentTypeFor(".text"));
0412: assertEquals("text/plain", map.getContentTypeFor(".txt"));
0413:
0414: // These types come from the properties file
0415: assertEquals("application/pdf", map.getContentTypeFor(".pdf"));
0416: assertEquals("application/zip", map.getContentTypeFor(".zip"));
0417:
0418: URLConnection.setFileNameMap(new FileNameMap() {
0419: public String getContentTypeFor(String fileName) {
0420: return "Spam!";
0421: }
0422: });
0423: try {
0424: assertEquals("Incorrect FileNameMap returned", "Spam!",
0425: URLConnection.getFileNameMap().getContentTypeFor(
0426: null));
0427: } finally {
0428: // unset the map so other tests don't fail
0429: URLConnection.setFileNameMap(null);
0430: }
0431: // RI fails since it does not support fileName that does not begin with
0432: // '.'
0433: assertEquals("image/gif", map.getContentTypeFor("gif"));
0434: }
0435:
0436: /**
0437: * @tests java.net.URLConnection#getHeaderFieldDate(java.lang.String, long)
0438: */
0439: public void test_getHeaderFieldDateLjava_lang_StringJ() {
0440:
0441: if (uc.getHeaderFieldDate("Date", 22L) == 22L) {
0442: System.out
0443: .println("WARNING: Server does not support 'Date', test_getHeaderFieldDateLjava_lang_StringJ not run");
0444: return;
0445: }
0446: assertTrue("Wrong value returned: "
0447: + uc.getHeaderFieldDate("Date", 22L), uc
0448: .getHeaderFieldDate("Date", 22L) > 930000000000L);
0449:
0450: long time = uc.getHeaderFieldDate("Last-Modified", 0);
0451: assertEquals("Wrong date: ", time,
0452: Support_Configuration.URLConnectionLastModified);
0453: }
0454:
0455: /**
0456: * @tests java.net.URLConnection#getHeaderField(int)
0457: */
0458: public void test_getHeaderFieldI() {
0459: int i = 0;
0460: String hf;
0461: boolean foundResponse = false;
0462: while ((hf = uc.getHeaderField(i++)) != null) {
0463: if (hf.equals(Support_Configuration.HomeAddressSoftware)) {
0464: foundResponse = true;
0465: }
0466: }
0467: assertTrue("Could not find header field containing \""
0468: + Support_Configuration.HomeAddressSoftware + "\"",
0469: foundResponse);
0470:
0471: i = 0;
0472: foundResponse = false;
0473: while ((hf = uc.getHeaderField(i++)) != null) {
0474: if (hf.equals(Support_Configuration.HomeAddressResponse)) {
0475: foundResponse = true;
0476: }
0477: }
0478: assertTrue("Could not find header field containing \""
0479: + Support_Configuration.HomeAddressResponse + "\"",
0480: foundResponse);
0481: }
0482:
0483: /**
0484: * @tests java.net.URLConnection#getHeaderFieldKey(int)
0485: */
0486: public void test_getHeaderFieldKeyI() {
0487: String hf;
0488: boolean foundResponse = false;
0489: for (int i = 0; i < 100; i++) {
0490: hf = uc.getHeaderFieldKey(i);
0491: if (hf != null && hf.toLowerCase().equals("content-type")) {
0492: foundResponse = true;
0493: break;
0494: }
0495: }
0496: assertTrue(
0497: "Could not find header field key containing \"content-type\"",
0498: foundResponse);
0499: }
0500:
0501: /**
0502: * @tests java.net.URLConnection#getHeaderField(java.lang.String)
0503: */
0504: public void test_getHeaderFieldLjava_lang_String() {
0505: String hf;
0506: hf = uc.getHeaderField("Content-Encoding");
0507: if (hf != null) {
0508: assertNull(
0509: "Wrong value returned for header field 'Content-Encoding': "
0510: + hf, hf);
0511: }
0512: hf = uc.getHeaderField("Content-Length");
0513: if (hf != null) {
0514: assertEquals(
0515: "Wrong value returned for header field 'Content-Length': ",
0516: "25", hf);
0517: }
0518: hf = uc.getHeaderField("Content-Type");
0519: if (hf != null) {
0520: assertTrue(
0521: "Wrong value returned for header field 'Content-Type': "
0522: + hf, hf.contains("text/html"));
0523: }
0524: hf = uc.getHeaderField("content-type");
0525: if (hf != null) {
0526: assertTrue(
0527: "Wrong value returned for header field 'content-type': "
0528: + hf, hf.contains("text/html"));
0529: }
0530: hf = uc.getHeaderField("Date");
0531: if (hf != null) {
0532: assertTrue("Wrong value returned for header field 'Date': "
0533: + hf, Integer.parseInt(hf.substring(
0534: hf.length() - 17, hf.length() - 13)) >= 1999);
0535: }
0536: hf = uc.getHeaderField("Expires");
0537: if (hf != null) {
0538: assertNull(
0539: "Wrong value returned for header field 'Expires': "
0540: + hf, hf);
0541: }
0542: hf = uc.getHeaderField("SERVER");
0543: if (hf != null) {
0544: assertTrue(
0545: "Wrong value returned for header field 'SERVER': "
0546: + hf + " (expected "
0547: + Support_Configuration.HomeAddressSoftware
0548: + ")",
0549: hf
0550: .equals(Support_Configuration.HomeAddressSoftware));
0551: }
0552: hf = uc.getHeaderField("Last-Modified");
0553: if (hf != null) {
0554: assertTrue(
0555: "Wrong value returned for header field 'Last-Modified': "
0556: + hf,
0557: hf
0558: .equals(Support_Configuration.URLConnectionLastModifiedString));
0559: }
0560: hf = uc.getHeaderField("accept-ranges");
0561: if (hf != null) {
0562: assertTrue(
0563: "Wrong value returned for header field 'accept-ranges': "
0564: + hf, hf.equals("bytes"));
0565: }
0566: hf = uc.getHeaderField("DoesNotExist");
0567: if (hf != null) {
0568: assertNull(
0569: "Wrong value returned for header field 'DoesNotExist': "
0570: + hf, hf);
0571: }
0572: }
0573:
0574: /**
0575: * @tests java.net.URLConnection#getHeaderFields()
0576: */
0577: public void test_getHeaderFields() throws IOException {
0578: try {
0579: uc.getInputStream();
0580: } catch (IOException e) {
0581: fail();
0582: }
0583:
0584: Map<String, List<String>> headers = uc.getHeaderFields();
0585: assertNotNull(headers);
0586:
0587: // content-length should always appear
0588: List<String> list = headers.get("Content-Length");
0589: if (list == null) {
0590: list = headers.get("content-length");
0591: }
0592: assertNotNull(list);
0593: String contentLength = (String) list.get(0);
0594: assertNotNull(contentLength);
0595:
0596: // there should be at least 2 headers
0597: assertTrue(headers.size() > 1);
0598: File resources = Support_Resources.createTempFolder();
0599: Support_Resources.copyFile(resources, null, "hyts_att.jar");
0600: URL fUrl1 = new URL("jar:file:" + resources.getPath()
0601: + "/hyts_att.jar!/");
0602: JarURLConnection con1 = (JarURLConnection) fUrl1
0603: .openConnection();
0604: headers = con1.getHeaderFields();
0605: assertNotNull(headers);
0606: assertEquals(0, headers.size());
0607: try {
0608: // the map should be unmodifiable
0609: headers.put("hi", Arrays.asList(new String[] { "bye" }));
0610: fail("The map should be unmodifiable");
0611: } catch (UnsupportedOperationException e) {
0612: // Expected
0613: }
0614: }
0615:
0616: /**
0617: * @tests java.net.URLConnection#getIfModifiedSince()
0618: */
0619: public void test_getIfModifiedSince() {
0620: uc.setIfModifiedSince(200);
0621: assertEquals("Returned wrong ifModifiedSince value", 200, uc
0622: .getIfModifiedSince());
0623: }
0624:
0625: /**
0626: * @tests java.net.URLConnection#getInputStream()
0627: */
0628: public void test_getInputStream() throws IOException {
0629: InputStream is = uc.getInputStream();
0630: byte[] ba = new byte[600];
0631: is.read(ba, 0, 600);
0632: is.close();
0633: String s = new String(ba);
0634: assertTrue("Incorrect input stream read", s
0635: .indexOf("Hello OneHandler") > 0);
0636:
0637: // open an non-existent file
0638: URL url = new URL("http://localhost:" + port + "/fred-zz6.txt");
0639: is = url.openStream();
0640: assertTrue("available() less than 0", is.available() >= 0);
0641: is.close();
0642:
0643: // create a server socket
0644: Support_HttpServerSocket serversocket = new Support_HttpServerSocket();
0645:
0646: // create a client connector
0647: Support_URLConnector client = new Support_URLConnector();
0648:
0649: // pass both to the HttpTest
0650: Support_HttpTests test = new Support_HttpTests(serversocket,
0651: client);
0652:
0653: // run various tests common to both HttpConnections and
0654: // HttpURLConnections
0655: test.runTests(this );
0656:
0657: // Authentication test is separate from other tests because it is only
0658: // in HttpURLConnection and not supported in HttpConnection
0659:
0660: serversocket = new Support_HttpServerSocket();
0661: Support_HttpServer server = new Support_HttpServer(
0662: serversocket, this );
0663: int p = Support_PortManager.getNextPort();
0664: server.startServer(p);
0665:
0666: // it is the Support_HttpServer's responsibility to close this
0667: // serversocket
0668: serversocket = null;
0669:
0670: final String authTestUrl = "http://localhost:"
0671: + server.getPort() + Support_HttpServer.AUTHTEST;
0672:
0673: // Authentication test
0674: // set up a very simple authenticator
0675: Authenticator.setDefault(new Authenticator() {
0676: public PasswordAuthentication getPasswordAuthentication() {
0677: return new PasswordAuthentication("test", "password"
0678: .toCharArray());
0679: }
0680: });
0681: try {
0682: client.open(authTestUrl);
0683: is = client.getInputStream();
0684: int c = is.read();
0685: while (c > 0) {
0686: c = is.read();
0687: }
0688: c = is.read();
0689: is.close();
0690: } catch (FileNotFoundException e) {
0691: fail("Error performing authentication test: " + e);
0692: }
0693:
0694: final String invalidLocation = "/missingFile.htm";
0695: final String redirectTestUrl = "http://localhost:"
0696: + server.getPort() + Support_HttpServer.REDIRECTTEST;
0697:
0698: // test redirecting to a non-existent URL on the same host
0699: try {
0700: // append the response code for the server to return
0701:
0702: client.open(redirectTestUrl + "/"
0703: + Support_HttpServer.MOVED_PERM + "-"
0704: + invalidLocation);
0705: is = client.getInputStream();
0706:
0707: int c = is.read();
0708: while (c > 0) {
0709: c = is.read();
0710: }
0711: c = is.read();
0712: is.close();
0713: fail("Incorrect data returned on redirect to non-existent file.");
0714: } catch (FileNotFoundException e) {
0715: }
0716: server.stopServer();
0717:
0718: }
0719:
0720: /**
0721: * @tests java.net.URLConnection#getLastModified()
0722: */
0723: public void test_getLastModified() {
0724: if (uc.getLastModified() == 0) {
0725: System.out
0726: .println("WARNING: Server does not support 'Last-Modified', test_getLastModified() not run");
0727: return;
0728: }
0729: assertTrue(
0730: "Returned wrong getLastModified value. Wanted: "
0731: + Support_Configuration.URLConnectionLastModified
0732: + " got: " + uc.getLastModified(),
0733: uc.getLastModified() == Support_Configuration.URLConnectionLastModified);
0734: }
0735:
0736: /**
0737: * @tests java.net.URLConnection#getOutputStream()
0738: */
0739: public void test_getOutputStream() throws Exception {
0740: int port = Support_Jetty.startDefaultServlet();
0741: try {
0742: boolean exception = false;
0743: URL test;
0744: java.net.URLConnection conn2 = null;
0745:
0746: test = new URL("http://localhost:" + port + "/");
0747: conn2 = (java.net.URLConnection) test.openConnection();
0748:
0749: try {
0750: conn2.getOutputStream();
0751: fail("should throw ProtocolException");
0752: } catch (java.net.ProtocolException e) {
0753: // correct
0754: }
0755:
0756: conn2.setDoOutput(true);
0757: conn2.getOutputStream();
0758: conn2.connect();
0759: conn2.getOutputStream();
0760:
0761: try {
0762: conn2.getInputStream();
0763: conn2.getOutputStream();
0764: fail("should throw ProtocolException");
0765: } catch (ProtocolException e) {
0766: // expected.
0767: }
0768:
0769: URL u = new URL("http://localhost:" + port + "/");
0770: java.net.HttpURLConnection conn = (java.net.HttpURLConnection) u
0771: .openConnection();
0772: conn.setDoOutput(true);
0773: conn.setRequestMethod("POST");
0774: OutputStream out = conn.getOutputStream();
0775: String posted = "this is a test";
0776: out.write(posted.getBytes());
0777: out.close();
0778: conn.getResponseCode();
0779: InputStream is = conn.getInputStream();
0780: String response = "";
0781: byte[] b = new byte[1024];
0782: int count = 0;
0783: while ((count = is.read(b)) > 0) {
0784: response += new String(b, 0, count);
0785: }
0786: assertEquals("Response to POST method invalid 1", posted,
0787: response);
0788:
0789: posted = "just a test";
0790: u = new URL("http://localhost:" + port + "/");
0791: conn = (java.net.HttpURLConnection) u.openConnection();
0792: conn.setDoOutput(true);
0793: conn.setRequestMethod("POST");
0794: conn.setRequestProperty("Content-length", String
0795: .valueOf(posted.length()));
0796: out = conn.getOutputStream();
0797: out.write(posted.getBytes());
0798: out.close();
0799: conn.getResponseCode();
0800: is = conn.getInputStream();
0801: response = "";
0802: b = new byte[1024];
0803: count = 0;
0804: while ((count = is.read(b)) > 0) {
0805: response += new String(b, 0, count);
0806: }
0807: assertTrue("Response to POST method invalid 2", response
0808: .equals(posted));
0809:
0810: posted = "just another test";
0811: u = new URL("http://localhost:" + port + "/");
0812: conn = (java.net.HttpURLConnection) u.openConnection();
0813: conn.setDoOutput(true);
0814: conn.setRequestMethod("POST");
0815: conn.setRequestProperty("Content-length", String
0816: .valueOf(posted.length()));
0817: out = conn.getOutputStream();
0818: out.write(posted.getBytes());
0819: // out.close();
0820: conn.getResponseCode();
0821: is = conn.getInputStream();
0822: response = "";
0823: b = new byte[1024];
0824: count = 0;
0825: while ((count = is.read(b)) > 0) {
0826: response += new String(b, 0, count);
0827: }
0828: assertTrue("Response to POST method invalid 3", response
0829: .equals(posted));
0830:
0831: u = new URL("http://localhost:" + port + "/");
0832: conn = (java.net.HttpURLConnection) u.openConnection();
0833: conn.setDoOutput(true);
0834: conn.setRequestMethod("POST");
0835: int result = conn.getResponseCode();
0836: assertTrue("Unexpected response code: " + result,
0837: result == 200);
0838:
0839: } finally {
0840: Support_Jetty.startDefaultServlet();
0841: }
0842: }
0843:
0844: /**
0845: * @tests java.net.URLConnection#getPermission()
0846: */
0847: public void test_getPermission() throws Exception {
0848: java.security.Permission p = uc.getPermission();
0849: assertTrue("Permission of wrong type: " + p.toString(),
0850: p instanceof java.net.SocketPermission);
0851: assertTrue("Permission has wrong name: " + p.getName(), p
0852: .getName().contains("localhost:" + port));
0853:
0854: URL fileUrl = new URL("file:myfile");
0855: Permission perm = new FilePermission("myfile", "read");
0856: Permission result = fileUrl.openConnection().getPermission();
0857: assertTrue("Wrong file: permission 1:" + perm + " , " + result,
0858: result.equals(perm));
0859:
0860: fileUrl = new URL("file:/myfile/");
0861: perm = new FilePermission("/myfile", "read");
0862: result = fileUrl.openConnection().getPermission();
0863: assertTrue("Wrong file: permission 2:" + perm + " , " + result,
0864: result.equals(perm));
0865:
0866: fileUrl = new URL("file:///host/volume/file");
0867: perm = new FilePermission("/host/volume/file", "read");
0868: result = fileUrl.openConnection().getPermission();
0869: assertTrue("Wrong file: permission 3:" + perm + " , " + result,
0870: result.equals(perm));
0871:
0872: URL httpUrl = new URL("http://home/myfile/");
0873: assertTrue("Wrong http: permission", httpUrl.openConnection()
0874: .getPermission().equals(
0875: new SocketPermission("home:80", "connect")));
0876: httpUrl = new URL("http://home2:8080/myfile/");
0877: assertTrue("Wrong http: permission", httpUrl.openConnection()
0878: .getPermission().equals(
0879: new SocketPermission("home2:8080", "connect")));
0880: URL ftpUrl = new URL("ftp://home/myfile/");
0881: assertTrue("Wrong ftp: permission", ftpUrl.openConnection()
0882: .getPermission().equals(
0883: new SocketPermission("home:21", "connect")));
0884: ftpUrl = new URL("ftp://home2:22/myfile/");
0885: assertTrue("Wrong ftp: permission", ftpUrl.openConnection()
0886: .getPermission().equals(
0887: new SocketPermission("home2:22", "connect")));
0888:
0889: URL jarUrl = new URL("jar:file:myfile!/");
0890: perm = new FilePermission("myfile", "read");
0891: result = jarUrl.openConnection().getPermission();
0892: assertTrue("Wrong jar: permission:" + perm + " , " + result,
0893: result.equals(new FilePermission("myfile", "read")));
0894: }
0895:
0896: /**
0897: * @tests java.net.URLConnection#getRequestProperties()
0898: */
0899: public void test_getRequestProperties() {
0900: uc.setRequestProperty("whatever", "you like");
0901: Map headers = uc.getRequestProperties();
0902:
0903: // content-length should always appear
0904: List header = (List) headers.get("whatever");
0905: assertNotNull(header);
0906:
0907: assertEquals("you like", header.get(0));
0908:
0909: assertTrue(headers.size() >= 1);
0910:
0911: try {
0912: // the map should be unmodifiable
0913: headers.put("hi", "bye");
0914: fail();
0915: } catch (UnsupportedOperationException e) {
0916: }
0917: try {
0918: // the list should be unmodifiable
0919: header.add("hi");
0920: fail();
0921: } catch (UnsupportedOperationException e) {
0922: }
0923:
0924: }
0925:
0926: /**
0927: * @tests java.net.URLConnection#getRequestProperties()
0928: */
0929: public void test_getRequestProperties_Exception()
0930: throws IOException {
0931: URL url = new URL("http", "test", 80, "index.html",
0932: new NewHandler());
0933: URLConnection urlCon = url.openConnection();
0934: urlCon.connect();
0935:
0936: try {
0937: urlCon.getRequestProperties();
0938: fail("should throw IllegalStateException");
0939: } catch (IllegalStateException e) {
0940: // expected
0941: }
0942: }
0943:
0944: /**
0945: * @tests java.net.URLConnection#getRequestProperty(java.lang.String)
0946: */
0947: public void test_getRequestProperty_LString_Exception()
0948: throws IOException {
0949: URL url = new URL("http", "test", 80, "index.html",
0950: new NewHandler());
0951: URLConnection urlCon = url.openConnection();
0952: urlCon.setRequestProperty("test", "testProperty");
0953: assertNull(urlCon.getRequestProperty("test"));
0954:
0955: urlCon.connect();
0956: try {
0957: urlCon.getRequestProperty("test");
0958: fail("should throw IllegalStateException");
0959: } catch (IllegalStateException e) {
0960: // expected
0961: }
0962: }
0963:
0964: /**
0965: * @tests java.net.URLConnection#getRequestProperty(java.lang.String)
0966: */
0967: public void test_getRequestPropertyLjava_lang_String() {
0968: uc.setRequestProperty("Yo", "yo");
0969: assertTrue("Wrong property returned: "
0970: + uc.getRequestProperty("Yo"), uc.getRequestProperty(
0971: "Yo").equals("yo"));
0972: assertNull("Wrong property returned: "
0973: + uc.getRequestProperty("No"), uc
0974: .getRequestProperty("No"));
0975: }
0976:
0977: /**
0978: * @tests java.net.URLConnection#getURL()
0979: */
0980: public void test_getURL() {
0981: assertTrue("Incorrect URL returned", uc.getURL().equals(url));
0982: }
0983:
0984: /**
0985: * @tests java.net.URLConnection#getUseCaches()
0986: */
0987: public void test_getUseCaches() {
0988: uc.setUseCaches(false);
0989: assertTrue("getUseCaches should have returned false", !uc
0990: .getUseCaches());
0991: uc.setUseCaches(true);
0992: assertTrue("getUseCaches should have returned true", uc
0993: .getUseCaches());
0994: }
0995:
0996: /**
0997: * @tests java.net.URLConnection#guessContentTypeFromStream(java.io.InputStream)
0998: */
0999: public void test_guessContentTypeFromStreamLjava_io_InputStream()
1000: throws IOException {
1001: String[] headers = new String[] { "<html>", "<head>",
1002: " <head ", "<body", "<BODY ", "<!DOCTYPE html",
1003: "<?xml " };
1004: String[] expected = new String[] { "text/html", "text/html",
1005: "text/html", "text/html", "text/html", "text/html",
1006: "application/xml" };
1007:
1008: String[] encodings = new String[] { "ASCII", "UTF-8",
1009: "UTF-16BE", "UTF-16LE", "UTF-32BE", "UTF-32LE" };
1010: for (int i = 0; i < headers.length; i++) {
1011: for (String enc : encodings) {
1012: InputStream is = new ByteArrayInputStream(toBOMBytes(
1013: headers[i], enc));
1014: String mime = URLConnection
1015: .guessContentTypeFromStream(is);
1016: assertEquals("checking " + headers[i] + " with " + enc,
1017: expected[i], mime);
1018: }
1019: }
1020:
1021: // Try simple case
1022: try {
1023: URLConnection.guessContentTypeFromStream(null);
1024: fail("should throw NullPointerException");
1025: } catch (NullPointerException e) {
1026: // expected
1027: }
1028:
1029: // Test magic bytes
1030: byte[][] bytes = new byte[][] { { 'P', 'K' }, { 'G', 'I' } };
1031: expected = new String[] { "application/zip", "image/gif" };
1032:
1033: for (int i = 0; i < bytes.length; i++) {
1034: InputStream is = new ByteArrayInputStream(bytes[i]);
1035: assertEquals(expected[i], URLConnection
1036: .guessContentTypeFromStream(is));
1037: }
1038: }
1039:
1040: /**
1041: * @tests java.net.URLConnection#setAllowUserInteraction(boolean)
1042: */
1043: public void test_setAllowUserInteractionZ()
1044: throws MalformedURLException {
1045: // Regression for HARMONY-72
1046: MockURLConnection u = new MockURLConnection(new URL(
1047: "http://www.apache.org"));
1048: u.connect();
1049: try {
1050: u.setAllowUserInteraction(false);
1051: fail("Assert 0: expected an IllegalStateException");
1052: } catch (IllegalStateException e) {
1053: // expected
1054: }
1055:
1056: }
1057:
1058: /**
1059: * @tests java.net.URLConnection#setConnectTimeout(int)
1060: */
1061: public void test_setConnectTimeoutI() throws Exception {
1062: URLConnection uc = new URL("http://localhost").openConnection();
1063: assertEquals(0, uc.getConnectTimeout());
1064: uc.setConnectTimeout(0);
1065: assertEquals(0, uc.getConnectTimeout());
1066: try {
1067: uc.setConnectTimeout(-100);
1068: fail("should throw IllegalArgumentException");
1069: } catch (IllegalArgumentException e) {
1070: // correct
1071: }
1072: assertEquals(0, uc.getConnectTimeout());
1073: uc.setConnectTimeout(100);
1074: assertEquals(100, uc.getConnectTimeout());
1075: try {
1076: uc.setConnectTimeout(-1);
1077: fail("should throw IllegalArgumentException");
1078: } catch (IllegalArgumentException e) {
1079: // correct
1080: }
1081: assertEquals(100, uc.getConnectTimeout());
1082: }
1083:
1084: /**
1085: * @tests java.net.URLConnection#setDefaultAllowUserInteraction(boolean)
1086: */
1087: public void test_setDefaultAllowUserInteractionZ() {
1088: assertTrue("Used to test", true);
1089: }
1090:
1091: /**
1092: * @tests java.net.URLConnection#setDefaultRequestProperty(java.lang.String,
1093: * java.lang.String)
1094: */
1095: public void test_setDefaultRequestPropertyLjava_lang_StringLjava_lang_String() {
1096: assertTrue("Used to test", true);
1097: }
1098:
1099: /**
1100: * @tests java.net.URLConnection#setDefaultUseCaches(boolean)
1101: */
1102: public void test_setDefaultUseCachesZ() {
1103: assertTrue("Used to test", true);
1104: }
1105:
1106: /**
1107: * @throws IOException
1108: * @throws MalformedURLException
1109: * @tests java.net.URLConnection#setDoInput(boolean)
1110: */
1111: public void test_setDoInputZ() throws MalformedURLException,
1112: IOException {
1113: assertTrue("Used to test", true);
1114: HttpURLConnection u = null;
1115:
1116: u = (HttpURLConnection) (new URL("http://localhost:" + port)
1117: .openConnection());
1118: u.connect();
1119:
1120: try {
1121: u.setDoInput(true);
1122: } catch (IllegalStateException e) { // expected
1123: }
1124: }
1125:
1126: /**
1127: * @throws IOException
1128: * @throws MalformedURLException
1129: * @tests java.net.URLConnection#setDoOutput(boolean)
1130: */
1131: public void test_setDoOutputZ() throws MalformedURLException,
1132: IOException {
1133: assertTrue("Used to test", true);
1134: HttpURLConnection u = null;
1135:
1136: u = (HttpURLConnection) (new URL("http://localhost:" + port)
1137: .openConnection());
1138: u.connect();
1139:
1140: try {
1141: u.setDoOutput(true);
1142: } catch (IllegalStateException e) { // expected
1143: }
1144: }
1145:
1146: /**
1147: * @throws IOException
1148: * @tests java.net.URLConnection#setFileNameMap(java.net.FileNameMap)
1149: */
1150: public void test_setFileNameMapLjava_net_FileNameMap()
1151: throws IOException {
1152: // nothing happens if set null
1153: URLConnection.setFileNameMap(null);
1154: // take no effect
1155: assertNotNull(URLConnection.getFileNameMap());
1156: }
1157:
1158: /**
1159: * @tests java.net.URLConnection#setIfModifiedSince(long)
1160: */
1161: public void test_setIfModifiedSinceJ() throws IOException {
1162: URL url = new URL("http://localhost:8080/");
1163: URLConnection connection = url.openConnection();
1164: Calendar cal = new GregorianCalendar(TimeZone
1165: .getTimeZone("GMT"));
1166: cal.clear();
1167: cal.set(2000, Calendar.MARCH, 5);
1168:
1169: long sinceTime = cal.getTime().getTime();
1170: connection.setIfModifiedSince(sinceTime);
1171: assertEquals("Wrong date set", sinceTime, connection
1172: .getIfModifiedSince());
1173:
1174: }
1175:
1176: /**
1177: * @tests java.net.URLConnection#setReadTimeout(int)
1178: */
1179: public void test_setReadTimeoutI() throws Exception {
1180: URLConnection uc = new URL("http://localhost").openConnection();
1181: assertEquals(0, uc.getReadTimeout());
1182: uc.setReadTimeout(0);
1183: assertEquals(0, uc.getReadTimeout());
1184: try {
1185: uc.setReadTimeout(-100);
1186: fail("should throw IllegalArgumentException");
1187: } catch (IllegalArgumentException e) {
1188: // correct
1189: }
1190: assertEquals(0, uc.getReadTimeout());
1191: uc.setReadTimeout(100);
1192: assertEquals(100, uc.getReadTimeout());
1193: try {
1194: uc.setReadTimeout(-1);
1195: fail("should throw IllegalArgumentException");
1196: } catch (IllegalArgumentException e) {
1197: // correct
1198: }
1199: assertEquals(100, uc.getReadTimeout());
1200: }
1201:
1202: /**
1203: * @tests java.net.URLConnection#setRequestProperty(String, String)
1204: */
1205: public void test_setRequestProperty() throws MalformedURLException,
1206: IOException {
1207:
1208: MockURLConnection u = new MockURLConnection(new URL(
1209: "http://www.apache.org"));
1210: try {
1211: u.setRequestProperty(null, "someValue");
1212: fail("Expected NullPointerException");
1213: } catch (NullPointerException e) {
1214: // expected
1215: }
1216:
1217: u.connect();
1218: try {
1219: // state of connection is checked first
1220: // so no NPE in case of null 'field' param
1221: u.setRequestProperty(null, "someValue");
1222: fail("Expected IllegalStateException");
1223: } catch (IllegalStateException e) {
1224: // expected
1225: }
1226: }
1227:
1228: /**
1229: * @tests java.net.URLConnection#setRequestProperty(java.lang.String,
1230: * java.lang.String)
1231: */
1232: public void test_setRequestPropertyLjava_lang_StringLjava_lang_String() {
1233: assertTrue("Used to test", true);
1234: }
1235:
1236: /**
1237: * @tests java.net.URLConnection#setUseCaches(boolean)
1238: */
1239: public void test_setUseCachesZ() throws MalformedURLException {
1240: // Regression for HARMONY-71
1241: MockURLConnection u = new MockURLConnection(new URL(
1242: "http://www.apache.org"));
1243: u.connect();
1244: try {
1245: u.setUseCaches(true);
1246: fail("Assert 0: expected an IllegalStateException");
1247: } catch (IllegalStateException e) {
1248: // expected
1249: }
1250: }
1251:
1252: /**
1253: * @tests java.net.URLConnection#toString()
1254: */
1255: public void test_toString() {
1256: assertTrue("Wrong toString: " + uc.toString(), uc.toString()
1257: .indexOf("URLConnection") > 0);
1258: }
1259:
1260: private byte[] toBOMBytes(String text, String enc)
1261: throws IOException {
1262: ByteArrayOutputStream bos = new ByteArrayOutputStream();
1263:
1264: if (enc.equals("UTF-8")) {
1265: bos.write(new byte[] { (byte) 0xEF, (byte) 0xBB,
1266: (byte) 0xBF });
1267: }
1268: if (enc.equals("UTF-16BE")) {
1269: bos.write(new byte[] { (byte) 0xFE, (byte) 0xFF });
1270: }
1271: if (enc.equals("UTF-16LE")) {
1272: bos.write(new byte[] { (byte) 0xFF, (byte) 0xFE });
1273: }
1274: if (enc.equals("UTF-32BE")) {
1275: bos.write(new byte[] { (byte) 0x00, (byte) 0x00,
1276: (byte) 0xFE, (byte) 0xFF });
1277: }
1278: if (enc.equals("UTF-32LE")) {
1279: bos.write(new byte[] { (byte) 0xFF, (byte) 0xFE,
1280: (byte) 0x00, (byte) 0x00 });
1281: }
1282:
1283: bos.write(text.getBytes(enc));
1284: return bos.toByteArray();
1285: }
1286: }
|