URLConnectionTest.java revision 854d06e7c3a4d8a013cc2f1bfec333f13e9f47ef
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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17package org.apache.harmony.luni.tests.java.net; 18 19import dalvik.annotation.BrokenTest; 20import dalvik.annotation.TestLevel; 21import dalvik.annotation.TestTargetClass; 22import dalvik.annotation.TestTargetNew; 23import dalvik.annotation.TestTargets; 24import junit.framework.TestCase; 25import tests.support.Support_Configuration; 26import tests.support.Support_PortManager; 27import tests.support.Support_TestWebData; 28import tests.support.Support_TestWebServer; 29import tests.support.resource.Support_Resources; 30 31import java.io.BufferedReader; 32import java.io.BufferedWriter; 33import java.io.ByteArrayInputStream; 34import java.io.ByteArrayOutputStream; 35import java.io.File; 36import java.io.FilePermission; 37import java.io.FileWriter; 38import java.io.IOException; 39import java.io.InputStream; 40import java.io.InputStreamReader; 41import java.io.OutputStream; 42import java.io.OutputStreamWriter; 43import java.net.CacheRequest; 44import java.net.CacheResponse; 45import java.net.FileNameMap; 46import java.net.HttpURLConnection; 47import java.net.JarURLConnection; 48import java.net.MalformedURLException; 49import java.net.ResponseCache; 50import java.net.SocketPermission; 51import java.net.SocketTimeoutException; 52import java.net.URI; 53import java.net.URISyntaxException; 54import java.net.URL; 55import java.net.URLConnection; 56import java.net.URLStreamHandler; 57import java.net.UnknownServiceException; 58import java.security.Permission; 59import java.text.ParseException; 60import java.util.Arrays; 61import java.util.Calendar; 62import java.util.Date; 63import java.util.GregorianCalendar; 64import java.util.List; 65import java.util.Map; 66import java.util.TimeZone; 67 68@TestTargetClass( 69 value = URLConnection.class, 70 untestedMethods = { 71 @TestTargetNew( 72 level = TestLevel.NOT_NECESSARY, 73 notes = "Default implementation returns always null according to spec.", 74 method = "getHeaderField", 75 args = {int.class} 76 ), 77 @TestTargetNew( 78 level = TestLevel.NOT_NECESSARY, 79 notes = "Default implementation returns always null according to spec.", 80 method = "getHeaderFieldKey", 81 args = {int.class} 82 ) 83 } 84) 85public class URLConnectionTest extends TestCase { 86 87 private static final String testString = "Hello World"; 88 89 private URLConnection fileURLCon; 90 91 private URL fileURL; 92 93 private JarURLConnection jarURLCon; 94 95 private URL jarURL; 96 97 private URLConnection gifURLCon; 98 99 private URL gifURL; 100 101 public boolean isGetCalled; 102 103 public boolean isPutCalled; 104 105 private Map<String, List<String>> mockHeaderMap; 106 107 private InputStream mockIs = new MockInputStream(); 108 109 public boolean isCacheWriteCalled; 110 111 public boolean isAbortCalled; 112 113 /** 114 * @tests {@link java.net.URLConnection#addRequestProperty(String, String)} 115 */ 116 @TestTargetNew( 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} 121 ) 122 public void test_addRequestProperty() throws MalformedURLException, 123 IOException { 124 125 126 MockURLConnection u = new MockURLConnection(new URL( 127 "http://www.apache.org")); 128 129 try { 130 // Regression for HARMONY-604 131 u.addRequestProperty(null, "someValue"); 132 fail("Expected NullPointerException"); 133 } catch (NullPointerException e) { 134 // expected 135 } 136 137 u.connect(); 138 try { 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) { 144 // expected 145 } 146 147 } 148 149 /** 150 * @tests {@link java.net.URLConnection#setRequestProperty(String, String)} 151 */ 152 @TestTargetNew( 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} 157 ) 158 public void test_setRequestProperty() throws MalformedURLException, 159 IOException { 160 161 MockURLConnection u = new MockURLConnection(new URL( 162 "http://www.apache.org")); 163 try { 164 u.setRequestProperty(null, "someValue"); 165 fail("Expected NullPointerException"); 166 } catch (NullPointerException e) { 167 // expected 168 } 169 170 try { 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"); 174 } 175 176 u.connect(); 177 178 try { 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) { 184 // expected 185 } 186 } 187 188 /** 189 * @tests {@link java.net.URLConnection#setUseCaches(boolean)} 190 */ 191 @TestTargetNew( 192 level = TestLevel.PARTIAL_COMPLETE, 193 notes = "Complete together with getUseCaches test.", 194 method = "setUseCaches", 195 args = {boolean.class} 196 ) 197 public void test_setUseCachesZ() throws MalformedURLException, IOException { 198 199 // Regression for HARMONY-71 200 MockURLConnection u = new MockURLConnection(new URL( 201 "http://www.apache.org")); 202 u.connect(); 203 try { 204 u.setUseCaches(true); 205 fail("Assert 0: expected an IllegalStateException"); 206 } catch (IllegalStateException e) { 207 // expected 208 } 209 } 210 211 /** 212 * @tests {@link java.net.URLConnection#setAllowUserInteraction(boolean)} 213 */ 214 @TestTargetNew( 215 level = TestLevel.PARTIAL, 216 notes = "Exceptions checked only.", 217 method = "setAllowUserInteraction", 218 args = {boolean.class} 219 ) 220 public void test_setAllowUserInteractionZ() throws MalformedURLException, 221 IOException { 222 223 // Regression for HARMONY-72 224 MockURLConnection u = new MockURLConnection(new URL( 225 "http://www.apache.org")); 226 u.connect(); 227 try { 228 u.setAllowUserInteraction(false); 229 fail("Assert 0: expected an IllegalStateException"); 230 } catch (IllegalStateException e) { 231 // expected 232 } 233 } 234 235 static class MockURLConnection extends URLConnection { 236 237 public MockURLConnection(URL url) { 238 super(url); 239 } 240 241 @Override 242 public void connect() { 243 connected = true; 244 } 245 } 246 247 static class NewHandler extends URLStreamHandler { 248 protected URLConnection openConnection(URL u) throws IOException { 249 return new HttpURLConnection(u) { 250 @Override 251 public void connect() throws IOException { 252 connected = true; 253 } 254 255 @Override 256 public void disconnect() { 257 // do nothing 258 } 259 260 @Override 261 public boolean usingProxy() { 262 return false; 263 } 264 }; 265 } 266 } 267 268 class MockCachedResponseCache extends ResponseCache { 269 270 public CacheResponse get(URI arg0, String arg1, Map arg2) 271 throws IOException { 272 if (null == arg0 || null == arg1 || null == arg2) { 273 throw new NullPointerException(); 274 } 275 isGetCalled = true; 276 return new MockCacheResponse(); 277 } 278 279 public CacheRequest put(URI arg0, URLConnection arg1) 280 throws IOException { 281 if (null == arg0 || null == arg1) { 282 throw new NullPointerException(); 283 } 284 isPutCalled = true; 285 return new MockCacheRequest(); 286 } 287 } 288 289 class MockNonCachedResponseCache extends ResponseCache { 290 291 public CacheResponse get(URI arg0, String arg1, Map arg2) 292 throws IOException { 293 isGetCalled = true; 294 return null; 295 } 296 297 public CacheRequest put(URI arg0, URLConnection arg1) 298 throws IOException { 299 isPutCalled = true; 300 return new MockCacheRequest(); 301 } 302 } 303 304 class MockCacheRequest extends CacheRequest { 305 306 public OutputStream getBody() throws IOException { 307 isCacheWriteCalled = true; 308 return new MockOutputStream(); 309 } 310 311 public void abort() { 312 isAbortCalled = true; 313 } 314 315 } 316 317 class MockInputStream extends InputStream { 318 319 public int read() throws IOException { 320 return 4711; 321 } 322 323 public int read(byte[] arg0, int arg1, int arg2) throws IOException { 324 return 1; 325 } 326 327 public int read(byte[] arg0) throws IOException { 328 return 1; 329 } 330 331 } 332 333 class MockOutputStream extends OutputStream { 334 335 public void write(int b) throws IOException { 336 isCacheWriteCalled = true; 337 } 338 339 public void write(byte[] b, int off, int len) throws IOException { 340 isCacheWriteCalled = true; 341 } 342 343 public void write(byte[] b) throws IOException { 344 isCacheWriteCalled = true; 345 } 346 } 347 348 class MockCacheResponse extends CacheResponse { 349 350 public Map<String, List<String>> getHeaders() throws IOException { 351 return mockHeaderMap; 352 } 353 354 public InputStream getBody() throws IOException { 355 return mockIs; 356 } 357 } 358 359 360 private static int port; 361 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(); 367 } 368 369 URL url; 370 371 URL url2; 372 373 URLConnection uc; 374 375 URLConnection uc2; 376 377 Support_TestWebServer server; 378 379 @Override 380 public void setUp() throws Exception { 381 super.setUp(); 382 383// ftpURL = new URL(Support_Configuration.testFTPURL); 384 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(); 392 393 fileURL = createTempHelloWorldFile(); 394 fileURLCon = fileURL.openConnection(); 395 396 jarURLCon = openJarURLConnection(); 397 jarURL = jarURLCon.getURL(); 398 399 gifURLCon = openGifURLConnection(); 400 gifURL = gifURLCon.getURL(); 401 } 402 403 @Override 404 public void tearDown()throws Exception { 405 super.tearDown(); 406 server.close(); 407 ((HttpURLConnection) uc).disconnect(); 408 ((HttpURLConnection) uc2).disconnect(); 409// if (((FtpURLConnection) ftpURLCon).getInputStream() != null) { 410// ((FtpURLConnection) ftpURLCon).getInputStream().close(); 411// } 412 } 413 414 /** 415 * @throws URISyntaxException 416 * @throws ClassNotFoundException 417 * @tests {@link java.net.URLConnection#addRequestProperty(java.lang.String,java.lang.String)} 418 */ 419 @TestTargetNew( 420 level = TestLevel.COMPLETE, 421 notes = "From harmony branch.", 422 method = "addRequestProperty", 423 args = {java.lang.String.class, java.lang.String.class} 424 ) 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()); 433 434 try { 435 // the map should be unmodifiable 436 map.put("hi", Arrays.asList(new String[] { "bye" })); 437 fail("could modify map"); 438 } catch (UnsupportedOperationException e) { 439 // Expected 440 } 441 try { 442 // the list should be unmodifiable 443 props.add("hi"); 444 fail("could modify list"); 445 } catch (UnsupportedOperationException e) { 446 // Expected 447 } 448 449 JarURLConnection con1 = openJarURLConnection(); 450 map = con1.getRequestProperties(); 451 assertNotNull(map); 452 assertEquals(0, map.size()); 453 try { 454 // the map should be unmodifiable 455 map.put("hi", Arrays.asList(new String[] { "bye" })); 456 fail(); 457 } catch (UnsupportedOperationException e) { 458 // Expected 459 } 460 } 461 462 public void testHttpPostHeaders() throws IOException { 463 String path = "/" + Math.random(); 464 HttpURLConnection connection = (HttpURLConnection) 465 new URL("http://localhost:" + port + path).openConnection(); 466 467 // post a request 468 connection.setDoOutput(true); 469 OutputStreamWriter writer 470 = new OutputStreamWriter(connection.getOutputStream()); 471 writer.write("hello"); 472 writer.flush(); 473 assertEquals(200, connection.getResponseCode()); 474 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? 482 } 483 484 /** 485 * @throws IOException 486 * @tests {@link java.net.URLConnection#getAllowUserInteraction()} 487 */ 488 @TestTargets({ 489 @TestTargetNew( 490 level = TestLevel.COMPLETE, 491 notes = "From harmony branch.", 492 method = "getAllowUserInteraction", 493 args = {} 494 ), 495 @TestTargetNew( 496 level = TestLevel.SUFFICIENT, 497 notes = "From harmony branch.", 498 method = "setAllowUserInteraction", 499 args = {boolean.class} 500 ) 501 }) 502 public void test_getAllowUserInteraction() throws IOException { 503 uc.setAllowUserInteraction(false); 504 assertFalse("getAllowUserInteraction should have returned false", uc 505 .getAllowUserInteraction()); 506 507 uc.setAllowUserInteraction(true); 508 assertTrue("getAllowUserInteraction should have returned true", uc 509 .getAllowUserInteraction()); 510 511 uc.connect(); 512 513 try { 514 uc.setAllowUserInteraction(false); 515 fail("Exception expected"); 516 } catch (IllegalStateException e) { 517 //ok 518 } 519 520 // test if setAllowUserInteraction works 521 URL serverURL = new URL("http://onearth.jpl.nasa.gov/landsat.cgi"); 522 523 // connect to server 524 URLConnection uc2 = serverURL.openConnection(); 525 HttpURLConnection conn = (HttpURLConnection) uc2; 526 uc2.setAllowUserInteraction(true); 527 528 uc2.setDoInput(true); 529 uc2.setDoOutput(true); 530 531 // get reference to stream to post to 532 OutputStream os = uc2.getOutputStream(); 533 534 InputStream in = uc2.getInputStream(); 535 536 537 int contentLength = uc2.getContentLength(); 538 String contentType = uc2.getContentType(); 539 int numBytesRead = 0; 540 int allBytesRead = 0; 541 542 byte[] buffer = new byte[4096]; 543 544 do { 545 546 numBytesRead = in.read(buffer); 547 allBytesRead += allBytesRead + numBytesRead; 548 549 } while (numBytesRead > 0); 550 551 assertTrue(allBytesRead > 0); 552 553 uc2.connect(); 554 555 numBytesRead = in.read(buffer); 556 557 assertEquals(-1, numBytesRead); 558 } 559 560 /** 561 * @throws IOException 562 * @tests {@link java.net.URLConnection#connect()} 563 */ 564 @TestTargetNew( 565 level = TestLevel.COMPLETE, 566 notes = "", 567 method = "connect", 568 args = {} 569 ) 570 public void test_connect() throws IOException { 571 572 uc.connect(); 573 ((HttpURLConnection) uc).disconnect(); 574 uc.connect(); 575 576 try { 577 uc.setDoOutput(false); 578 } catch (Exception e) { 579 // ok 580 } 581 } 582 583 /** 584 * @tests {@link java.net.URLConnection#getContent()} 585 */ 586 @TestTargetNew( 587 level = TestLevel.COMPLETE, 588 notes = "From harmony branch.", 589 method = "getContent", 590 args = {} 591 ) 592 public void test_getContent() throws IOException { 593 byte[] ba = new byte[testString.getBytes().length]; 594 String buf = null; 595 596 Object obj = fileURLCon.getContent(); 597 if (obj instanceof String) { 598 buf = (String) obj; 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); 604 buf = r.readLine(); 605 assertTrue("Incorrect content returned from fileURL: "+buf, 606 testString.equals(buf.trim())); 607 } else { 608 fail("Some unkown type is returned "+obj.toString()); 609 } 610 611 //Exception test 612 URL url = new URL("http://a/b/c/?y"); 613 URLConnection fakeCon = url.openConnection(); 614 try { 615 fakeCon.getContent(); 616 } catch (IOException e) { 617 //ok 618 } 619 620 ((HttpURLConnection) uc).disconnect(); 621 try { 622 uc.getContent(); 623 } catch (IOException e) { 624 //ok 625 } 626 627 } 628 629 /** 630 * @tests {@link java.net.URLConnection#getContent(Class[])} 631 */ 632 @TestTargetNew( 633 level = TestLevel.COMPLETE, 634 notes = "From harmony branch.", 635 method = "getContent", 636 args = {java.lang.Class[].class} 637 ) 638 public void test_getContent_LjavalangClass() throws IOException { 639 byte[] ba = new byte[600]; 640 641 fileURLCon.setDoInput(true); 642 fileURLCon.connect(); 643 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())); 649 650 String test = (String) fileURLCon.getContent(new Class[] {String.class} ); 651 assertNull(test); 652 653 //Exception test 654 ((HttpURLConnection) uc).disconnect(); 655 try { 656 uc.getContent(); 657 } catch (IOException e) { 658 //ok 659 } 660 661 try { 662 ((InputStream) fileURLCon.getContent(null)).read(ba, 0, 600); 663 fail("should throw NullPointerException"); 664 } catch (NullPointerException e) { 665 // expected 666 } 667 668 try { 669 ((InputStream) fileURLCon.getContent(new Class[] {})).read(ba, 0, 600); 670 fail("should throw NullPointerException"); 671 } catch (NullPointerException e) { 672 // expected 673 } 674 675 try { 676 ((InputStream) fileURLCon.getContent(new Class[] { Class.class })).read(ba, 677 0, 600); 678 fail("should throw NullPointerException"); 679 } catch (NullPointerException e) { 680 // expected 681 } 682 } 683 684 /** 685 * @throws IOException 686 * @tests {@link java.net.URLConnection#getContentEncoding()} 687 */ 688 @TestTargetNew( 689 level = TestLevel.COMPLETE, 690 notes = "", 691 method = "getContentEncoding", 692 args = {} 693 ) 694 @BrokenTest("Fails in CTS, passes in CoreTestRunner") 695 public void test_getContentEncoding() throws IOException { 696 // faulty setup 697 try { 698 699 fileURLCon.getContentEncoding(); 700 fail("Exception expected"); 701 } catch (Throwable e) { 702 //ok 703 } 704 705 // positive case 706 707 URL url = new URL("http://www.amazon.com/"); 708 709 URLConnection con = url.openConnection(); 710 con.setRequestProperty("Accept-Encoding", "gzip"); 711 con.connect(); 712 713 assertEquals(con.getContentEncoding(), "gzip"); 714 715 716 uc2.setRequestProperty("Accept-Encoding", "bla"); 717 uc2.connect(); 718 719 assertNull(uc2.getContentEncoding()); 720 721 } 722 723 /** 724 * @tests {@link java.net.URLConnection#getContentLength()} 725 */ 726 @TestTargetNew( 727 level = TestLevel.COMPLETE, 728 notes = "", 729 method = "getContentLength", 730 args = {} 731 ) 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()); 737 738 assertNotNull(jarURLCon.getContentLength()); 739 assertNotNull(gifURLCon.getContentLength()); 740 } 741 742 /** 743 * @tests {@link java.net.URLConnection#getContentType()} 744 */ 745 @TestTargetNew( 746 level = TestLevel.SUFFICIENT, 747 notes = "only default encoding may be tested", 748 method = "getContentType", 749 args = {} 750 ) 751 public void test_getContentType() throws IOException, MalformedURLException { 752 753 assertTrue("getContentType failed: " + fileURLCon.getContentType(), 754 fileURLCon.getContentType().contains("text/plain")); 755 756 URLConnection htmlFileCon = openHTMLFile(); 757 String contentType = htmlFileCon.getContentType(); 758 if (contentType != null) { 759 assertTrue(contentType.equalsIgnoreCase("text/html")); 760 } 761 762 763 /* 764 contentType = uc.getContentType(); 765 if (contentType != null) { 766 assertTrue(contentType.equalsIgnoreCase("text/html")); 767 } 768 769 contentType = gifURLCon.getContentType(); 770 if (contentType != null) { 771 assertTrue(contentType.equalsIgnoreCase("image/gif")); 772 } 773 */ 774 775 } 776 777 /** 778 * @tests {@link java.net.URLConnection#getDate()} 779 */ 780 @TestTargetNew( 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.", 785 method = "getDate", 786 args = {} 787 ) 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); 792 } 793 794 /** 795 * @throws IOException 796 * @tests {@link java.net.URLConnection#getDefaultAllowUserInteraction()} 797 */ 798 @TestTargets({ 799 @TestTargetNew( 800 level = TestLevel.COMPLETE, 801 notes = "From harmony branch.", 802 method = "getDefaultAllowUserInteraction", 803 args = {} 804 ), 805 @TestTargetNew( 806 level = TestLevel.COMPLETE, 807 notes = "From harmony branch.", 808 method = "setDefaultAllowUserInteraction", 809 args = {boolean.class} 810 ) 811 }) 812 public void test_getDefaultAllowUserInteraction() throws IOException { 813 boolean oldSetting = URLConnection.getDefaultAllowUserInteraction(); 814 815 URLConnection.setDefaultAllowUserInteraction(false); 816 assertFalse( 817 "getDefaultAllowUserInteraction should have returned false", 818 URLConnection.getDefaultAllowUserInteraction()); 819 820 URLConnection.setDefaultAllowUserInteraction(true); 821 assertTrue("getDefaultAllowUserInteraction should have returned true", 822 URLConnection.getDefaultAllowUserInteraction()); 823 824 URLConnection.setDefaultAllowUserInteraction(oldSetting); 825 } 826 827 /** 828 * @tests {@link java.net.URLConnection#getDefaultRequestProperty(String)} 829 */ 830 @TestTargets({ 831 @TestTargetNew( 832 level = TestLevel.COMPLETE, 833 notes = "From harmony branch.", 834 method = "getDefaultRequestProperty", 835 args = {java.lang.String.class} 836 ), 837 @TestTargetNew( 838 level = TestLevel.COMPLETE, 839 notes = "From harmony branch.", 840 method = "setDefaultRequestProperty", 841 args = {java.lang.String.class, java.lang.String.class} 842 ) 843 }) 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")); 849 850 URLConnection.setDefaultRequestProperty("Shmoo", "Boom"); 851 assertNull("setDefaultRequestProperty should have returned: null", 852 URLConnection.getDefaultRequestProperty("Shmoo")); 853 854 assertNull("setDefaultRequestProperty should have returned: null", 855 URLConnection.getDefaultRequestProperty("Kapow")); 856 857 URLConnection.setDefaultRequestProperty("Shmoo", null); 858 } 859 860 /** 861 * @throws IOException 862 * @tests {@link java.net.URLConnection#getDefaultUseCaches()} 863 */ 864 @TestTargets({ 865 @TestTargetNew( 866 level = TestLevel.COMPLETE, 867 notes = "From harmony branch.", 868 method = "getDefaultUseCaches", 869 args = {} 870 ), 871 @TestTargetNew( 872 level = TestLevel.COMPLETE, 873 notes = "From harmony branch.", 874 method = "setDefaultUseCaches", 875 args = {boolean.class} 876 ) 877 }) 878 public void test_getDefaultUseCaches_CachedRC() throws IOException { 879 boolean oldSetting = uc.getDefaultUseCaches(); 880 881 ResponseCache old = ResponseCache.getDefault(); 882 ResponseCache rc = new MockCachedResponseCache(); 883 ResponseCache.setDefault(rc); 884 885 // Recreate the connection so that we get the cache from ResponseCache. 886 uc2 = url2.openConnection(); 887 888 uc2.setUseCaches(true); 889 890 uc.setDefaultUseCaches(false); 891 892 // uc unaffected 893 assertTrue(uc.getUseCaches()); 894 // uc2 unaffected 895 assertTrue(uc2.getUseCaches()); 896 897 //test get 898 assertFalse("getDefaultUseCaches should have returned false", uc 899 .getDefaultUseCaches()); 900 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()); 905 906 // test if uc does not cache but uc2 does 907 isGetCalled = false; 908 isPutCalled = false; 909 910 // test uc 911 uc.setDoOutput(true); 912 assertFalse(isGetCalled); 913 uc.connect(); 914 assertFalse(isGetCalled); 915 assertFalse(isPutCalled); 916 OutputStream os = uc.getOutputStream(); 917 assertFalse(isPutCalled); 918 assertFalse(isGetCalled); 919 920 os.close(); 921 922 //uc2 should be unaffected 923 uc2.setDoOutput(true); 924 assertFalse(isGetCalled); 925 uc2.connect(); 926 assertTrue(isGetCalled); 927 assertFalse(isPutCalled); 928 929 uc.setDefaultUseCaches(oldSetting); 930 ResponseCache.setDefault(null); 931 } 932 933 /** 934 * @throws IOException 935 * @tests {@link java.net.URLConnection#getDoInput()} 936 */ 937 @TestTargets({ 938 @TestTargetNew( 939 level = TestLevel.COMPLETE, 940 notes = "From harmony branch.", 941 method = "getDoInput", 942 args = {} 943 ), 944 @TestTargetNew( 945 level = TestLevel.COMPLETE, 946 notes = "From harmony branch.", 947 method = "setDoInput", 948 args = {boolean.class} 949 ) 950 }) 951 public void test_getDoInput() throws IOException { 952 assertTrue("Should be set to true by default", uc.getDoInput()); 953 954 fileURLCon.setDoInput(true); 955 assertTrue("Should have been set to true", fileURLCon.getDoInput()); 956 957 uc2.setDoInput(false); 958 assertFalse("Should have been set to false", uc2.getDoInput()); 959 960 fileURLCon.connect(); 961 fileURLCon.getInputStream(); 962 963 uc2.connect(); 964 try { 965 uc2.getInputStream(); 966 } catch (Throwable e) { 967 // ok 968 } 969 970 } 971 972 /** 973 * @throws IOException 974 * @tests {@link java.net.URLConnection#getDoOutput()} 975 */ 976 @TestTargets({ 977 @TestTargetNew( 978 level = TestLevel.COMPLETE, 979 notes = "From harmony branch.", 980 method = "getDoOutput", 981 args = {} 982 ), 983 @TestTargetNew( 984 level = TestLevel.COMPLETE, 985 notes = "From harmony branch.", 986 method = "setDoOutput", 987 args = {boolean.class} 988 ) 989 }) 990 public void test_getDoOutput() throws IOException { 991 assertFalse("Should be set to false by default", uc.getDoOutput()); 992 993 uc.setDoOutput(true); 994 assertTrue("Should have been set to true", uc.getDoOutput()); 995 996 uc.connect(); 997 uc.getOutputStream(); 998 999 uc2.setDoOutput(false); 1000 assertFalse("Should have been set to false", uc2.getDoOutput()); 1001 uc2.connect(); 1002 1003 try{ 1004 uc2.getOutputStream(); 1005 } catch (Throwable e) { 1006 //ok 1007 } 1008 } 1009 1010 /** 1011 * @throws IOException 1012 * @tests {@link java.net.URLConnection#getExpiration()} 1013 */ 1014 @TestTargetNew( 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", 1020 args = {} 1021 ) 1022 public void test_getExpiration() throws IOException { 1023 1024 uc.connect(); 1025 // should be unknown 1026 assertEquals("getExpiration returned wrong expiration", 0, uc 1027 .getExpiration()); 1028 1029 uc2.connect(); 1030 assertTrue("getExpiration returned wrong expiration: " + uc2 1031 .getExpiration(), uc2.getExpiration() > 0); 1032 } 1033 1034 /** 1035 * @tests {@link java.net.URLConnection#getFileNameMap()} 1036 */ 1037 @TestTargetNew( 1038 level = TestLevel.PARTIAL, 1039 notes = "From harmony branch.", 1040 method = "getFileNameMap", 1041 args = {} 1042 ) 1043 public void test_getFileNameMap() { 1044 // Tests for the standard MIME types -- users may override these 1045 // in their JRE 1046 1047 FileNameMap mapOld = URLConnection.getFileNameMap(); 1048 1049 try { 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")); 1055 1056 // These types come from the properties file : 1057 // not black-box testing. Special tests moved to setContentType 1058 /* 1059 assertEquals("application/pdf", map.getContentTypeFor(".pdf")); 1060 assertEquals("application/zip", map.getContentTypeFor(".zip")); 1061 assertEquals("image/gif", map.getContentTypeFor("gif")); 1062 */ 1063 1064 URLConnection.setFileNameMap(new FileNameMap() { 1065 public String getContentTypeFor(String fileName) { 1066 return "Spam!"; 1067 } 1068 }); 1069 1070 assertEquals("Incorrect FileNameMap returned", "Spam!", 1071 URLConnection.getFileNameMap().getContentTypeFor(null)); 1072 } finally { 1073 // unset the map so other tests don't fail 1074 URLConnection.setFileNameMap(mapOld); 1075 } 1076 // RI fails since it does not support fileName that does not begin with 1077 // '.' 1078 1079 } 1080 1081 /** 1082 * @tests {@link java.net.URLConnection#getHeaderFieldDate(java.lang.String, long)} 1083 */ 1084 @TestTargetNew( 1085 level = TestLevel.COMPLETE, 1086 notes = "", 1087 method = "getHeaderFieldDate", 1088 args = {java.lang.String.class, long.class} 1089 ) 1090 public void test_getHeaderFieldDateLjava_lang_StringJ() { 1091 Support_TestWebData params = Support_TestWebData.testParams[0]; 1092 1093 long hf; 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); 1115 } 1116 1117 /** 1118 * @tests {@link java.net.URLConnection#getHeaderField(int)} 1119 */ 1120 @TestTargetNew( 1121 level = TestLevel.NOT_NECESSARY, 1122 notes = "not supported. Always returns null.From harmony branch.", 1123 method = "getHeaderField", 1124 args = {int.class} 1125 ) 1126 public void DISABLED_test_getHeaderFieldI() { 1127 int i = 0; 1128 String hf; 1129 boolean foundResponse = false; 1130 while ((hf = uc.getHeaderField(i++)) != null) { 1131 if (hf.equals(Support_Configuration.HomeAddressSoftware)) { 1132 foundResponse = true; 1133 } 1134 } 1135 assertTrue("Could not find header field containing \"" 1136 + Support_Configuration.HomeAddressSoftware + "\"", 1137 foundResponse); 1138 1139 i = 0; 1140 foundResponse = false; 1141 while ((hf = uc.getHeaderField(i++)) != null) { 1142 if (hf.equals(Support_Configuration.HomeAddressResponse)) { 1143 foundResponse = true; 1144 } 1145 } 1146 assertTrue("Could not find header field containing \"" 1147 + Support_Configuration.HomeAddressResponse + "\"", 1148 foundResponse); 1149 } 1150 1151 /** 1152 * @tests {@link java.net.URLConnection#getHeaderFieldKey(int)} 1153 */ 1154 @TestTargetNew( 1155 level = TestLevel.NOT_NECESSARY, 1156 notes = "Not supported. Current implementation returns always null according to spec.", 1157 method = "getHeaderFieldKey", 1158 args = {int.class} 1159 ) 1160 public void DISABLED_test_getHeaderFieldKeyI() { 1161 String hf; 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; 1167 break; 1168 } 1169 } 1170 assertTrue( 1171 "Could not find header field key containing \"content-type\"", 1172 foundResponse); 1173 } 1174 1175 /** 1176 * @throws IOException 1177 * @tests {@link java.net.URLConnection#getHeaderFieldInt(String, int)} 1178 */ 1179 @TestTargetNew( 1180 level = TestLevel.SUFFICIENT, 1181 notes = "", 1182 method = "getHeaderFieldInt", 1183 args = {java.lang.String.class, int.class} 1184 ) 1185 public void test_getHeaderFieldInt() throws IOException, ParseException { 1186 Support_TestWebData params = Support_TestWebData.testParams[1]; 1187 1188 int hf = 0; 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); 1207 1208 } 1209 1210 /** 1211 * @tests {@link java.net.URLConnection#getHeaderField(java.lang.String)} 1212 */ 1213 @TestTargetNew( 1214 level = TestLevel.COMPLETE, 1215 notes = "", 1216 method = "getHeaderField", 1217 args = {java.lang.String.class} 1218 ) 1219 public void test_getHeaderFieldLjava_lang_String() { 1220 Support_TestWebData params = Support_TestWebData.testParams[0]; 1221 1222 String hf; 1223 hf = uc.getHeaderField("Content-Encoding"); 1224 assertNull("String value returned for header field 'Content-Encoding':", 1225 hf); 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': " 1243 + hf, hf); 1244 } 1245 1246 /** 1247 * @throws URISyntaxException 1248 * @throws ClassNotFoundException 1249 * @tests {@link java.net.URLConnection#getHeaderFields()} 1250 */ 1251 @TestTargetNew( 1252 level = TestLevel.COMPLETE, 1253 notes = "", 1254 method = "getHeaderFields", 1255 args = {} 1256 ) 1257 public void test_getHeaderFields() throws IOException, ClassNotFoundException, URISyntaxException { 1258 Support_TestWebData params = Support_TestWebData.testParams[1]; 1259 1260 try { 1261 uc2.getInputStream(); 1262 } catch (IOException e) { 1263 fail("Error in test setup: "+e.getMessage()); 1264 } 1265 1266 Map<String, List<String>> headers = uc2.getHeaderFields(); 1267 assertNotNull(headers); 1268 1269 List<String> list = headers.get("content-type"); 1270 if (list == null) { 1271 list = headers.get("Content-Type"); 1272 } 1273 if (list == null) { 1274 list = headers.get("Content-type"); 1275 } 1276 1277 assertNotNull(list); 1278 String contentType = (String) list.get(0); 1279 assertEquals(params.testType, contentType); 1280 1281 // there should be at least 2 headers 1282 assertTrue("Not more than one header in URL connection", 1283 headers.size() > 1); 1284 1285 headers = jarURLCon.getHeaderFields(); 1286 assertNotNull(headers); 1287 assertEquals(0, headers.size()); 1288 1289 try { 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) { 1294 // Expected 1295 } 1296 } 1297 1298 /** 1299 * @throws IOException 1300 * @tests {@link java.net.URLConnection#getLastModified()} 1301 */ 1302 @TestTargetNew( 1303 level = TestLevel.COMPLETE, 1304 notes = "From harmony branch.", 1305 method = "getLastModified", 1306 args = {} 1307 ) 1308 public void test_getLastModified() throws IOException { 1309 1310 URL url4 = new URL(Support_Configuration.hTTPURLwLastModified); 1311 URLConnection uc4 = url4.openConnection(); 1312 1313 uc4.connect(); 1314 1315 if (uc4.getLastModified() == 0) { 1316 System.out 1317 .println("WARNING: Server does not support 'Last-Modified', test_getLastModified() not run"); 1318 return; 1319 } 1320 1321 long millis = uc4.getHeaderFieldDate("Last-Modified", 0); 1322 1323 assertEquals( 1324 "Returned wrong getLastModified value. Wanted: " 1325 + " got: " + uc4.getLastModified(), 1326 millis, uc4.getLastModified()); 1327 1328 1329 ((HttpURLConnection) uc).disconnect(); 1330 } 1331 1332 @TestTargetNew( 1333 level = TestLevel.COMPLETE, 1334 notes = "", 1335 method = "getOutputStream", 1336 args = {} 1337 ) 1338 public void test_getOutputStream() throws IOException { 1339 String posted = "this is a test"; 1340 URLConnection uc3 = new URL(Support_Configuration.hTTPURLgoogle) 1341 .openConnection(); 1342 uc3.setDoOutput(true); 1343 uc3.connect(); 1344 1345 BufferedWriter w = new BufferedWriter(new OutputStreamWriter(uc3 1346 .getOutputStream()), posted.getBytes().length); 1347 1348 w.write(posted); 1349 w.flush(); 1350 w.close(); 1351 1352 int code = ((HttpURLConnection) uc3).getResponseCode(); 1353 1354 1355 // writing to url not allowed 1356 assertEquals("Got different responseCode ", 405, code); 1357 1358 1359 // try exception testing 1360 try { 1361 fileURLCon.setDoOutput(true); 1362 fileURLCon.connect(); 1363 fileURLCon.getOutputStream(); 1364 } catch (UnknownServiceException e) { 1365 // ok cannot write to fileURL 1366 } 1367 1368 ((HttpURLConnection) uc2).disconnect(); 1369 1370 try { 1371 uc2.getOutputStream(); 1372 fail("Exception expected"); 1373 } catch (IOException e) { 1374 // ok 1375 } 1376 } 1377 1378 /** 1379 * @tests {@link java.net.URLConnection#getPermission()} 1380 */ 1381 @TestTargetNew( 1382 level = TestLevel.SUFFICIENT, 1383 notes = "From harmony branch.", 1384 method = "getPermission", 1385 args = {} 1386 ) 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)); 1393 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 1398 .equals(perm)); 1399 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 1404 .equals(perm)); 1405 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 1410 .equals(perm)); 1411 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"))); 1428 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"))); 1434 } 1435 1436 /** 1437 * @tests {@link java.net.URLConnection#getRequestProperties()} 1438 */ 1439 @TestTargetNew( 1440 level = TestLevel.PARTIAL_COMPLETE, 1441 notes = "implementation test.From harmony branch.", 1442 method = "getRequestProperties", 1443 args = {} 1444 ) 1445 public void test_getRequestProperties() { 1446 uc.setRequestProperty("whatever", "you like"); 1447 Map headers = uc.getRequestProperties(); 1448 1449 // content-length should always appear 1450 List header = (List) headers.get("whatever"); 1451 assertNotNull(header); 1452 1453 assertEquals("you like", header.get(0)); 1454 1455 assertTrue(headers.size() >= 1); 1456 1457 try { 1458 // the map should be unmodifiable 1459 headers.put("hi", "bye"); 1460 fail(); 1461 } catch (UnsupportedOperationException e) { 1462 } 1463 try { 1464 // the list should be unmodifiable 1465 header.add("hi"); 1466 fail(); 1467 } catch (UnsupportedOperationException e) { 1468 } 1469 1470 } 1471 1472 /** 1473 * @tests {@link java.net.URLConnection#getRequestProperties()} 1474 */ 1475 @TestTargetNew( 1476 level = TestLevel.COMPLETE, 1477 notes = "Exceptions checked only.From harmony branch.", 1478 method = "getRequestProperties", 1479 args = {} 1480 ) 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(); 1484 urlCon.connect(); 1485 1486 try { 1487 urlCon.getRequestProperties(); 1488 fail("should throw IllegalStateException"); 1489 } catch (IllegalStateException e) { 1490 // expected 1491 } 1492 1493 } 1494 1495 /** 1496 * @tests {@link java.net.URLConnection#getRequestProperty(java.lang.String)} 1497 */ 1498 @TestTargetNew( 1499 level = TestLevel.PARTIAL_COMPLETE, 1500 notes = "Exceptions checked only.From harmony branch.", 1501 method = "getRequestProperty", 1502 args = { String.class } 1503 ) 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")); 1509 1510 urlCon.connect(); 1511 try { 1512 urlCon.getRequestProperty("test"); 1513 fail("should throw IllegalStateException"); 1514 } catch (IllegalStateException e) { 1515 // expected 1516 } 1517 } 1518 1519 /** 1520 * @tests {@link java.net.URLConnection#getRequestProperty(java.lang.String)} 1521 */ 1522 @TestTargetNew( 1523 level = TestLevel.PARTIAL_COMPLETE, 1524 notes = "From harmony branch.", 1525 method = "getRequestProperty", 1526 args = {java.lang.String.class} 1527 ) 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")); 1534 } 1535 1536 /** 1537 * @tests {@link java.net.URLConnection#getURL()} 1538 */ 1539 @TestTargetNew( 1540 level = TestLevel.COMPLETE, 1541 notes = "Exceptions checked only -> only partially implemented. From harmony branch.", 1542 method = "getURL", 1543 args = {} 1544 ) 1545 public void test_getURL() { 1546 assertTrue("Incorrect URL returned", uc.getURL().equals(url)); 1547 } 1548 1549 /** 1550 * @throws IOException 1551 * @tests {@link java.net.URLConnection#getUseCaches()} 1552 */ 1553 @TestTargets({ 1554 @TestTargetNew( 1555 level = TestLevel.COMPLETE, 1556 notes = "Exceptions checked in setUseCaches. From harmony branch.", 1557 method = "getUseCaches", 1558 args = {} 1559 ), 1560 @TestTargetNew( 1561 level = TestLevel.PARTIAL_COMPLETE, 1562 notes = "Exceptions checked in setUseCaches. From harmony branch.", 1563 method = "setUseCaches", 1564 args = {boolean.class} 1565 ) 1566 }) 1567 public void test_getUseCaches() throws IOException { 1568 uc2.setUseCaches(false); 1569 assertTrue("getUseCaches should have returned false", !uc2 1570 .getUseCaches()); 1571 uc2.setUseCaches(true); 1572 assertTrue("getUseCaches should have returned true", uc2.getUseCaches()); 1573 1574 uc2.connect(); 1575 1576 1577 try { 1578 uc2.setUseCaches(false); 1579 fail("Exception expected"); 1580 } catch (IllegalStateException e) { 1581 //ok 1582 } 1583 1584 ((HttpURLConnection) uc2).disconnect(); 1585 1586 } 1587 1588 /** 1589 * @tests {@link java.net.URLConnection#guessContentTypeFromName(String)} 1590 */ 1591 @TestTargetNew( 1592 level = TestLevel.COMPLETE, 1593 notes = "", 1594 method = "guessContentTypeFromName", 1595 args = {java.lang.String.class} 1596 ) 1597 public void test_guessContentTypeFromName() 1598 throws IOException { 1599 1600 URLConnection htmlFileCon = openHTMLFile(); 1601 String[] expected = new String[] {"text/html", 1602 "text/plain" }; 1603 String[] resources = new String[] { 1604 htmlFileCon.getURL().toString(), 1605 fileURL.toString() 1606 }; 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], 1610 expected[i], mime); 1611 } 1612 1613 // Try simple case 1614 try { 1615 URLConnection.guessContentTypeFromStream(null); 1616 fail("should throw NullPointerException"); 1617 } catch (NullPointerException e) { 1618 // expected 1619 } 1620 } 1621 1622 /** 1623 * @tests {@link java.net.URLConnection#guessContentTypeFromStream(java.io.InputStream)} 1624 */ 1625 @TestTargetNew( 1626 level = TestLevel.COMPLETE, 1627 notes = "", 1628 method = "guessContentTypeFromStream", 1629 args = {java.io.InputStream.class} 1630 ) 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 "); 1639 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 "); 1646 1647 //"UTF-16BE", "UTF-16LE", "UTF-32BE" and 1648 //"UTF-32LE" are not supported 1649 1650 // Try simple case 1651 try { 1652 URLConnection.guessContentTypeFromStream(null); 1653 fail("should throw NullPointerException"); 1654 } catch (NullPointerException e) { 1655 // expected 1656 } 1657 /* not supported 1658 // Test magic bytes 1659 byte[][] bytes = new byte[][] { { 'P', 'K' }, { 'G', 'I' } }; 1660 expected = new String[] { "application/zip", "image/gif" }; 1661 1662 for (int i = 0; i < bytes.length; i++) { 1663 InputStream is = new ByteArrayInputStream(bytes[i]); 1664 assertEquals(expected[i], URLConnection 1665 .guessContentTypeFromStream(is)); 1666 } 1667 */ 1668 } 1669 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, 1677 expected, mime); 1678 } 1679 1680 /** 1681 * @tests {@link java.net.URLConnection#setConnectTimeout(int)} 1682 */ 1683 @TestTargets({ 1684 @TestTargetNew( 1685 level = TestLevel.COMPLETE, 1686 notes = "", 1687 method = "setConnectTimeout", 1688 args = {int.class} 1689 ), 1690 @TestTargetNew( 1691 level = TestLevel.COMPLETE, 1692 notes = "", 1693 method = "getConnectTimeout", 1694 args = {} 1695 ) 1696 }) 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()); 1702 try { 1703 uc.setConnectTimeout(-100); 1704 fail("should throw IllegalArgumentException"); 1705 } catch (IllegalArgumentException e) { 1706 // correct 1707 } 1708 assertEquals(0, uc.getConnectTimeout()); 1709 uc.setConnectTimeout(100); 1710 assertEquals(100, uc.getConnectTimeout()); 1711 try { 1712 uc.setConnectTimeout(-1); 1713 fail("should throw IllegalArgumentException"); 1714 } catch (IllegalArgumentException e) { 1715 // correct 1716 } 1717 assertEquals(100, uc.getConnectTimeout()); 1718 1719 uc2.setConnectTimeout(2); 1720 1721 try { 1722 uc2.connect(); 1723 } catch (SocketTimeoutException e) { 1724 //ok 1725 } 1726 1727 } 1728 1729 /** 1730 * @throws IOException 1731 * @tests {@link java.net.URLConnection#setFileNameMap(java.net.FileNameMap)} 1732 */ 1733 @TestTargets({ 1734 @TestTargetNew( 1735 level = TestLevel.COMPLETE, 1736 notes = "", 1737 method = "setFileNameMap", 1738 args = {java.net.FileNameMap.class} 1739 ), 1740 @TestTargetNew( 1741 level = TestLevel.COMPLETE, 1742 notes = "", 1743 method = "getFileNameMap", 1744 args = {} 1745 ) 1746 }) 1747 public void test_setFileNameMapLjava_net_FileNameMap() throws IOException { 1748 FileNameMap mapOld = URLConnection.getFileNameMap(); 1749 // nothing happens if set null 1750 URLConnection.setFileNameMap(null); 1751 // take no effect 1752 assertNotNull(URLConnection.getFileNameMap()); 1753 1754 try { 1755 URLConnection.setFileNameMap(new java.net.FileNameMap(){ 1756 public String getContentTypeFor(String fileName) { 1757 if (fileName==null || fileName.length()<1) 1758 return null; 1759 String name=fileName.toLowerCase(); 1760 String type=null; 1761 if (name.endsWith(".xml")) 1762 type="text/xml"; 1763 else if (name.endsWith(".dtd")) 1764 type="text/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")) 1770 type = "image/gif"; 1771 else 1772 type="application/unknown"; 1773 return type; 1774 } 1775 }); 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")); 1780 } finally { 1781 1782 URLConnection.setFileNameMap(mapOld); 1783 } 1784 } 1785 1786 /** 1787 * @tests {@link java.net.URLConnection#setIfModifiedSince(long)} 1788 */ 1789 @TestTargets ( { 1790 @TestTargetNew( 1791 level = TestLevel.COMPLETE, 1792 notes = "", 1793 method = "setIfModifiedSince", 1794 args = {long.class} 1795 ), 1796 @TestTargetNew( 1797 level = TestLevel.PARTIAL_COMPLETE, 1798 notes = "From harmony branch.", 1799 method = "getIfModifiedSince", 1800 args = {} 1801 ) 1802 }) 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")); 1807 cal.clear(); 1808 cal.set(2000, Calendar.MARCH, 5); 1809 1810 long sinceTime = cal.getTime().getTime(); 1811 connection.setIfModifiedSince(sinceTime); 1812 assertEquals("Wrong date set", sinceTime, connection 1813 .getIfModifiedSince()); 1814 1815 // content should be returned 1816 1817 uc2.setIfModifiedSince(sinceTime); 1818 uc2.connect(); 1819 1820 1821 assertEquals(200,((HttpURLConnection) uc2).getResponseCode()); 1822 1823 try { 1824 uc2.setIfModifiedSince(2); 1825 fail("Exception expected"); 1826 } catch (IllegalStateException e) { 1827 //ok 1828 } 1829 1830 ((HttpURLConnection) uc2).disconnect(); 1831 1832 1833 } 1834 1835 @TestTargetNew( 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", 1839 args = {} 1840 ) 1841 public void test_getIfModifiedSinceJ() throws IOException { 1842 1843 uc2.setIfModifiedSince(Calendar.getInstance().getTimeInMillis()); 1844 uc2.connect(); 1845 1846 assertEquals(200,((HttpURLConnection) uc2).getResponseCode()); 1847 1848 } 1849 1850 1851 /** 1852 * @tests {@link java.net.URLConnection#setReadTimeout(int)} 1853 */ 1854 @TestTargets({ 1855 @TestTargetNew( 1856 level = TestLevel.COMPLETE, 1857 notes = "Test for SocketTimeoutException fails: instead undocumented UnknownServiceException is thrown.", 1858 method = "setReadTimeout", 1859 args = {int.class} 1860 ), 1861 @TestTargetNew( 1862 level = TestLevel.COMPLETE, 1863 notes = "Test for SocketTimeoutException fails: instead undocumented UnknownServiceException is thrown.", 1864 method = "getReadTimeout", 1865 args = {} 1866 ) 1867 }) 1868 public void test_setReadTimeoutI() throws Exception { 1869 assertEquals(0, uc.getReadTimeout()); 1870 uc.setReadTimeout(0); 1871 assertEquals(0, uc.getReadTimeout()); 1872 try { 1873 uc.setReadTimeout(-100); 1874 fail("should throw IllegalArgumentException"); 1875 } catch (IllegalArgumentException e) { 1876 // correct 1877 } 1878 assertEquals(0, uc.getReadTimeout()); 1879 uc.setReadTimeout(100); 1880 assertEquals(100, uc.getReadTimeout()); 1881 try { 1882 uc.setReadTimeout(-1); 1883 fail("should throw IllegalArgumentException"); 1884 } catch (IllegalArgumentException e) { 1885 // correct 1886 } 1887 assertEquals(100, uc.getReadTimeout()); 1888 1889 byte[] ba = new byte[600]; 1890 1891 uc2.setReadTimeout(5); 1892 uc2.setDoInput(true); 1893 uc2.connect(); 1894 1895 try { 1896 ((InputStream) uc2.getInputStream()).read(ba, 0, 600); 1897 } catch (SocketTimeoutException e) { 1898 //ok 1899 } catch ( UnknownServiceException e) { 1900 fail(""+e.getMessage()); 1901 } 1902 } 1903 1904 /** 1905 * @tests {@link java.net.URLConnection#toString()} 1906 */ 1907 @TestTargetNew( 1908 level = TestLevel.COMPLETE, 1909 notes = "", 1910 method = "toString", 1911 args = {} 1912 ) 1913 public void test_toString() { 1914 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); 1919 } 1920 1921 @TestTargetNew( 1922 level = TestLevel.SUFFICIENT, 1923 notes = "protected constructor", 1924 method = "URLConnection", 1925 args = {java.net.URL.class} 1926 ) 1927 public void test_URLConnection() { 1928 String url = uc2.getURL().toString(); 1929 assertEquals(url2.toString(), url); 1930 } 1931 1932 @TestTargetNew( 1933 level = TestLevel.PARTIAL_COMPLETE, 1934 notes = "", 1935 method = "getInputStream", 1936 args = {} 1937 ) 1938 public void testGetInputStream() throws IOException { 1939 fileURLCon.setDoInput(true); 1940 fileURLCon.connect(); 1941 1942 BufferedReader buf = new BufferedReader(new InputStreamReader( 1943 fileURLCon.getInputStream()), testString.getBytes().length); 1944 1945 String nextline; 1946 while ((nextline = buf.readLine()) != null) { 1947 assertEquals(testString, nextline); 1948 } 1949 1950 buf.close(); 1951 1952 assertNotNull(uc.getInputStream()); 1953 1954 ((HttpURLConnection) uc2).disconnect(); 1955 1956 assertNotNull(uc2.getInputStream()); 1957 1958 } 1959 1960 @TestTargetNew( 1961 level = TestLevel.PARTIAL_COMPLETE, 1962 notes = "Verifies SecurityException.", 1963 method = "setContentHandlerFactory", 1964 args = {java.net.ContentHandlerFactory.class} 1965 ) 1966 public void test_setContentHandlerFactory() { 1967 SecurityManager sm = new SecurityManager() { 1968 1969 public void checkPermission(Permission perm) { 1970 } 1971 1972 public void checkSetFactory() { 1973 throw new SecurityException(); 1974 } 1975 }; 1976 SecurityManager old_sm = System.getSecurityManager(); 1977 System.setSecurityManager(sm); 1978 try { 1979 uc.setContentHandlerFactory(null); 1980 fail("SecurityException was not thrown."); 1981 } catch(SecurityException se) { 1982 //exception 1983 } finally { 1984 System.setSecurityManager(old_sm); 1985 } 1986 1987 } 1988 1989 private URLConnection openGifURLConnection() throws IOException { 1990 String cts = System.getProperty("java.io.tmpdir"); 1991 File tmpDir = new File(cts); 1992 Support_Resources.copyFile(tmpDir, null, "Harmony.GIF"); 1993 URL fUrl1 = new URL("file:/" + tmpDir.getPath() 1994 + "/Harmony.GIF"); 1995 URLConnection con1 = fUrl1.openConnection(); 1996 return con1; 1997 } 1998 1999 private JarURLConnection openJarURLConnection() 2000 throws MalformedURLException, IOException { 2001 String cts = System.getProperty("java.io.tmpdir"); 2002 File tmpDir = new File(cts); 2003 Support_Resources.copyFile(tmpDir, null, "hyts_att.jar"); 2004 URL fUrl1 = new URL("jar:file:" + tmpDir.getPath() 2005 + "/hyts_att.jar!/"); 2006 JarURLConnection con1 = (JarURLConnection) fUrl1.openConnection(); 2007 return con1; 2008 } 2009 2010 private URLConnection openHTMLFile() throws IOException { 2011 String cts = System.getProperty("java.io.tmpdir"); 2012 File tmpDir = new File(cts); 2013 Support_Resources.copyFile(tmpDir, null, "hyts_htmltest.html"); 2014 URL fUrl1 = new URL("file:/" + tmpDir.getPath() 2015 + "/hyts_htmltest.html"); 2016 URLConnection con1 = fUrl1.openConnection(); 2017 return con1; 2018 } 2019 2020 private URL createTempHelloWorldFile() throws MalformedURLException { 2021 // create content to read 2022 File tmpDir = new File(System.getProperty("java.io.tmpdir")); 2023 File sampleFile = null; 2024 try { 2025 if (tmpDir.isDirectory()) { 2026 sampleFile = File.createTempFile("openStreamTest", ".txt", 2027 tmpDir); 2028 sampleFile.deleteOnExit(); 2029 } else { 2030 fail("Error in test setup tmpDir does not exist"); 2031 } 2032 2033 FileWriter fstream = new FileWriter(sampleFile); 2034 BufferedWriter out = new BufferedWriter(fstream, testString.getBytes().length); 2035 out.write(testString); 2036 // Close the output stream 2037 out.close(); 2038 } catch (Exception e) {// Catch exception if any 2039 fail("Error: in test setup" + e.getMessage()); 2040 } 2041 2042 // read content from file 2043 return sampleFile.toURL(); 2044 } 2045} 2046