1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.apache.harmony.luni.tests.java.net;
19 import dalvik.annotation.BrokenTest;
20 import dalvik.annotation.TestLevel;
21 import dalvik.annotation.TestTargetClass;
22 import dalvik.annotation.TestTargetNew;
23 import dalvik.annotation.TestTargets;
24 import junit.framework.TestCase;
25 import tests.support.Support_Configuration;
26 import tests.support.Support_PortManager;
27 import tests.support.Support_TestWebData;
28 import tests.support.Support_TestWebServer;
29 import tests.support.resource.Support_Resources;
31 import java.io.BufferedReader;
32 import java.io.BufferedWriter;
33 import java.io.ByteArrayInputStream;
34 import java.io.ByteArrayOutputStream;
36 import java.io.FilePermission;
37 import java.io.FileWriter;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.InputStreamReader;
41 import java.io.OutputStream;
42 import java.io.OutputStreamWriter;
43 import java.net.CacheRequest;
44 import java.net.CacheResponse;
45 import java.net.FileNameMap;
46 import java.net.HttpURLConnection;
47 import java.net.JarURLConnection;
48 import java.net.MalformedURLException;
49 import java.net.ResponseCache;
50 import java.net.SocketPermission;
51 import java.net.SocketTimeoutException;
53 import java.net.URISyntaxException;
55 import java.net.URLConnection;
56 import java.net.URLStreamHandler;
57 import java.net.UnknownServiceException;
58 import java.security.Permission;
59 import java.text.ParseException;
60 import java.util.Arrays;
61 import java.util.Calendar;
62 import java.util.Date;
63 import java.util.GregorianCalendar;
64 import java.util.List;
66 import java.util.TimeZone;
69 value = URLConnection.class,
72 level = TestLevel.NOT_NECESSARY,
73 notes = "Default implementation returns always null according to spec.",
74 method = "getHeaderField",
78 level = TestLevel.NOT_NECESSARY,
79 notes = "Default implementation returns always null according to spec.",
80 method = "getHeaderFieldKey",
85 public class URLConnectionTest extends TestCase {
87 private static final String testString = "Hello World";
89 private URLConnection fileURLCon;
93 private JarURLConnection jarURLCon;
97 private URLConnection gifURLCon;
101 public boolean isGetCalled;
103 public boolean isPutCalled;
105 private Map<String, List<String>> mockHeaderMap;
107 private InputStream mockIs = new MockInputStream();
109 public boolean isCacheWriteCalled;
111 public boolean isAbortCalled;
114 * @tests {@link java.net.URLConnection#addRequestProperty(String, String)}
117 level = TestLevel.COMPLETE,
118 notes = "Exceptions checked only. Cannot test positive test since getter method is not supported.",
119 method = "addRequestProperty",
120 args = {java.lang.String.class, java.lang.String.class}
122 public void test_addRequestProperty() throws MalformedURLException,
126 MockURLConnection u = new MockURLConnection(new URL(
127 "http://www.apache.org"));
130 // Regression for HARMONY-604
131 u.addRequestProperty(null, "someValue");
132 fail("Expected NullPointerException");
133 } catch (NullPointerException e) {
139 // state of connection is checked first
140 // so no NPE in case of null 'field' param
141 u.addRequestProperty(null, "someValue");
142 fail("Expected IllegalStateException");
143 } catch (IllegalStateException e) {
150 * @tests {@link java.net.URLConnection#setRequestProperty(String, String)}
153 level = TestLevel.PARTIAL_COMPLETE,
154 notes = "Exceptions checked only -> only partially implemented.",
155 method = "setRequestProperty",
156 args = {java.lang.String.class, java.lang.String.class}
158 public void test_setRequestProperty() throws MalformedURLException,
161 MockURLConnection u = new MockURLConnection(new URL(
162 "http://www.apache.org"));
164 u.setRequestProperty(null, "someValue");
165 fail("Expected NullPointerException");
166 } catch (NullPointerException e) {
171 u.setRequestProperty("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.0; de-DE; rv:1.7.5) Gecko/20041122 Firefox/1.0");
172 } catch (NullPointerException e) {
173 fail("Unexpected Exception");
179 // state of connection is checked first
180 // so no NPE in case of null 'field' param
181 u.setRequestProperty(null, "someValue");
182 fail("Expected IllegalStateException");
183 } catch (IllegalStateException e) {
189 * @tests {@link java.net.URLConnection#setUseCaches(boolean)}
192 level = TestLevel.PARTIAL_COMPLETE,
193 notes = "Complete together with getUseCaches test.",
194 method = "setUseCaches",
195 args = {boolean.class}
197 public void test_setUseCachesZ() throws MalformedURLException, IOException {
199 // Regression for HARMONY-71
200 MockURLConnection u = new MockURLConnection(new URL(
201 "http://www.apache.org"));
204 u.setUseCaches(true);
205 fail("Assert 0: expected an IllegalStateException");
206 } catch (IllegalStateException e) {
212 * @tests {@link java.net.URLConnection#setAllowUserInteraction(boolean)}
215 level = TestLevel.PARTIAL,
216 notes = "Exceptions checked only.",
217 method = "setAllowUserInteraction",
218 args = {boolean.class}
220 public void test_setAllowUserInteractionZ() throws MalformedURLException,
223 // Regression for HARMONY-72
224 MockURLConnection u = new MockURLConnection(new URL(
225 "http://www.apache.org"));
228 u.setAllowUserInteraction(false);
229 fail("Assert 0: expected an IllegalStateException");
230 } catch (IllegalStateException e) {
235 static class MockURLConnection extends URLConnection {
237 public MockURLConnection(URL url) {
242 public void connect() {
247 static class NewHandler extends URLStreamHandler {
248 protected URLConnection openConnection(URL u) throws IOException {
249 return new HttpURLConnection(u) {
251 public void connect() throws IOException {
256 public void disconnect() {
261 public boolean usingProxy() {
268 class MockCachedResponseCache extends ResponseCache {
270 public CacheResponse get(URI arg0, String arg1, Map arg2)
272 if (null == arg0 || null == arg1 || null == arg2) {
273 throw new NullPointerException();
276 return new MockCacheResponse();
279 public CacheRequest put(URI arg0, URLConnection arg1)
281 if (null == arg0 || null == arg1) {
282 throw new NullPointerException();
285 return new MockCacheRequest();
289 class MockNonCachedResponseCache extends ResponseCache {
291 public CacheResponse get(URI arg0, String arg1, Map arg2)
297 public CacheRequest put(URI arg0, URLConnection arg1)
300 return new MockCacheRequest();
304 class MockCacheRequest extends CacheRequest {
306 public OutputStream getBody() throws IOException {
307 isCacheWriteCalled = true;
308 return new MockOutputStream();
311 public void abort() {
312 isAbortCalled = true;
317 class MockInputStream extends InputStream {
319 public int read() throws IOException {
323 public int read(byte[] arg0, int arg1, int arg2) throws IOException {
327 public int read(byte[] arg0) throws IOException {
333 class MockOutputStream extends OutputStream {
335 public void write(int b) throws IOException {
336 isCacheWriteCalled = true;
339 public void write(byte[] b, int off, int len) throws IOException {
340 isCacheWriteCalled = true;
343 public void write(byte[] b) throws IOException {
344 isCacheWriteCalled = true;
348 class MockCacheResponse extends CacheResponse {
350 public Map<String, List<String>> getHeaders() throws IOException {
351 return mockHeaderMap;
354 public InputStream getBody() throws IOException {
360 private static int port;
362 static String getContentType(String fileName) throws IOException {
363 String resourceName = "org/apache/harmony/luni/tests/" + fileName;
364 URL url = ClassLoader.getSystemClassLoader().getResource(resourceName);
365 assertNotNull("Cannot find test resource " + resourceName, url);
366 return url.openConnection().getContentType();
377 Support_TestWebServer server;
380 public void setUp() throws Exception {
383 // ftpURL = new URL(Support_Configuration.testFTPURL);
385 port = Support_PortManager.getNextPort();
386 server = new Support_TestWebServer();
387 server.initServer(port, false);
388 url = new URL("http://localhost:" + port + "/test1");
389 uc = url.openConnection();
390 url2 = new URL("http://localhost:" + port + "/test2");
391 uc2 = url2.openConnection();
393 fileURL = createTempHelloWorldFile();
394 fileURLCon = fileURL.openConnection();
396 jarURLCon = openJarURLConnection();
397 jarURL = jarURLCon.getURL();
399 gifURLCon = openGifURLConnection();
400 gifURL = gifURLCon.getURL();
404 public void tearDown()throws Exception {
407 ((HttpURLConnection) uc).disconnect();
408 ((HttpURLConnection) uc2).disconnect();
409 // if (((FtpURLConnection) ftpURLCon).getInputStream() != null) {
410 // ((FtpURLConnection) ftpURLCon).getInputStream().close();
415 * @throws URISyntaxException
416 * @throws ClassNotFoundException
417 * @tests {@link java.net.URLConnection#addRequestProperty(java.lang.String,java.lang.String)}
420 level = TestLevel.COMPLETE,
421 notes = "From harmony branch.",
422 method = "addRequestProperty",
423 args = {java.lang.String.class, java.lang.String.class}
425 public void test_addRequestPropertyLjava_lang_StringLjava_lang_String()
426 throws IOException, ClassNotFoundException, URISyntaxException {
427 uc.setRequestProperty("prop", "yo");
428 uc.setRequestProperty("prop", "yo2");
429 assertEquals("yo2", uc.getRequestProperty("prop"));
430 Map<String, List<String>> map = uc.getRequestProperties();
431 List<String> props = uc.getRequestProperties().get("prop");
432 assertEquals(1, props.size());
435 // the map should be unmodifiable
436 map.put("hi", Arrays.asList(new String[] { "bye" }));
437 fail("could modify map");
438 } catch (UnsupportedOperationException e) {
442 // the list should be unmodifiable
444 fail("could modify list");
445 } catch (UnsupportedOperationException e) {
449 JarURLConnection con1 = openJarURLConnection();
450 map = con1.getRequestProperties();
452 assertEquals(0, map.size());
454 // the map should be unmodifiable
455 map.put("hi", Arrays.asList(new String[] { "bye" }));
457 } catch (UnsupportedOperationException e) {
462 public void testHttpPostHeaders() throws IOException {
463 String path = "/" + Math.random();
464 HttpURLConnection connection = (HttpURLConnection)
465 new URL("http://localhost:" + port + path).openConnection();
468 connection.setDoOutput(true);
469 OutputStreamWriter writer
470 = new OutputStreamWriter(connection.getOutputStream());
471 writer.write("hello");
473 assertEquals(200, connection.getResponseCode());
475 // validate the request by asking the server what was received
476 Map<String, String> headers = server.pathToRequest().get(path).getHeaders();
477 assertNull(headers.get("Accept"));
478 assertEquals("application/x-www-form-urlencoded", headers.get("Content-Type"));
479 assertEquals("5", headers.get("Content-Length"));
480 assertEquals("localhost:" + port, headers.get("Host"));
481 // TODO: test User-Agent?
485 * @throws IOException
486 * @tests {@link java.net.URLConnection#getAllowUserInteraction()}
490 level = TestLevel.COMPLETE,
491 notes = "From harmony branch.",
492 method = "getAllowUserInteraction",
496 level = TestLevel.SUFFICIENT,
497 notes = "From harmony branch.",
498 method = "setAllowUserInteraction",
499 args = {boolean.class}
502 public void test_getAllowUserInteraction() throws IOException {
503 uc.setAllowUserInteraction(false);
504 assertFalse("getAllowUserInteraction should have returned false", uc
505 .getAllowUserInteraction());
507 uc.setAllowUserInteraction(true);
508 assertTrue("getAllowUserInteraction should have returned true", uc
509 .getAllowUserInteraction());
514 uc.setAllowUserInteraction(false);
515 fail("Exception expected");
516 } catch (IllegalStateException e) {
520 // test if setAllowUserInteraction works
521 URL serverURL = new URL("http://onearth.jpl.nasa.gov/landsat.cgi");
524 URLConnection uc2 = serverURL.openConnection();
525 HttpURLConnection conn = (HttpURLConnection) uc2;
526 uc2.setAllowUserInteraction(true);
528 uc2.setDoInput(true);
529 uc2.setDoOutput(true);
531 // get reference to stream to post to
532 OutputStream os = uc2.getOutputStream();
534 InputStream in = uc2.getInputStream();
537 int contentLength = uc2.getContentLength();
538 String contentType = uc2.getContentType();
539 int numBytesRead = 0;
540 int allBytesRead = 0;
542 byte[] buffer = new byte[4096];
546 numBytesRead = in.read(buffer);
547 allBytesRead += allBytesRead + numBytesRead;
549 } while (numBytesRead > 0);
551 assertTrue(allBytesRead > 0);
555 numBytesRead = in.read(buffer);
557 assertEquals(-1, numBytesRead);
561 * @throws IOException
562 * @tests {@link java.net.URLConnection#connect()}
565 level = TestLevel.COMPLETE,
570 public void test_connect() throws IOException {
573 ((HttpURLConnection) uc).disconnect();
577 uc.setDoOutput(false);
578 } catch (Exception e) {
584 * @tests {@link java.net.URLConnection#getContent()}
587 level = TestLevel.COMPLETE,
588 notes = "From harmony branch.",
589 method = "getContent",
592 public void test_getContent() throws IOException {
593 byte[] ba = new byte[testString.getBytes().length];
596 Object obj = fileURLCon.getContent();
597 if (obj instanceof String) {
599 assertTrue("Incorrect content returned from fileURL: "+buf,
600 testString.equals(buf.trim()));
601 } else if (obj instanceof InputStream) {
602 InputStream i = (InputStream) obj;
603 BufferedReader r = new BufferedReader(new InputStreamReader(i),testString.getBytes().length);
605 assertTrue("Incorrect content returned from fileURL: "+buf,
606 testString.equals(buf.trim()));
608 fail("Some unkown type is returned "+obj.toString());
612 URL url = new URL("http://a/b/c/?y");
613 URLConnection fakeCon = url.openConnection();
615 fakeCon.getContent();
616 } catch (IOException e) {
620 ((HttpURLConnection) uc).disconnect();
623 } catch (IOException e) {
630 * @tests {@link java.net.URLConnection#getContent(Class[])}
633 level = TestLevel.COMPLETE,
634 notes = "From harmony branch.",
635 method = "getContent",
636 args = {java.lang.Class[].class}
638 public void test_getContent_LjavalangClass() throws IOException {
639 byte[] ba = new byte[600];
641 fileURLCon.setDoInput(true);
642 fileURLCon.connect();
644 InputStream helloWorld2 = (InputStream) fileURLCon.getContent(new Class[] {InputStream.class});
645 assertNotNull(helloWorld2);
646 BufferedReader r = new BufferedReader(new InputStreamReader(helloWorld2),testString.getBytes().length);
647 assertTrue("Incorrect content returned from fileURL",
648 testString.equals(r.readLine().trim()));
650 String test = (String) fileURLCon.getContent(new Class[] {String.class} );
654 ((HttpURLConnection) uc).disconnect();
657 } catch (IOException e) {
662 ((InputStream) fileURLCon.getContent(null)).read(ba, 0, 600);
663 fail("should throw NullPointerException");
664 } catch (NullPointerException e) {
669 ((InputStream) fileURLCon.getContent(new Class[] {})).read(ba, 0, 600);
670 fail("should throw NullPointerException");
671 } catch (NullPointerException e) {
676 ((InputStream) fileURLCon.getContent(new Class[] { Class.class })).read(ba,
678 fail("should throw NullPointerException");
679 } catch (NullPointerException e) {
685 * @throws IOException
686 * @tests {@link java.net.URLConnection#getContentEncoding()}
689 level = TestLevel.COMPLETE,
691 method = "getContentEncoding",
694 @BrokenTest("Fails in CTS, passes in CoreTestRunner")
695 public void test_getContentEncoding() throws IOException {
699 fileURLCon.getContentEncoding();
700 fail("Exception expected");
701 } catch (Throwable e) {
707 URL url = new URL("http://www.amazon.com/");
709 URLConnection con = url.openConnection();
710 con.setRequestProperty("Accept-Encoding", "gzip");
713 assertEquals(con.getContentEncoding(), "gzip");
716 uc2.setRequestProperty("Accept-Encoding", "bla");
719 assertNull(uc2.getContentEncoding());
724 * @tests {@link java.net.URLConnection#getContentLength()}
727 level = TestLevel.COMPLETE,
729 method = "getContentLength",
732 public void test_getContentLength() {
733 assertEquals(testString.getBytes().length,
734 fileURLCon.getContentLength());
735 assertEquals(Support_TestWebData.test1.length, uc.getContentLength());
736 assertEquals(Support_TestWebData.test2.length, uc2.getContentLength());
738 assertNotNull(jarURLCon.getContentLength());
739 assertNotNull(gifURLCon.getContentLength());
743 * @tests {@link java.net.URLConnection#getContentType()}
746 level = TestLevel.SUFFICIENT,
747 notes = "only default encoding may be tested",
748 method = "getContentType",
751 public void test_getContentType() throws IOException, MalformedURLException {
753 assertTrue("getContentType failed: " + fileURLCon.getContentType(),
754 fileURLCon.getContentType().contains("text/plain"));
756 URLConnection htmlFileCon = openHTMLFile();
757 String contentType = htmlFileCon.getContentType();
758 if (contentType != null) {
759 assertTrue(contentType.equalsIgnoreCase("text/html"));
764 contentType = uc.getContentType();
765 if (contentType != null) {
766 assertTrue(contentType.equalsIgnoreCase("text/html"));
769 contentType = gifURLCon.getContentType();
770 if (contentType != null) {
771 assertTrue(contentType.equalsIgnoreCase("image/gif"));
778 * @tests {@link java.net.URLConnection#getDate()}
781 level = TestLevel.COMPLETE,
782 notes = "From harmony branch. URLConnection.getDate crashes in cases " +
783 "where the returned expiration date doesn't seems to be " +
784 "parsable. The RI just returns 0.",
788 public void test_getDate() {
789 // should be greater than 930000000000L which represents the past
790 assertTrue("getDate gave wrong date: " + uc.getDate(),
791 uc.getDate() > 930000000000L);
795 * @throws IOException
796 * @tests {@link java.net.URLConnection#getDefaultAllowUserInteraction()}
800 level = TestLevel.COMPLETE,
801 notes = "From harmony branch.",
802 method = "getDefaultAllowUserInteraction",
806 level = TestLevel.COMPLETE,
807 notes = "From harmony branch.",
808 method = "setDefaultAllowUserInteraction",
809 args = {boolean.class}
812 public void test_getDefaultAllowUserInteraction() throws IOException {
813 boolean oldSetting = URLConnection.getDefaultAllowUserInteraction();
815 URLConnection.setDefaultAllowUserInteraction(false);
817 "getDefaultAllowUserInteraction should have returned false",
818 URLConnection.getDefaultAllowUserInteraction());
820 URLConnection.setDefaultAllowUserInteraction(true);
821 assertTrue("getDefaultAllowUserInteraction should have returned true",
822 URLConnection.getDefaultAllowUserInteraction());
824 URLConnection.setDefaultAllowUserInteraction(oldSetting);
828 * @tests {@link java.net.URLConnection#getDefaultRequestProperty(String)}
832 level = TestLevel.COMPLETE,
833 notes = "From harmony branch.",
834 method = "getDefaultRequestProperty",
835 args = {java.lang.String.class}
838 level = TestLevel.COMPLETE,
839 notes = "From harmony branch.",
840 method = "setDefaultRequestProperty",
841 args = {java.lang.String.class, java.lang.String.class}
844 @SuppressWarnings("deprecation")
845 public void test_getDefaultRequestPropertyLjava_lang_String() {
846 URLConnection.setDefaultRequestProperty("Shmoo", "Blah");
847 assertNull("setDefaultRequestProperty should have returned: null",
848 URLConnection.getDefaultRequestProperty("Shmoo"));
850 URLConnection.setDefaultRequestProperty("Shmoo", "Boom");
851 assertNull("setDefaultRequestProperty should have returned: null",
852 URLConnection.getDefaultRequestProperty("Shmoo"));
854 assertNull("setDefaultRequestProperty should have returned: null",
855 URLConnection.getDefaultRequestProperty("Kapow"));
857 URLConnection.setDefaultRequestProperty("Shmoo", null);
861 * @throws IOException
862 * @tests {@link java.net.URLConnection#getDefaultUseCaches()}
866 level = TestLevel.COMPLETE,
867 notes = "From harmony branch.",
868 method = "getDefaultUseCaches",
872 level = TestLevel.COMPLETE,
873 notes = "From harmony branch.",
874 method = "setDefaultUseCaches",
875 args = {boolean.class}
878 public void test_getDefaultUseCaches_CachedRC() throws IOException {
879 boolean oldSetting = uc.getDefaultUseCaches();
881 ResponseCache old = ResponseCache.getDefault();
882 ResponseCache rc = new MockCachedResponseCache();
883 ResponseCache.setDefault(rc);
885 // Recreate the connection so that we get the cache from ResponseCache.
886 uc2 = url2.openConnection();
888 uc2.setUseCaches(true);
890 uc.setDefaultUseCaches(false);
893 assertTrue(uc.getUseCaches());
895 assertTrue(uc2.getUseCaches());
898 assertFalse("getDefaultUseCaches should have returned false", uc
899 .getDefaultUseCaches());
901 // subsequent connections should have default value
902 URL url3 = new URL("http://localhost:" + port + "/test2");
903 URLConnection uc3 = url3.openConnection();
904 assertFalse(uc3.getUseCaches());
906 // test if uc does not cache but uc2 does
911 uc.setDoOutput(true);
912 assertFalse(isGetCalled);
914 assertFalse(isGetCalled);
915 assertFalse(isPutCalled);
916 OutputStream os = uc.getOutputStream();
917 assertFalse(isPutCalled);
918 assertFalse(isGetCalled);
922 //uc2 should be unaffected
923 uc2.setDoOutput(true);
924 assertFalse(isGetCalled);
926 assertTrue(isGetCalled);
927 assertFalse(isPutCalled);
929 uc.setDefaultUseCaches(oldSetting);
930 ResponseCache.setDefault(null);
934 * @throws IOException
935 * @tests {@link java.net.URLConnection#getDoInput()}
939 level = TestLevel.COMPLETE,
940 notes = "From harmony branch.",
941 method = "getDoInput",
945 level = TestLevel.COMPLETE,
946 notes = "From harmony branch.",
947 method = "setDoInput",
948 args = {boolean.class}
951 public void test_getDoInput() throws IOException {
952 assertTrue("Should be set to true by default", uc.getDoInput());
954 fileURLCon.setDoInput(true);
955 assertTrue("Should have been set to true", fileURLCon.getDoInput());
957 uc2.setDoInput(false);
958 assertFalse("Should have been set to false", uc2.getDoInput());
960 fileURLCon.connect();
961 fileURLCon.getInputStream();
965 uc2.getInputStream();
966 } catch (Throwable e) {
973 * @throws IOException
974 * @tests {@link java.net.URLConnection#getDoOutput()}
978 level = TestLevel.COMPLETE,
979 notes = "From harmony branch.",
980 method = "getDoOutput",
984 level = TestLevel.COMPLETE,
985 notes = "From harmony branch.",
986 method = "setDoOutput",
987 args = {boolean.class}
990 public void test_getDoOutput() throws IOException {
991 assertFalse("Should be set to false by default", uc.getDoOutput());
993 uc.setDoOutput(true);
994 assertTrue("Should have been set to true", uc.getDoOutput());
997 uc.getOutputStream();
999 uc2.setDoOutput(false);
1000 assertFalse("Should have been set to false", uc2.getDoOutput());
1004 uc2.getOutputStream();
1005 } catch (Throwable e) {
1011 * @throws IOException
1012 * @tests {@link java.net.URLConnection#getExpiration()}
1015 level = TestLevel.COMPLETE,
1016 notes = "From harmony branch. URLConnection.getExpiration crashes in " +
1017 "cases where the returned expiration date doesn't seems to " +
1018 "be parsable. The RI just returns 0.",
1019 method = "getExpiration",
1022 public void test_getExpiration() throws IOException {
1025 // should be unknown
1026 assertEquals("getExpiration returned wrong expiration", 0, uc
1030 assertTrue("getExpiration returned wrong expiration: " + uc2
1031 .getExpiration(), uc2.getExpiration() > 0);
1035 * @tests {@link java.net.URLConnection#getFileNameMap()}
1038 level = TestLevel.PARTIAL,
1039 notes = "From harmony branch.",
1040 method = "getFileNameMap",
1043 public void test_getFileNameMap() {
1044 // Tests for the standard MIME types -- users may override these
1047 FileNameMap mapOld = URLConnection.getFileNameMap();
1050 // These types are defaulted
1051 assertEquals("text/html", mapOld.getContentTypeFor(".htm"));
1052 assertEquals("text/html", mapOld.getContentTypeFor(".html"));
1053 assertEquals("text/plain", mapOld.getContentTypeFor(".text"));
1054 assertEquals("text/plain", mapOld.getContentTypeFor(".txt"));
1056 // These types come from the properties file :
1057 // not black-box testing. Special tests moved to setContentType
1059 assertEquals("application/pdf", map.getContentTypeFor(".pdf"));
1060 assertEquals("application/zip", map.getContentTypeFor(".zip"));
1061 assertEquals("image/gif", map.getContentTypeFor("gif"));
1064 URLConnection.setFileNameMap(new FileNameMap() {
1065 public String getContentTypeFor(String fileName) {
1070 assertEquals("Incorrect FileNameMap returned", "Spam!",
1071 URLConnection.getFileNameMap().getContentTypeFor(null));
1073 // unset the map so other tests don't fail
1074 URLConnection.setFileNameMap(mapOld);
1076 // RI fails since it does not support fileName that does not begin with
1082 * @tests {@link java.net.URLConnection#getHeaderFieldDate(java.lang.String, long)}
1085 level = TestLevel.COMPLETE,
1087 method = "getHeaderFieldDate",
1088 args = {java.lang.String.class, long.class}
1090 public void test_getHeaderFieldDateLjava_lang_StringJ() {
1091 Support_TestWebData params = Support_TestWebData.testParams[0];
1094 hf = uc.getHeaderFieldDate("Content-Encoding", Long.MIN_VALUE);
1095 assertEquals("Long value returned for header field 'Content-Encoding':",
1096 Long.MIN_VALUE, hf);
1097 hf = uc.getHeaderFieldDate("Content-Length", Long.MIN_VALUE);
1098 assertEquals("Long value returned for header field 'Content-Length': ",
1099 Long.MIN_VALUE, hf);
1100 hf = uc.getHeaderFieldDate("Content-Type", Long.MIN_VALUE);
1101 assertEquals("Long value returned for header field 'Content-Type': ",
1102 Long.MIN_VALUE, hf);
1103 hf = uc.getHeaderFieldDate("content-type", Long.MIN_VALUE);
1104 assertEquals("Long value returned for header field 'content-type': ",
1105 Long.MIN_VALUE, hf);
1106 hf = uc.getHeaderFieldDate("Date", Long.MIN_VALUE);
1107 assertTrue("Wrong value returned for header field 'Date': " + hf,
1108 new Date().getTime() - hf < 5000);
1109 hf = uc.getHeaderFieldDate("SERVER", Long.MIN_VALUE);
1110 assertEquals("Long value returned for header field 'SERVER': ",
1111 Long.MIN_VALUE, hf);
1112 hf = uc.getHeaderFieldDate("Last-Modified", Long.MIN_VALUE);
1113 assertEquals("Long value returned for header field 'Last-Modified': ",
1114 Long.MIN_VALUE, hf);
1118 * @tests {@link java.net.URLConnection#getHeaderField(int)}
1121 level = TestLevel.NOT_NECESSARY,
1122 notes = "not supported. Always returns null.From harmony branch.",
1123 method = "getHeaderField",
1126 public void DISABLED_test_getHeaderFieldI() {
1129 boolean foundResponse = false;
1130 while ((hf = uc.getHeaderField(i++)) != null) {
1131 if (hf.equals(Support_Configuration.HomeAddressSoftware)) {
1132 foundResponse = true;
1135 assertTrue("Could not find header field containing \""
1136 + Support_Configuration.HomeAddressSoftware + "\"",
1140 foundResponse = false;
1141 while ((hf = uc.getHeaderField(i++)) != null) {
1142 if (hf.equals(Support_Configuration.HomeAddressResponse)) {
1143 foundResponse = true;
1146 assertTrue("Could not find header field containing \""
1147 + Support_Configuration.HomeAddressResponse + "\"",
1152 * @tests {@link java.net.URLConnection#getHeaderFieldKey(int)}
1155 level = TestLevel.NOT_NECESSARY,
1156 notes = "Not supported. Current implementation returns always null according to spec.",
1157 method = "getHeaderFieldKey",
1160 public void DISABLED_test_getHeaderFieldKeyI() {
1162 boolean foundResponse = false;
1163 for (int i = 0; i < 100; i++) {
1164 hf = uc.getHeaderFieldKey(i);
1165 if (hf != null && hf.toLowerCase().equals("content-type")) {
1166 foundResponse = true;
1171 "Could not find header field key containing \"content-type\"",
1176 * @throws IOException
1177 * @tests {@link java.net.URLConnection#getHeaderFieldInt(String, int)}
1180 level = TestLevel.SUFFICIENT,
1182 method = "getHeaderFieldInt",
1183 args = {java.lang.String.class, int.class}
1185 public void test_getHeaderFieldInt() throws IOException, ParseException {
1186 Support_TestWebData params = Support_TestWebData.testParams[1];
1189 hf = uc2.getHeaderFieldInt("Content-Encoding", Integer.MIN_VALUE);
1190 assertEquals(Integer.MIN_VALUE, hf);
1191 hf = uc2.getHeaderFieldInt("Content-Length", Integer.MIN_VALUE);
1192 assertEquals(params.testLength, hf);
1193 hf = uc2.getHeaderFieldInt("Content-Type", Integer.MIN_VALUE);
1194 assertEquals(Integer.MIN_VALUE, hf);
1195 hf = uc2.getHeaderFieldInt("Date", Integer.MIN_VALUE);
1196 assertEquals(Integer.MIN_VALUE, hf);
1197 hf = uc2.getHeaderFieldInt("Expires", Integer.MIN_VALUE);
1198 assertEquals(Integer.MIN_VALUE, hf);
1199 hf = uc2.getHeaderFieldInt("SERVER", Integer.MIN_VALUE);
1200 assertEquals(Integer.MIN_VALUE, hf);
1201 hf = uc2.getHeaderFieldInt("Last-Modified", Integer.MIN_VALUE);
1202 assertEquals(Integer.MIN_VALUE, hf);
1203 hf = uc2.getHeaderFieldInt("accept-ranges", Integer.MIN_VALUE);
1204 assertEquals(Integer.MIN_VALUE, hf);
1205 hf = uc2.getHeaderFieldInt("DoesNotExist", Integer.MIN_VALUE);
1206 assertEquals(Integer.MIN_VALUE, hf);
1211 * @tests {@link java.net.URLConnection#getHeaderField(java.lang.String)}
1214 level = TestLevel.COMPLETE,
1216 method = "getHeaderField",
1217 args = {java.lang.String.class}
1219 public void test_getHeaderFieldLjava_lang_String() {
1220 Support_TestWebData params = Support_TestWebData.testParams[0];
1223 hf = uc.getHeaderField("Content-Encoding");
1224 assertNull("String value returned for header field 'Content-Encoding':",
1226 hf = uc.getHeaderField("Content-Length");
1227 assertEquals("Wrong value returned for header field 'Content-Length': ",
1228 String.valueOf(params.testLength), hf);
1229 hf = uc.getHeaderField("Content-Type");
1230 assertEquals("Wrong value returned for header field 'Content-Type': ",
1231 params.testType, hf);
1232 hf = uc.getHeaderField("content-type");
1233 assertEquals("Wrong value returned for header field 'content-type': ",
1234 params.testType, hf);
1235 hf = uc.getHeaderField("Date");
1236 assertTrue("Wrong string value returned for header field 'Date': "
1237 + hf, hf.length() > 20);
1238 hf = uc.getHeaderField("SERVER");
1239 assertEquals("Wrong value returned for header field 'SERVER': ",
1240 "TestWebServer" + port, hf);
1241 hf = uc.getHeaderField("Last-Modified");
1242 assertNull("Wrong string value returned for 'Last-Modified': "
1247 * @throws URISyntaxException
1248 * @throws ClassNotFoundException
1249 * @tests {@link java.net.URLConnection#getHeaderFields()}
1252 level = TestLevel.COMPLETE,
1254 method = "getHeaderFields",
1257 public void test_getHeaderFields() throws IOException, ClassNotFoundException, URISyntaxException {
1258 Support_TestWebData params = Support_TestWebData.testParams[1];
1261 uc2.getInputStream();
1262 } catch (IOException e) {
1263 fail("Error in test setup: "+e.getMessage());
1266 Map<String, List<String>> headers = uc2.getHeaderFields();
1267 assertNotNull(headers);
1269 List<String> list = headers.get("content-type");
1271 list = headers.get("Content-Type");
1274 list = headers.get("Content-type");
1277 assertNotNull(list);
1278 String contentType = (String) list.get(0);
1279 assertEquals(params.testType, contentType);
1281 // there should be at least 2 headers
1282 assertTrue("Not more than one header in URL connection",
1283 headers.size() > 1);
1285 headers = jarURLCon.getHeaderFields();
1286 assertNotNull(headers);
1287 assertEquals(0, headers.size());
1290 // the map should be unmodifiable
1291 headers.put("hi", Arrays.asList(new String[] { "bye" }));
1292 fail("The map should be unmodifiable");
1293 } catch (UnsupportedOperationException e) {
1299 * @throws IOException
1300 * @tests {@link java.net.URLConnection#getLastModified()}
1303 level = TestLevel.COMPLETE,
1304 notes = "From harmony branch.",
1305 method = "getLastModified",
1308 public void test_getLastModified() throws IOException {
1310 URL url4 = new URL(Support_Configuration.hTTPURLwLastModified);
1311 URLConnection uc4 = url4.openConnection();
1315 if (uc4.getLastModified() == 0) {
1317 .println("WARNING: Server does not support 'Last-Modified', test_getLastModified() not run");
1321 long millis = uc4.getHeaderFieldDate("Last-Modified", 0);
1324 "Returned wrong getLastModified value. Wanted: "
1325 + " got: " + uc4.getLastModified(),
1326 millis, uc4.getLastModified());
1329 ((HttpURLConnection) uc).disconnect();
1333 level = TestLevel.COMPLETE,
1335 method = "getOutputStream",
1338 public void test_getOutputStream() throws IOException {
1339 String posted = "this is a test";
1340 URLConnection uc3 = new URL(Support_Configuration.hTTPURLgoogle)
1342 uc3.setDoOutput(true);
1345 BufferedWriter w = new BufferedWriter(new OutputStreamWriter(uc3
1346 .getOutputStream()), posted.getBytes().length);
1352 int code = ((HttpURLConnection) uc3).getResponseCode();
1355 // writing to url not allowed
1356 assertEquals("Got different responseCode ", 405, code);
1359 // try exception testing
1361 fileURLCon.setDoOutput(true);
1362 fileURLCon.connect();
1363 fileURLCon.getOutputStream();
1364 } catch (UnknownServiceException e) {
1365 // ok cannot write to fileURL
1368 ((HttpURLConnection) uc2).disconnect();
1371 uc2.getOutputStream();
1372 fail("Exception expected");
1373 } catch (IOException e) {
1379 * @tests {@link java.net.URLConnection#getPermission()}
1382 level = TestLevel.SUFFICIENT,
1383 notes = "From harmony branch.",
1384 method = "getPermission",
1387 public void test_getPermission() throws Exception {
1388 java.security.Permission p = uc.getPermission();
1389 assertTrue("Permission of wrong type: " + p.toString(),
1390 p instanceof java.net.SocketPermission);
1391 assertTrue("Permission has wrong name: " + p.getName(), p.getName()
1392 .contains("localhost:" + port));
1394 URL fileUrl = new URL("file:myfile");
1395 Permission perm = new FilePermission("myfile", "read");
1396 Permission result = fileUrl.openConnection().getPermission();
1397 assertTrue("Wrong file: permission 1:" + perm + " , " + result, result
1400 fileUrl = new URL("file:/myfile/");
1401 perm = new FilePermission("/myfile", "read");
1402 result = fileUrl.openConnection().getPermission();
1403 assertTrue("Wrong file: permission 2:" + perm + " , " + result, result
1406 fileUrl = new URL("file:///host/volume/file");
1407 perm = new FilePermission("/host/volume/file", "read");
1408 result = fileUrl.openConnection().getPermission();
1409 assertTrue("Wrong file: permission 3:" + perm + " , " + result, result
1412 URL httpUrl = new URL("http://home/myfile/");
1413 assertTrue("Wrong http: permission", httpUrl.openConnection()
1414 .getPermission().equals(
1415 new SocketPermission("home:80", "connect")));
1416 httpUrl = new URL("http://home2:8080/myfile/");
1417 assertTrue("Wrong http: permission", httpUrl.openConnection()
1418 .getPermission().equals(
1419 new SocketPermission("home2:8080", "connect")));
1420 URL ftpUrl = new URL("ftp://home/myfile/");
1421 assertTrue("Wrong ftp: permission", ftpUrl.openConnection()
1422 .getPermission().equals(
1423 new SocketPermission("home:21", "connect")));
1424 ftpUrl = new URL("ftp://home2:22/myfile/");
1425 assertTrue("Wrong ftp: permission", ftpUrl.openConnection()
1426 .getPermission().equals(
1427 new SocketPermission("home2:22", "connect")));
1429 URL jarUrl = new URL("jar:file:myfile!/");
1430 perm = new FilePermission("myfile", "read");
1431 result = jarUrl.openConnection().getPermission();
1432 assertTrue("Wrong jar: permission:" + perm + " , " + result, result
1433 .equals(new FilePermission("myfile", "read")));
1437 * @tests {@link java.net.URLConnection#getRequestProperties()}
1440 level = TestLevel.PARTIAL_COMPLETE,
1441 notes = "implementation test.From harmony branch.",
1442 method = "getRequestProperties",
1445 public void test_getRequestProperties() {
1446 uc.setRequestProperty("whatever", "you like");
1447 Map headers = uc.getRequestProperties();
1449 // content-length should always appear
1450 List header = (List) headers.get("whatever");
1451 assertNotNull(header);
1453 assertEquals("you like", header.get(0));
1455 assertTrue(headers.size() >= 1);
1458 // the map should be unmodifiable
1459 headers.put("hi", "bye");
1461 } catch (UnsupportedOperationException e) {
1464 // the list should be unmodifiable
1467 } catch (UnsupportedOperationException e) {
1473 * @tests {@link java.net.URLConnection#getRequestProperties()}
1476 level = TestLevel.COMPLETE,
1477 notes = "Exceptions checked only.From harmony branch.",
1478 method = "getRequestProperties",
1481 public void test_getRequestProperties_Exception() throws IOException {
1482 URL url = new URL("http", "test", 80, "index.html", new NewHandler());
1483 URLConnection urlCon = url.openConnection();
1487 urlCon.getRequestProperties();
1488 fail("should throw IllegalStateException");
1489 } catch (IllegalStateException e) {
1496 * @tests {@link java.net.URLConnection#getRequestProperty(java.lang.String)}
1499 level = TestLevel.PARTIAL_COMPLETE,
1500 notes = "Exceptions checked only.From harmony branch.",
1501 method = "getRequestProperty",
1502 args = { String.class }
1504 public void test_getRequestProperty_LString_Exception() throws IOException {
1505 URL url = new URL("http", "test", 80, "index.html", new NewHandler());
1506 URLConnection urlCon = url.openConnection();
1507 urlCon.setRequestProperty("test", "testProperty");
1508 assertNull(urlCon.getRequestProperty("test"));
1512 urlCon.getRequestProperty("test");
1513 fail("should throw IllegalStateException");
1514 } catch (IllegalStateException e) {
1520 * @tests {@link java.net.URLConnection#getRequestProperty(java.lang.String)}
1523 level = TestLevel.PARTIAL_COMPLETE,
1524 notes = "From harmony branch.",
1525 method = "getRequestProperty",
1526 args = {java.lang.String.class}
1528 public void test_getRequestPropertyLjava_lang_String() {
1529 uc.setRequestProperty("Yo", "yo");
1530 assertTrue("Wrong property returned: " + uc.getRequestProperty("Yo"),
1531 uc.getRequestProperty("Yo").equals("yo"));
1532 assertNull("Wrong property returned: " + uc.getRequestProperty("No"),
1533 uc.getRequestProperty("No"));
1537 * @tests {@link java.net.URLConnection#getURL()}
1540 level = TestLevel.COMPLETE,
1541 notes = "Exceptions checked only -> only partially implemented. From harmony branch.",
1545 public void test_getURL() {
1546 assertTrue("Incorrect URL returned", uc.getURL().equals(url));
1550 * @throws IOException
1551 * @tests {@link java.net.URLConnection#getUseCaches()}
1555 level = TestLevel.COMPLETE,
1556 notes = "Exceptions checked in setUseCaches. From harmony branch.",
1557 method = "getUseCaches",
1561 level = TestLevel.PARTIAL_COMPLETE,
1562 notes = "Exceptions checked in setUseCaches. From harmony branch.",
1563 method = "setUseCaches",
1564 args = {boolean.class}
1567 public void test_getUseCaches() throws IOException {
1568 uc2.setUseCaches(false);
1569 assertTrue("getUseCaches should have returned false", !uc2
1571 uc2.setUseCaches(true);
1572 assertTrue("getUseCaches should have returned true", uc2.getUseCaches());
1578 uc2.setUseCaches(false);
1579 fail("Exception expected");
1580 } catch (IllegalStateException e) {
1584 ((HttpURLConnection) uc2).disconnect();
1589 * @tests {@link java.net.URLConnection#guessContentTypeFromName(String)}
1592 level = TestLevel.COMPLETE,
1594 method = "guessContentTypeFromName",
1595 args = {java.lang.String.class}
1597 public void test_guessContentTypeFromName()
1598 throws IOException {
1600 URLConnection htmlFileCon = openHTMLFile();
1601 String[] expected = new String[] {"text/html",
1603 String[] resources = new String[] {
1604 htmlFileCon.getURL().toString(),
1607 for (int i = 0; i < resources.length; i++) {
1608 String mime = URLConnection.guessContentTypeFromName( resources[i]);
1609 assertEquals("checking " + resources[i] + " expected " + expected[i]+"got " + expected[i],
1615 URLConnection.guessContentTypeFromStream(null);
1616 fail("should throw NullPointerException");
1617 } catch (NullPointerException e) {
1623 * @tests {@link java.net.URLConnection#guessContentTypeFromStream(java.io.InputStream)}
1626 level = TestLevel.COMPLETE,
1628 method = "guessContentTypeFromStream",
1629 args = {java.io.InputStream.class}
1631 public void test_guessContentTypeFromStreamLjava_io_InputStream()
1632 throws IOException {
1633 assertContentTypeEquals("ASCII", "text/html", "<html>");
1634 assertContentTypeEquals("ASCII", "text/html", "<head>");
1635 assertContentTypeEquals("ASCII", "text/html", "<head ");
1636 assertContentTypeEquals("ASCII", "text/html", "<body");
1637 assertContentTypeEquals("ASCII", "text/html", "<BODY ");
1638 assertContentTypeEquals("ASCII", "application/xml", "<?xml ");
1640 assertContentTypeEquals("UTF-8", "text/html", "<html>");
1641 assertContentTypeEquals("UTF-8", "text/html", "<head>");
1642 assertContentTypeEquals("UTF-8", "text/html", "<head ");
1643 assertContentTypeEquals("UTF-8", "text/html", "<body");
1644 assertContentTypeEquals("UTF-8", "text/html", "<BODY ");
1645 assertContentTypeEquals("UTF-8", "application/xml", "<?xml ");
1647 //"UTF-16BE", "UTF-16LE", "UTF-32BE" and
1648 //"UTF-32LE" are not supported
1652 URLConnection.guessContentTypeFromStream(null);
1653 fail("should throw NullPointerException");
1654 } catch (NullPointerException e) {
1659 byte[][] bytes = new byte[][] { { 'P', 'K' }, { 'G', 'I' } };
1660 expected = new String[] { "application/zip", "image/gif" };
1662 for (int i = 0; i < bytes.length; i++) {
1663 InputStream is = new ByteArrayInputStream(bytes[i]);
1664 assertEquals(expected[i], URLConnection
1665 .guessContentTypeFromStream(is));
1670 void assertContentTypeEquals(String encoding, String expected,
1671 String header) throws IOException {
1672 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1673 String encodedString = new String(header.getBytes(), encoding);
1674 InputStream is = new ByteArrayInputStream(encodedString.getBytes());
1675 String mime = URLConnection.guessContentTypeFromStream(is);
1676 assertEquals("checking '" + header + "' with " + encoding,
1681 * @tests {@link java.net.URLConnection#setConnectTimeout(int)}
1685 level = TestLevel.COMPLETE,
1687 method = "setConnectTimeout",
1691 level = TestLevel.COMPLETE,
1693 method = "getConnectTimeout",
1697 public void test_setConnectTimeoutI() throws Exception {
1698 URLConnection uc = new URL("http://localhost").openConnection();
1699 assertEquals(0, uc.getConnectTimeout());
1700 uc.setConnectTimeout(0);
1701 assertEquals(0, uc.getConnectTimeout());
1703 uc.setConnectTimeout(-100);
1704 fail("should throw IllegalArgumentException");
1705 } catch (IllegalArgumentException e) {
1708 assertEquals(0, uc.getConnectTimeout());
1709 uc.setConnectTimeout(100);
1710 assertEquals(100, uc.getConnectTimeout());
1712 uc.setConnectTimeout(-1);
1713 fail("should throw IllegalArgumentException");
1714 } catch (IllegalArgumentException e) {
1717 assertEquals(100, uc.getConnectTimeout());
1719 uc2.setConnectTimeout(2);
1723 } catch (SocketTimeoutException e) {
1730 * @throws IOException
1731 * @tests {@link java.net.URLConnection#setFileNameMap(java.net.FileNameMap)}
1735 level = TestLevel.COMPLETE,
1737 method = "setFileNameMap",
1738 args = {java.net.FileNameMap.class}
1741 level = TestLevel.COMPLETE,
1743 method = "getFileNameMap",
1747 public void test_setFileNameMapLjava_net_FileNameMap() throws IOException {
1748 FileNameMap mapOld = URLConnection.getFileNameMap();
1749 // nothing happens if set null
1750 URLConnection.setFileNameMap(null);
1752 assertNotNull(URLConnection.getFileNameMap());
1755 URLConnection.setFileNameMap(new java.net.FileNameMap(){
1756 public String getContentTypeFor(String fileName) {
1757 if (fileName==null || fileName.length()<1)
1759 String name=fileName.toLowerCase();
1761 if (name.endsWith(".xml"))
1763 else if (name.endsWith(".dtd"))
1765 else if (name.endsWith(".pdf"))
1766 type = "application/pdf";
1767 else if (name.endsWith(".zip"))
1768 type = "application/zip";
1769 else if (name.endsWith(".gif"))
1772 type="application/unknown";
1776 FileNameMap mapNew = URLConnection.getFileNameMap();
1777 assertEquals("application/pdf", mapNew.getContentTypeFor(".pdf"));
1778 assertEquals("application/zip", mapNew.getContentTypeFor(".zip"));
1779 assertEquals("image/gif", mapNew.getContentTypeFor(".gif"));
1782 URLConnection.setFileNameMap(mapOld);
1787 * @tests {@link java.net.URLConnection#setIfModifiedSince(long)}
1791 level = TestLevel.COMPLETE,
1793 method = "setIfModifiedSince",
1797 level = TestLevel.PARTIAL_COMPLETE,
1798 notes = "From harmony branch.",
1799 method = "getIfModifiedSince",
1803 public void test_setIfModifiedSinceJ() throws IOException {
1804 URL url = new URL("http://localhost:8080/");
1805 URLConnection connection = url.openConnection();
1806 Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
1808 cal.set(2000, Calendar.MARCH, 5);
1810 long sinceTime = cal.getTime().getTime();
1811 connection.setIfModifiedSince(sinceTime);
1812 assertEquals("Wrong date set", sinceTime, connection
1813 .getIfModifiedSince());
1815 // content should be returned
1817 uc2.setIfModifiedSince(sinceTime);
1821 assertEquals(200,((HttpURLConnection) uc2).getResponseCode());
1824 uc2.setIfModifiedSince(2);
1825 fail("Exception expected");
1826 } catch (IllegalStateException e) {
1830 ((HttpURLConnection) uc2).disconnect();
1836 level = TestLevel.SUFFICIENT,
1837 notes = "test that page was not renewed in time indicated -> page returned event though it should not.",
1838 method = "getIfModifiedSince",
1841 public void test_getIfModifiedSinceJ() throws IOException {
1843 uc2.setIfModifiedSince(Calendar.getInstance().getTimeInMillis());
1846 assertEquals(200,((HttpURLConnection) uc2).getResponseCode());
1852 * @tests {@link java.net.URLConnection#setReadTimeout(int)}
1856 level = TestLevel.COMPLETE,
1857 notes = "Test for SocketTimeoutException fails: instead undocumented UnknownServiceException is thrown.",
1858 method = "setReadTimeout",
1862 level = TestLevel.COMPLETE,
1863 notes = "Test for SocketTimeoutException fails: instead undocumented UnknownServiceException is thrown.",
1864 method = "getReadTimeout",
1868 public void test_setReadTimeoutI() throws Exception {
1869 assertEquals(0, uc.getReadTimeout());
1870 uc.setReadTimeout(0);
1871 assertEquals(0, uc.getReadTimeout());
1873 uc.setReadTimeout(-100);
1874 fail("should throw IllegalArgumentException");
1875 } catch (IllegalArgumentException e) {
1878 assertEquals(0, uc.getReadTimeout());
1879 uc.setReadTimeout(100);
1880 assertEquals(100, uc.getReadTimeout());
1882 uc.setReadTimeout(-1);
1883 fail("should throw IllegalArgumentException");
1884 } catch (IllegalArgumentException e) {
1887 assertEquals(100, uc.getReadTimeout());
1889 byte[] ba = new byte[600];
1891 uc2.setReadTimeout(5);
1892 uc2.setDoInput(true);
1896 ((InputStream) uc2.getInputStream()).read(ba, 0, 600);
1897 } catch (SocketTimeoutException e) {
1899 } catch ( UnknownServiceException e) {
1900 fail(""+e.getMessage());
1905 * @tests {@link java.net.URLConnection#toString()}
1908 level = TestLevel.COMPLETE,
1910 method = "toString",
1913 public void test_toString() {
1915 assertTrue("Wrong toString: " + uc.toString(), uc.toString().indexOf(
1916 "URLConnection") > 0);
1917 assertTrue("Wrong toString: " + uc.toString(), uc.toString().indexOf(
1918 uc.getURL().toString()) > 0);
1922 level = TestLevel.SUFFICIENT,
1923 notes = "protected constructor",
1924 method = "URLConnection",
1925 args = {java.net.URL.class}
1927 public void test_URLConnection() {
1928 String url = uc2.getURL().toString();
1929 assertEquals(url2.toString(), url);
1933 level = TestLevel.PARTIAL_COMPLETE,
1935 method = "getInputStream",
1938 public void testGetInputStream() throws IOException {
1939 fileURLCon.setDoInput(true);
1940 fileURLCon.connect();
1942 BufferedReader buf = new BufferedReader(new InputStreamReader(
1943 fileURLCon.getInputStream()), testString.getBytes().length);
1946 while ((nextline = buf.readLine()) != null) {
1947 assertEquals(testString, nextline);
1952 assertNotNull(uc.getInputStream());
1954 ((HttpURLConnection) uc2).disconnect();
1956 assertNotNull(uc2.getInputStream());
1960 private URLConnection openGifURLConnection() throws IOException {
1961 String cts = System.getProperty("java.io.tmpdir");
1962 File tmpDir = new File(cts);
1963 Support_Resources.copyFile(tmpDir, null, "Harmony.GIF");
1964 URL fUrl1 = new URL("file:/" + tmpDir.getPath()
1966 URLConnection con1 = fUrl1.openConnection();
1970 private JarURLConnection openJarURLConnection()
1971 throws MalformedURLException, IOException {
1972 String cts = System.getProperty("java.io.tmpdir");
1973 File tmpDir = new File(cts);
1974 Support_Resources.copyFile(tmpDir, null, "hyts_att.jar");
1975 URL fUrl1 = new URL("jar:file:" + tmpDir.getPath()
1976 + "/hyts_att.jar!/");
1977 JarURLConnection con1 = (JarURLConnection) fUrl1.openConnection();
1981 private URLConnection openHTMLFile() throws IOException {
1982 String cts = System.getProperty("java.io.tmpdir");
1983 File tmpDir = new File(cts);
1984 Support_Resources.copyFile(tmpDir, null, "hyts_htmltest.html");
1985 URL fUrl1 = new URL("file:/" + tmpDir.getPath()
1986 + "/hyts_htmltest.html");
1987 URLConnection con1 = fUrl1.openConnection();
1991 private URL createTempHelloWorldFile() throws MalformedURLException {
1992 // create content to read
1993 File tmpDir = new File(System.getProperty("java.io.tmpdir"));
1994 File sampleFile = null;
1996 if (tmpDir.isDirectory()) {
1997 sampleFile = File.createTempFile("openStreamTest", ".txt",
1999 sampleFile.deleteOnExit();
2001 fail("Error in test setup tmpDir does not exist");
2004 FileWriter fstream = new FileWriter(sampleFile);
2005 BufferedWriter out = new BufferedWriter(fstream, testString.getBytes().length);
2006 out.write(testString);
2007 // Close the output stream
2009 } catch (Exception e) {// Catch exception if any
2010 fail("Error: in test setup" + e.getMessage());
2013 // read content from file
2014 return sampleFile.toURL();