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