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 junit.framework.TestCase; 21import tests.support.Support_Configuration; 22import tests.support.Support_TestWebData; 23import tests.support.Support_TestWebServer; 24import tests.support.resource.Support_Resources; 25 26import java.io.BufferedReader; 27import java.io.BufferedWriter; 28import java.io.ByteArrayInputStream; 29import java.io.ByteArrayOutputStream; 30import java.io.File; 31import java.io.FilePermission; 32import java.io.FileWriter; 33import java.io.IOException; 34import java.io.InputStream; 35import java.io.InputStreamReader; 36import java.io.OutputStream; 37import java.io.OutputStreamWriter; 38import java.net.CacheRequest; 39import java.net.CacheResponse; 40import java.net.FileNameMap; 41import java.net.HttpURLConnection; 42import java.net.JarURLConnection; 43import java.net.MalformedURLException; 44import java.net.ResponseCache; 45import java.net.SocketPermission; 46import java.net.SocketTimeoutException; 47import java.net.URI; 48import java.net.URISyntaxException; 49import java.net.URL; 50import java.net.URLConnection; 51import java.net.URLStreamHandler; 52import java.net.UnknownServiceException; 53import java.security.Permission; 54import java.text.ParseException; 55import java.util.Arrays; 56import java.util.Calendar; 57import java.util.Date; 58import java.util.GregorianCalendar; 59import java.util.List; 60import java.util.Map; 61import java.util.TimeZone; 62 63public class URLConnectionTest extends TestCase { 64 65 private static final String testString = "Hello World"; 66 67 private URLConnection fileURLCon; 68 69 private URL fileURL; 70 71 private JarURLConnection jarURLCon; 72 73 private URLConnection gifURLCon; 74 75 /** 76 * {@link java.net.URLConnection#addRequestProperty(String, String)} 77 */ 78 public void test_addRequestProperty() throws MalformedURLException, 79 IOException { 80 81 82 MockURLConnection u = new MockURLConnection(new URL( 83 "http://www.apache.org")); 84 85 try { 86 // Regression for HARMONY-604 87 u.addRequestProperty(null, "someValue"); 88 fail("Expected NullPointerException"); 89 } catch (NullPointerException e) { 90 // expected 91 } 92 93 u.connect(); 94 try { 95 // state of connection is checked first 96 // so no NPE in case of null 'field' param 97 u.addRequestProperty(null, "someValue"); 98 fail("Expected IllegalStateException"); 99 } catch (IllegalStateException e) { 100 // expected 101 } 102 103 } 104 105 /** 106 * {@link java.net.URLConnection#setRequestProperty(String, String)} 107 */ 108 public void test_setRequestProperty() throws MalformedURLException, 109 IOException { 110 111 MockURLConnection u = new MockURLConnection(new URL( 112 "http://www.apache.org")); 113 try { 114 u.setRequestProperty(null, "someValue"); 115 fail("Expected NullPointerException"); 116 } catch (NullPointerException e) { 117 // expected 118 } 119 120 try { 121 u.setRequestProperty("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.0; de-DE; rv:1.7.5) Gecko/20041122 Firefox/1.0"); 122 } catch (NullPointerException e) { 123 fail("Unexpected Exception"); 124 } 125 126 u.connect(); 127 128 try { 129 // state of connection is checked first 130 // so no NPE in case of null 'field' param 131 u.setRequestProperty(null, "someValue"); 132 fail("Expected IllegalStateException"); 133 } catch (IllegalStateException e) { 134 // expected 135 } 136 } 137 138 /** 139 * {@link java.net.URLConnection#setUseCaches(boolean)} 140 */ 141 public void test_setUseCachesZ() throws MalformedURLException, IOException { 142 143 // Regression for HARMONY-71 144 MockURLConnection u = new MockURLConnection(new URL( 145 "http://www.apache.org")); 146 u.connect(); 147 try { 148 u.setUseCaches(true); 149 fail("Assert 0: expected an IllegalStateException"); 150 } catch (IllegalStateException e) { 151 // expected 152 } 153 } 154 155 /** 156 * {@link java.net.URLConnection#setAllowUserInteraction(boolean)} 157 */ 158 public void test_setAllowUserInteractionZ() throws MalformedURLException, 159 IOException { 160 161 // Regression for HARMONY-72 162 MockURLConnection u = new MockURLConnection(new URL( 163 "http://www.apache.org")); 164 u.connect(); 165 try { 166 u.setAllowUserInteraction(false); 167 fail("Assert 0: expected an IllegalStateException"); 168 } catch (IllegalStateException e) { 169 // expected 170 } 171 } 172 173 static class MockURLConnection extends URLConnection { 174 175 public MockURLConnection(URL url) { 176 super(url); 177 } 178 179 @Override 180 public void connect() { 181 connected = true; 182 } 183 } 184 185 static class NewHandler extends URLStreamHandler { 186 protected URLConnection openConnection(URL u) throws IOException { 187 return new HttpURLConnection(u) { 188 @Override 189 public void connect() throws IOException { 190 connected = true; 191 } 192 193 @Override 194 public void disconnect() { 195 // do nothing 196 } 197 198 @Override 199 public boolean usingProxy() { 200 return false; 201 } 202 }; 203 } 204 } 205 206 private static int port; 207 208 URL url; 209 210 URL url2; 211 212 URLConnection uc; 213 214 URLConnection uc2; 215 216 Support_TestWebServer server; 217 218 @Override 219 public void setUp() throws Exception { 220 super.setUp(); 221 222 server = new Support_TestWebServer(); 223 port = server.initServer(); 224 url = new URL("http://localhost:" + port + "/test1"); 225 uc = url.openConnection(); 226 url2 = new URL("http://localhost:" + port + "/test2"); 227 uc2 = url2.openConnection(); 228 229 fileURL = createTempHelloWorldFile(); 230 fileURLCon = fileURL.openConnection(); 231 232 jarURLCon = openJarURLConnection(); 233 gifURLCon = openGifURLConnection(); 234 } 235 236 @Override 237 public void tearDown()throws Exception { 238 super.tearDown(); 239 server.close(); 240 ((HttpURLConnection) uc).disconnect(); 241 ((HttpURLConnection) uc2).disconnect(); 242 } 243 244 /** 245 * @throws URISyntaxException 246 * @throws ClassNotFoundException 247 * {@link java.net.URLConnection#addRequestProperty(java.lang.String,java.lang.String)} 248 */ 249 public void test_addRequestPropertyLjava_lang_StringLjava_lang_String() 250 throws IOException, ClassNotFoundException, URISyntaxException { 251 uc.setRequestProperty("prop", "yo"); 252 uc.setRequestProperty("prop", "yo2"); 253 assertEquals("yo2", uc.getRequestProperty("prop")); 254 Map<String, List<String>> map = uc.getRequestProperties(); 255 List<String> props = uc.getRequestProperties().get("prop"); 256 assertEquals(1, props.size()); 257 258 try { 259 // the map should be unmodifiable 260 map.put("hi", Arrays.asList(new String[] { "bye" })); 261 fail("could modify map"); 262 } catch (UnsupportedOperationException e) { 263 // Expected 264 } 265 try { 266 // the list should be unmodifiable 267 props.add("hi"); 268 fail("could modify list"); 269 } catch (UnsupportedOperationException e) { 270 // Expected 271 } 272 273 JarURLConnection con1 = openJarURLConnection(); 274 map = con1.getRequestProperties(); 275 assertNotNull(map); 276 assertEquals(0, map.size()); 277 try { 278 // the map should be unmodifiable 279 map.put("hi", Arrays.asList(new String[] { "bye" })); 280 fail(); 281 } catch (UnsupportedOperationException e) { 282 // Expected 283 } 284 } 285 286 public void testHttpPostHeaders() throws IOException { 287 String path = "/" + Math.random(); 288 HttpURLConnection connection = (HttpURLConnection) 289 new URL("http://localhost:" + port + path).openConnection(); 290 291 // post a request 292 connection.setDoOutput(true); 293 OutputStreamWriter writer 294 = new OutputStreamWriter(connection.getOutputStream()); 295 writer.write("hello"); 296 writer.flush(); 297 assertEquals(200, connection.getResponseCode()); 298 299 // validate the request by asking the server what was received 300 Map<String, String> headers = server.pathToRequest().get(path).getHeaders(); 301 assertNull(headers.get("Accept")); 302 assertEquals("application/x-www-form-urlencoded", headers.get("Content-Type")); 303 assertEquals("5", headers.get("Content-Length")); 304 assertEquals("localhost:" + port, headers.get("Host")); 305 // TODO: test User-Agent? 306 } 307 308 public void test_getAllowUserInteraction() throws Exception { 309 uc.setAllowUserInteraction(false); 310 assertFalse(uc.getAllowUserInteraction()); 311 312 uc.setAllowUserInteraction(true); 313 assertTrue(uc.getAllowUserInteraction()); 314 315 uc.connect(); 316 317 // Can't call the setter after connecting. 318 try { 319 uc.setAllowUserInteraction(false); 320 fail(); 321 } catch (IllegalStateException expected) { 322 } 323 } 324 325 /** 326 * @throws IOException 327 * {@link java.net.URLConnection#connect()} 328 */ 329 public void test_connect() throws IOException { 330 331 uc.connect(); 332 ((HttpURLConnection) uc).disconnect(); 333 uc.connect(); 334 335 try { 336 uc.setDoOutput(false); 337 } catch (Exception e) { 338 // ok 339 } 340 } 341 342 /** 343 * {@link java.net.URLConnection#getContent()} 344 */ 345 public void test_getContent() throws IOException { 346 byte[] ba = new byte[testString.getBytes().length]; 347 String buf = null; 348 349 Object obj = fileURLCon.getContent(); 350 if (obj instanceof String) { 351 buf = (String) obj; 352 assertTrue("Incorrect content returned from fileURL: "+buf, 353 testString.equals(buf.trim())); 354 } else if (obj instanceof InputStream) { 355 InputStream i = (InputStream) obj; 356 BufferedReader r = new BufferedReader(new InputStreamReader(i),testString.getBytes().length); 357 buf = r.readLine(); 358 assertTrue("Incorrect content returned from fileURL: "+buf, 359 testString.equals(buf.trim())); 360 i.close(); 361 } else { 362 fail("Some unknown type is returned "+obj.toString()); 363 } 364 365 //Exception test 366 URL url = new URL("http://a/b/c/?y"); 367 URLConnection fakeCon = url.openConnection(); 368 try { 369 fakeCon.getContent(); 370 } catch (IOException e) { 371 //ok 372 } 373 374 ((HttpURLConnection) uc).disconnect(); 375 try { 376 uc.getContent(); 377 } catch (IOException e) { 378 //ok 379 } 380 381 } 382 383 /** 384 * {@link java.net.URLConnection#getContent(Class[])} 385 */ 386 public void test_getContent_LjavalangClass() throws IOException { 387 byte[] ba = new byte[600]; 388 389 fileURLCon.setDoInput(true); 390 fileURLCon.connect(); 391 392 InputStream helloWorld2 = (InputStream) fileURLCon.getContent(new Class[] {InputStream.class}); 393 assertNotNull(helloWorld2); 394 BufferedReader r = new BufferedReader(new InputStreamReader(helloWorld2),testString.getBytes().length); 395 assertTrue("Incorrect content returned from fileURL", 396 testString.equals(r.readLine().trim())); 397 398 String test = (String) fileURLCon.getContent(new Class[] {String.class} ); 399 assertNull(test); 400 401 //Exception test 402 ((HttpURLConnection) uc).disconnect(); 403 try { 404 uc.getContent(); 405 } catch (IOException e) { 406 //ok 407 } 408 409 try { 410 ((InputStream) fileURLCon.getContent(null)).read(ba, 0, 600); 411 fail("should throw NullPointerException"); 412 } catch (NullPointerException e) { 413 // expected 414 } 415 416 try { 417 ((InputStream) fileURLCon.getContent(new Class[] {})).read(ba, 0, 600); 418 fail("should throw NullPointerException"); 419 } catch (NullPointerException e) { 420 // expected 421 } 422 423 try { 424 ((InputStream) fileURLCon.getContent(new Class[] { Class.class })).read(ba, 425 0, 600); 426 fail("should throw NullPointerException"); 427 } catch (NullPointerException e) { 428 // expected 429 } 430 431 fileURLCon.getInputStream().close(); 432 } 433 434 /** 435 * @throws IOException 436 * {@link java.net.URLConnection#getContentEncoding()} 437 */ 438 @BrokenTest("Fails in CTS, passes in CoreTestRunner") 439 public void test_getContentEncoding() throws IOException { 440 // faulty setup 441 try { 442 443 fileURLCon.getContentEncoding(); 444 fail("Exception expected"); 445 } catch (Throwable e) { 446 //ok 447 } 448 449 // positive case 450 451 URL url = new URL("http://www.amazon.com/"); 452 453 URLConnection con = url.openConnection(); 454 con.setRequestProperty("Accept-Encoding", "gzip"); 455 con.connect(); 456 457 assertEquals(con.getContentEncoding(), "gzip"); 458 459 460 uc2.setRequestProperty("Accept-Encoding", "bla"); 461 uc2.connect(); 462 463 assertNull(uc2.getContentEncoding()); 464 465 } 466 467 /** 468 * {@link java.net.URLConnection#getContentLength()} 469 */ 470 public void test_getContentLength() throws Exception { 471 assertEquals(testString.getBytes().length, fileURLCon.getContentLength()); 472 assertEquals(Support_TestWebData.test1.length, uc.getContentLength()); 473 assertEquals(Support_TestWebData.test2.length, uc2.getContentLength()); 474 475 assertNotNull(jarURLCon.getContentLength()); 476 assertNotNull(gifURLCon.getContentLength()); 477 478 fileURLCon.getInputStream().close(); 479 } 480 481 public void test_getContentType() throws Exception { 482 assertTrue("getContentType failed: " + fileURLCon.getContentType(), 483 fileURLCon.getContentType().contains("text/plain")); 484 485 fileURLCon.getInputStream().close(); 486 487 URLConnection htmlFileCon = openHTMLFile(); 488 String contentType = htmlFileCon.getContentType(); 489 if (contentType != null) { 490 assertTrue(contentType.equalsIgnoreCase("text/html")); 491 } 492 } 493 494 /** 495 * {@link java.net.URLConnection#getDate()} 496 */ 497 public void test_getDate() { 498 // should be greater than 930000000000L which represents the past 499 assertTrue("getDate gave wrong date: " + uc.getDate(), 500 uc.getDate() > 930000000000L); 501 } 502 503 /** 504 * @throws IOException 505 * {@link java.net.URLConnection#getDefaultAllowUserInteraction()} 506 */ 507 public void test_getDefaultAllowUserInteraction() throws IOException { 508 boolean oldSetting = URLConnection.getDefaultAllowUserInteraction(); 509 510 URLConnection.setDefaultAllowUserInteraction(false); 511 assertFalse( 512 "getDefaultAllowUserInteraction should have returned false", 513 URLConnection.getDefaultAllowUserInteraction()); 514 515 URLConnection.setDefaultAllowUserInteraction(true); 516 assertTrue("getDefaultAllowUserInteraction should have returned true", 517 URLConnection.getDefaultAllowUserInteraction()); 518 519 URLConnection.setDefaultAllowUserInteraction(oldSetting); 520 } 521 522 /** 523 * {@link java.net.URLConnection#getDefaultRequestProperty(String)} 524 */ 525 @SuppressWarnings("deprecation") 526 public void test_getDefaultRequestPropertyLjava_lang_String() { 527 URLConnection.setDefaultRequestProperty("Shmoo", "Blah"); 528 assertNull("setDefaultRequestProperty should have returned: null", 529 URLConnection.getDefaultRequestProperty("Shmoo")); 530 531 URLConnection.setDefaultRequestProperty("Shmoo", "Boom"); 532 assertNull("setDefaultRequestProperty should have returned: null", 533 URLConnection.getDefaultRequestProperty("Shmoo")); 534 535 assertNull("setDefaultRequestProperty should have returned: null", 536 URLConnection.getDefaultRequestProperty("Kapow")); 537 538 URLConnection.setDefaultRequestProperty("Shmoo", null); 539 } 540 541 /** 542 * @throws IOException 543 * {@link java.net.URLConnection#getDoInput()} 544 */ 545 public void test_getDoInput() throws IOException { 546 assertTrue("Should be set to true by default", uc.getDoInput()); 547 548 fileURLCon.setDoInput(true); 549 assertTrue("Should have been set to true", fileURLCon.getDoInput()); 550 551 uc2.setDoInput(false); 552 assertFalse("Should have been set to false", uc2.getDoInput()); 553 554 fileURLCon.connect(); 555 fileURLCon.getInputStream().close(); 556 557 uc2.connect(); 558 try { 559 uc2.getInputStream(); 560 } catch (Throwable expected) { 561 } 562 } 563 564 /** 565 * @throws IOException 566 * {@link java.net.URLConnection#getDoOutput()} 567 */ 568 public void test_getDoOutput() throws IOException { 569 assertFalse("Should be set to false by default", uc.getDoOutput()); 570 571 uc.setDoOutput(true); 572 assertTrue("Should have been set to true", uc.getDoOutput()); 573 574 uc.connect(); 575 uc.getOutputStream(); 576 577 uc2.setDoOutput(false); 578 assertFalse("Should have been set to false", uc2.getDoOutput()); 579 uc2.connect(); 580 581 try{ 582 uc2.getOutputStream(); 583 } catch (Throwable e) { 584 //ok 585 } 586 } 587 588 /** 589 * @throws IOException 590 * {@link java.net.URLConnection#getExpiration()} 591 */ 592 public void test_getExpiration() throws IOException { 593 594 uc.connect(); 595 // should be unknown 596 assertEquals("getExpiration returned wrong expiration", 0, uc 597 .getExpiration()); 598 599 uc2.connect(); 600 assertTrue("getExpiration returned wrong expiration: " + uc2 601 .getExpiration(), uc2.getExpiration() > 0); 602 } 603 604 /** 605 * {@link java.net.URLConnection#getFileNameMap()} 606 */ 607 public void test_getFileNameMap() { 608 // Tests for the standard MIME types -- users may override these 609 // in their JRE 610 611 FileNameMap mapOld = URLConnection.getFileNameMap(); 612 613 try { 614 // These types are defaulted 615 assertEquals("text/html", mapOld.getContentTypeFor(".htm")); 616 assertEquals("text/html", mapOld.getContentTypeFor(".html")); 617 assertEquals("text/plain", mapOld.getContentTypeFor(".text")); 618 assertEquals("text/plain", mapOld.getContentTypeFor(".txt")); 619 620 // These types come from the properties file : 621 // not black-box testing. Special tests moved to setContentType 622 /* 623 assertEquals("application/pdf", map.getContentTypeFor(".pdf")); 624 assertEquals("application/zip", map.getContentTypeFor(".zip")); 625 assertEquals("image/gif", map.getContentTypeFor("gif")); 626 */ 627 628 URLConnection.setFileNameMap(new FileNameMap() { 629 public String getContentTypeFor(String fileName) { 630 return "Spam!"; 631 } 632 }); 633 634 assertEquals("Incorrect FileNameMap returned", "Spam!", 635 URLConnection.getFileNameMap().getContentTypeFor(null)); 636 } finally { 637 // unset the map so other tests don't fail 638 URLConnection.setFileNameMap(mapOld); 639 } 640 // RI fails since it does not support fileName that does not begin with 641 // '.' 642 643 } 644 645 /** 646 * {@link java.net.URLConnection#getHeaderFieldDate(java.lang.String, long)} 647 */ 648 public void test_getHeaderFieldDateLjava_lang_StringJ() { 649 Support_TestWebData params = Support_TestWebData.testParams[0]; 650 651 long hf; 652 hf = uc.getHeaderFieldDate("Content-Encoding", Long.MIN_VALUE); 653 assertEquals("Long value returned for header field 'Content-Encoding':", 654 Long.MIN_VALUE, hf); 655 hf = uc.getHeaderFieldDate("Content-Length", Long.MIN_VALUE); 656 assertEquals("Long value returned for header field 'Content-Length': ", 657 Long.MIN_VALUE, hf); 658 hf = uc.getHeaderFieldDate("Content-Type", Long.MIN_VALUE); 659 assertEquals("Long value returned for header field 'Content-Type': ", 660 Long.MIN_VALUE, hf); 661 hf = uc.getHeaderFieldDate("content-type", Long.MIN_VALUE); 662 assertEquals("Long value returned for header field 'content-type': ", 663 Long.MIN_VALUE, hf); 664 hf = uc.getHeaderFieldDate("Date", Long.MIN_VALUE); 665 assertTrue("Wrong value returned for header field 'Date': " + hf, 666 new Date().getTime() - hf < 5000); 667 hf = uc.getHeaderFieldDate("SERVER", Long.MIN_VALUE); 668 assertEquals("Long value returned for header field 'SERVER': ", 669 Long.MIN_VALUE, hf); 670 hf = uc.getHeaderFieldDate("Last-Modified", Long.MIN_VALUE); 671 assertEquals("Long value returned for header field 'Last-Modified': ", 672 Long.MIN_VALUE, hf); 673 } 674 675 /** 676 * {@link java.net.URLConnection#getHeaderField(int)} 677 */ 678 public void DISABLED_test_getHeaderFieldI() { 679 int i = 0; 680 String hf; 681 boolean foundResponse = false; 682 while ((hf = uc.getHeaderField(i++)) != null) { 683 if (hf.equals(Support_Configuration.HomeAddressSoftware)) { 684 foundResponse = true; 685 } 686 } 687 assertTrue("Could not find header field containing \"" 688 + Support_Configuration.HomeAddressSoftware + "\"", 689 foundResponse); 690 691 i = 0; 692 foundResponse = false; 693 while ((hf = uc.getHeaderField(i++)) != null) { 694 if (hf.equals(Support_Configuration.HomeAddressResponse)) { 695 foundResponse = true; 696 } 697 } 698 assertTrue("Could not find header field containing \"" 699 + Support_Configuration.HomeAddressResponse + "\"", 700 foundResponse); 701 } 702 703 /** 704 * {@link java.net.URLConnection#getHeaderFieldKey(int)} 705 */ 706 public void DISABLED_test_getHeaderFieldKeyI() { 707 String hf; 708 boolean foundResponse = false; 709 for (int i = 0; i < 100; i++) { 710 hf = uc.getHeaderFieldKey(i); 711 if (hf != null && hf.toLowerCase().equals("content-type")) { 712 foundResponse = true; 713 break; 714 } 715 } 716 assertTrue( 717 "Could not find header field key containing \"content-type\"", 718 foundResponse); 719 } 720 721 /** 722 * @throws IOException 723 * {@link java.net.URLConnection#getHeaderFieldInt(String, int)} 724 */ 725 public void test_getHeaderFieldInt() throws IOException, ParseException { 726 Support_TestWebData params = Support_TestWebData.testParams[1]; 727 728 int hf = 0; 729 hf = uc2.getHeaderFieldInt("Content-Encoding", Integer.MIN_VALUE); 730 assertEquals(Integer.MIN_VALUE, hf); 731 hf = uc2.getHeaderFieldInt("Content-Length", Integer.MIN_VALUE); 732 assertEquals(params.testLength, hf); 733 hf = uc2.getHeaderFieldInt("Content-Type", Integer.MIN_VALUE); 734 assertEquals(Integer.MIN_VALUE, hf); 735 hf = uc2.getHeaderFieldInt("Date", Integer.MIN_VALUE); 736 assertEquals(Integer.MIN_VALUE, hf); 737 hf = uc2.getHeaderFieldInt("Expires", Integer.MIN_VALUE); 738 assertEquals(Integer.MIN_VALUE, hf); 739 hf = uc2.getHeaderFieldInt("SERVER", Integer.MIN_VALUE); 740 assertEquals(Integer.MIN_VALUE, hf); 741 hf = uc2.getHeaderFieldInt("Last-Modified", Integer.MIN_VALUE); 742 assertEquals(Integer.MIN_VALUE, hf); 743 hf = uc2.getHeaderFieldInt("accept-ranges", Integer.MIN_VALUE); 744 assertEquals(Integer.MIN_VALUE, hf); 745 hf = uc2.getHeaderFieldInt("DoesNotExist", Integer.MIN_VALUE); 746 assertEquals(Integer.MIN_VALUE, hf); 747 748 } 749 750 /** 751 * {@link java.net.URLConnection#getHeaderField(java.lang.String)} 752 */ 753 public void test_getHeaderFieldLjava_lang_String() { 754 Support_TestWebData params = Support_TestWebData.testParams[0]; 755 756 String hf; 757 hf = uc.getHeaderField("Content-Encoding"); 758 assertNull("String value returned for header field 'Content-Encoding':", 759 hf); 760 hf = uc.getHeaderField("Content-Length"); 761 assertEquals("Wrong value returned for header field 'Content-Length': ", 762 String.valueOf(params.testLength), hf); 763 hf = uc.getHeaderField("Content-Type"); 764 assertEquals("Wrong value returned for header field 'Content-Type': ", 765 params.testType, hf); 766 hf = uc.getHeaderField("content-type"); 767 assertEquals("Wrong value returned for header field 'content-type': ", 768 params.testType, hf); 769 hf = uc.getHeaderField("Date"); 770 assertTrue("Wrong string value returned for header field 'Date': " 771 + hf, hf.length() > 20); 772 hf = uc.getHeaderField("SERVER"); 773 assertEquals("Wrong value returned for header field 'SERVER': ", 774 "TestWebServer" + port, hf); 775 hf = uc.getHeaderField("Last-Modified"); 776 assertNull("Wrong string value returned for 'Last-Modified': " 777 + hf, hf); 778 } 779 780 /** 781 * @throws URISyntaxException 782 * @throws ClassNotFoundException 783 * {@link java.net.URLConnection#getHeaderFields()} 784 */ 785 public void test_getHeaderFields() throws IOException, ClassNotFoundException, URISyntaxException { 786 Support_TestWebData params = Support_TestWebData.testParams[1]; 787 788 try { 789 uc2.getInputStream(); 790 } catch (IOException e) { 791 fail("Error in test setup: "+e.getMessage()); 792 } 793 794 Map<String, List<String>> headers = uc2.getHeaderFields(); 795 assertNotNull(headers); 796 797 List<String> list = headers.get("content-type"); 798 if (list == null) { 799 list = headers.get("Content-Type"); 800 } 801 if (list == null) { 802 list = headers.get("Content-type"); 803 } 804 805 assertNotNull(list); 806 String contentType = (String) list.get(0); 807 assertEquals(params.testType, contentType); 808 809 // there should be at least 2 headers 810 assertTrue("Not more than one header in URL connection", 811 headers.size() > 1); 812 813 headers = jarURLCon.getHeaderFields(); 814 assertNotNull(headers); 815 assertEquals(0, headers.size()); 816 817 try { 818 // the map should be unmodifiable 819 headers.put("hi", Arrays.asList(new String[] { "bye" })); 820 fail("The map should be unmodifiable"); 821 } catch (UnsupportedOperationException e) { 822 // Expected 823 } 824 } 825 826 /** 827 * @throws IOException 828 * {@link java.net.URLConnection#getLastModified()} 829 */ 830 public void test_getLastModified() throws IOException { 831 832 URL url4 = new URL(Support_Configuration.hTTPURLwLastModified); 833 URLConnection uc4 = url4.openConnection(); 834 835 uc4.connect(); 836 837 if (uc4.getLastModified() == 0) { 838 System.out 839 .println("WARNING: Server does not support 'Last-Modified', test_getLastModified() not run"); 840 return; 841 } 842 843 long millis = uc4.getHeaderFieldDate("Last-Modified", 0); 844 845 assertEquals( 846 "Returned wrong getLastModified value. Wanted: " 847 + " got: " + uc4.getLastModified(), 848 millis, uc4.getLastModified()); 849 850 851 ((HttpURLConnection) uc).disconnect(); 852 } 853 854 public void test_getOutputStream() throws IOException { 855 String posted = "this is a test"; 856 URLConnection uc3 = new URL("http://www.google.com/ie").openConnection(); 857 uc3.setDoOutput(true); 858 uc3.connect(); 859 860 BufferedWriter w = new BufferedWriter(new OutputStreamWriter(uc3 861 .getOutputStream()), posted.getBytes().length); 862 863 w.write(posted); 864 w.flush(); 865 w.close(); 866 867 int code = ((HttpURLConnection) uc3).getResponseCode(); 868 869 // writing to url not allowed 870 assertEquals("Got different responseCode ", 405, code); 871 872 // try exception testing 873 try { 874 fileURLCon.setDoOutput(true); 875 fileURLCon.connect(); 876 fileURLCon.getInputStream().close(); 877 fileURLCon.getOutputStream(); 878 } catch (UnknownServiceException expected) { 879 } 880 881 ((HttpURLConnection) uc2).disconnect(); 882 883 try { 884 uc2.getOutputStream(); 885 fail("Exception expected"); 886 } catch (IOException e) { 887 // ok 888 } 889 } 890 891 /** 892 * {@link java.net.URLConnection#getRequestProperties()} 893 */ 894 public void test_getRequestProperties() { 895 uc.setRequestProperty("whatever", "you like"); 896 Map headers = uc.getRequestProperties(); 897 898 // content-length should always appear 899 List header = (List) headers.get("whatever"); 900 assertNotNull(header); 901 902 assertEquals("you like", header.get(0)); 903 904 assertTrue(headers.size() >= 1); 905 906 try { 907 // the map should be unmodifiable 908 headers.put("hi", "bye"); 909 fail(); 910 } catch (UnsupportedOperationException e) { 911 } 912 try { 913 // the list should be unmodifiable 914 header.add("hi"); 915 fail(); 916 } catch (UnsupportedOperationException e) { 917 } 918 919 } 920 921 /** 922 * {@link java.net.URLConnection#getRequestProperties()} 923 */ 924 public void test_getRequestProperties_Exception() throws IOException { 925 URL url = new URL("http", "test", 80, "index.html", new NewHandler()); 926 URLConnection urlCon = url.openConnection(); 927 urlCon.connect(); 928 929 try { 930 urlCon.getRequestProperties(); 931 fail("should throw IllegalStateException"); 932 } catch (IllegalStateException e) { 933 // expected 934 } 935 936 } 937 938 /** 939 * {@link java.net.URLConnection#getRequestProperty(java.lang.String)} 940 */ 941 public void test_getRequestProperty_LString_Exception() throws IOException { 942 URL url = new URL("http", "test", 80, "index.html", new NewHandler()); 943 URLConnection urlCon = url.openConnection(); 944 urlCon.setRequestProperty("test", "testProperty"); 945 assertNull(urlCon.getRequestProperty("test")); 946 947 urlCon.connect(); 948 try { 949 urlCon.getRequestProperty("test"); 950 fail("should throw IllegalStateException"); 951 } catch (IllegalStateException e) { 952 // expected 953 } 954 } 955 956 /** 957 * {@link java.net.URLConnection#getRequestProperty(java.lang.String)} 958 */ 959 public void test_getRequestPropertyLjava_lang_String() { 960 uc.setRequestProperty("Yo", "yo"); 961 assertTrue("Wrong property returned: " + uc.getRequestProperty("Yo"), 962 uc.getRequestProperty("Yo").equals("yo")); 963 assertNull("Wrong property returned: " + uc.getRequestProperty("No"), 964 uc.getRequestProperty("No")); 965 } 966 967 /** 968 * {@link java.net.URLConnection#getURL()} 969 */ 970 public void test_getURL() { 971 assertTrue("Incorrect URL returned", uc.getURL().equals(url)); 972 } 973 974 /** 975 * @throws IOException 976 * {@link java.net.URLConnection#getUseCaches()} 977 */ 978 public void test_getUseCaches() throws IOException { 979 uc2.setUseCaches(false); 980 assertTrue("getUseCaches should have returned false", !uc2 981 .getUseCaches()); 982 uc2.setUseCaches(true); 983 assertTrue("getUseCaches should have returned true", uc2.getUseCaches()); 984 985 uc2.connect(); 986 987 988 try { 989 uc2.setUseCaches(false); 990 fail("Exception expected"); 991 } catch (IllegalStateException e) { 992 //ok 993 } 994 995 ((HttpURLConnection) uc2).disconnect(); 996 997 } 998 999 /** 1000 * {@link java.net.URLConnection#guessContentTypeFromName(String)} 1001 */ 1002 public void test_guessContentTypeFromName() 1003 throws IOException { 1004 1005 URLConnection htmlFileCon = openHTMLFile(); 1006 String[] expected = new String[] {"text/html", 1007 "text/plain" }; 1008 String[] resources = new String[] { 1009 htmlFileCon.getURL().toString(), 1010 fileURL.toString() 1011 }; 1012 for (int i = 0; i < resources.length; i++) { 1013 String mime = URLConnection.guessContentTypeFromName( resources[i]); 1014 assertEquals("checking " + resources[i] + " expected " + expected[i]+"got " + expected[i], 1015 expected[i], mime); 1016 } 1017 1018 // Try simple case 1019 try { 1020 URLConnection.guessContentTypeFromStream(null); 1021 fail("should throw NullPointerException"); 1022 } catch (NullPointerException e) { 1023 // expected 1024 } 1025 } 1026 1027 /** 1028 * {@link java.net.URLConnection#guessContentTypeFromStream(java.io.InputStream)} 1029 */ 1030 public void test_guessContentTypeFromStreamLjava_io_InputStream() 1031 throws IOException { 1032 assertContentTypeEquals("ASCII", "text/html", "<html>"); 1033 assertContentTypeEquals("ASCII", "text/html", "<head>"); 1034 assertContentTypeEquals("ASCII", "text/html", "<head "); 1035 assertContentTypeEquals("ASCII", "text/html", "<body"); 1036 assertContentTypeEquals("ASCII", "text/html", "<BODY "); 1037 assertContentTypeEquals("ASCII", "application/xml", "<?xml "); 1038 1039 assertContentTypeEquals("UTF-8", "text/html", "<html>"); 1040 assertContentTypeEquals("UTF-8", "text/html", "<head>"); 1041 assertContentTypeEquals("UTF-8", "text/html", "<head "); 1042 assertContentTypeEquals("UTF-8", "text/html", "<body"); 1043 assertContentTypeEquals("UTF-8", "text/html", "<BODY "); 1044 assertContentTypeEquals("UTF-8", "application/xml", "<?xml "); 1045 1046 //"UTF-16BE", "UTF-16LE", "UTF-32BE" and 1047 //"UTF-32LE" are not supported 1048 1049 // Try simple case 1050 try { 1051 URLConnection.guessContentTypeFromStream(null); 1052 fail("should throw NullPointerException"); 1053 } catch (NullPointerException e) { 1054 // expected 1055 } 1056 /* not supported 1057 // Test magic bytes 1058 byte[][] bytes = new byte[][] { { 'P', 'K' }, { 'G', 'I' } }; 1059 expected = new String[] { "application/zip", "image/gif" }; 1060 1061 for (int i = 0; i < bytes.length; i++) { 1062 InputStream is = new ByteArrayInputStream(bytes[i]); 1063 assertEquals(expected[i], URLConnection 1064 .guessContentTypeFromStream(is)); 1065 } 1066 */ 1067 } 1068 1069 void assertContentTypeEquals(String encoding, String expected, 1070 String header) throws IOException { 1071 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 1072 String encodedString = new String(header.getBytes(), encoding); 1073 InputStream is = new ByteArrayInputStream(encodedString.getBytes()); 1074 String mime = URLConnection.guessContentTypeFromStream(is); 1075 assertEquals("checking '" + header + "' with " + encoding, 1076 expected, mime); 1077 } 1078 1079 /** 1080 * {@link java.net.URLConnection#setConnectTimeout(int)} 1081 */ 1082 public void test_setConnectTimeoutI() throws Exception { 1083 URLConnection uc = new URL("http://localhost").openConnection(); 1084 assertEquals(0, uc.getConnectTimeout()); 1085 uc.setConnectTimeout(0); 1086 assertEquals(0, uc.getConnectTimeout()); 1087 try { 1088 uc.setConnectTimeout(-100); 1089 fail("should throw IllegalArgumentException"); 1090 } catch (IllegalArgumentException e) { 1091 // correct 1092 } 1093 assertEquals(0, uc.getConnectTimeout()); 1094 uc.setConnectTimeout(100); 1095 assertEquals(100, uc.getConnectTimeout()); 1096 try { 1097 uc.setConnectTimeout(-1); 1098 fail("should throw IllegalArgumentException"); 1099 } catch (IllegalArgumentException e) { 1100 // correct 1101 } 1102 assertEquals(100, uc.getConnectTimeout()); 1103 1104 uc2.setConnectTimeout(2); 1105 1106 try { 1107 uc2.connect(); 1108 } catch (SocketTimeoutException e) { 1109 //ok 1110 } 1111 1112 } 1113 1114 /** 1115 * @throws IOException 1116 * {@link java.net.URLConnection#setFileNameMap(java.net.FileNameMap)} 1117 */ 1118 public void test_setFileNameMapLjava_net_FileNameMap() throws IOException { 1119 FileNameMap mapOld = URLConnection.getFileNameMap(); 1120 // nothing happens if set null 1121 URLConnection.setFileNameMap(null); 1122 // take no effect 1123 assertNotNull(URLConnection.getFileNameMap()); 1124 1125 try { 1126 URLConnection.setFileNameMap(new java.net.FileNameMap(){ 1127 public String getContentTypeFor(String fileName) { 1128 if (fileName==null || fileName.length()<1) 1129 return null; 1130 String name=fileName.toLowerCase(); 1131 String type=null; 1132 if (name.endsWith(".xml")) 1133 type="text/xml"; 1134 else if (name.endsWith(".dtd")) 1135 type="text/dtd"; 1136 else if (name.endsWith(".pdf")) 1137 type = "application/pdf"; 1138 else if (name.endsWith(".zip")) 1139 type = "application/zip"; 1140 else if (name.endsWith(".gif")) 1141 type = "image/gif"; 1142 else 1143 type="application/unknown"; 1144 return type; 1145 } 1146 }); 1147 FileNameMap mapNew = URLConnection.getFileNameMap(); 1148 assertEquals("application/pdf", mapNew.getContentTypeFor(".pdf")); 1149 assertEquals("application/zip", mapNew.getContentTypeFor(".zip")); 1150 assertEquals("image/gif", mapNew.getContentTypeFor(".gif")); 1151 } finally { 1152 1153 URLConnection.setFileNameMap(mapOld); 1154 } 1155 } 1156 1157 /** 1158 * {@link java.net.URLConnection#setIfModifiedSince(long)} 1159 */ 1160 public void test_setIfModifiedSinceJ() throws IOException { 1161 URL url = new URL("http://localhost:8080/"); 1162 URLConnection connection = url.openConnection(); 1163 Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); 1164 cal.clear(); 1165 cal.set(2000, Calendar.MARCH, 5); 1166 1167 long sinceTime = cal.getTime().getTime(); 1168 connection.setIfModifiedSince(sinceTime); 1169 assertEquals("Wrong date set", sinceTime, connection 1170 .getIfModifiedSince()); 1171 1172 // content should be returned 1173 1174 uc2.setIfModifiedSince(sinceTime); 1175 uc2.connect(); 1176 1177 1178 assertEquals(200,((HttpURLConnection) uc2).getResponseCode()); 1179 1180 try { 1181 uc2.setIfModifiedSince(2); 1182 fail("Exception expected"); 1183 } catch (IllegalStateException e) { 1184 //ok 1185 } 1186 1187 ((HttpURLConnection) uc2).disconnect(); 1188 1189 1190 } 1191 1192 public void test_getIfModifiedSinceJ() throws IOException { 1193 1194 uc2.setIfModifiedSince(Calendar.getInstance().getTimeInMillis()); 1195 uc2.connect(); 1196 1197 assertEquals(200,((HttpURLConnection) uc2).getResponseCode()); 1198 1199 } 1200 1201 1202 /** 1203 * {@link java.net.URLConnection#setReadTimeout(int)} 1204 */ 1205 public void test_setReadTimeoutI() throws Exception { 1206 assertEquals(0, uc.getReadTimeout()); 1207 uc.setReadTimeout(0); 1208 assertEquals(0, uc.getReadTimeout()); 1209 try { 1210 uc.setReadTimeout(-100); 1211 fail("should throw IllegalArgumentException"); 1212 } catch (IllegalArgumentException e) { 1213 // correct 1214 } 1215 assertEquals(0, uc.getReadTimeout()); 1216 uc.setReadTimeout(100); 1217 assertEquals(100, uc.getReadTimeout()); 1218 try { 1219 uc.setReadTimeout(-1); 1220 fail("should throw IllegalArgumentException"); 1221 } catch (IllegalArgumentException e) { 1222 // correct 1223 } 1224 assertEquals(100, uc.getReadTimeout()); 1225 1226 byte[] ba = new byte[600]; 1227 1228 uc2.setReadTimeout(5); 1229 uc2.setDoInput(true); 1230 uc2.connect(); 1231 1232 try { 1233 ((InputStream) uc2.getInputStream()).read(ba, 0, 600); 1234 } catch (SocketTimeoutException e) { 1235 //ok 1236 } catch ( UnknownServiceException e) { 1237 fail(""+e.getMessage()); 1238 } 1239 } 1240 1241 /** 1242 * {@link java.net.URLConnection#toString()} 1243 */ 1244 public void test_toString() { 1245 1246 assertTrue("Wrong toString: " + uc.toString(), uc.toString().indexOf( 1247 "URLConnection") > 0); 1248 assertTrue("Wrong toString: " + uc.toString(), uc.toString().indexOf( 1249 uc.getURL().toString()) > 0); 1250 } 1251 1252 public void test_URLConnection() { 1253 String url = uc2.getURL().toString(); 1254 assertEquals(url2.toString(), url); 1255 } 1256 1257 public void testGetInputStream() throws IOException { 1258 fileURLCon.setDoInput(true); 1259 fileURLCon.connect(); 1260 1261 BufferedReader buf = new BufferedReader(new InputStreamReader( 1262 fileURLCon.getInputStream()), testString.getBytes().length); 1263 1264 String nextline; 1265 while ((nextline = buf.readLine()) != null) { 1266 assertEquals(testString, nextline); 1267 } 1268 1269 buf.close(); 1270 1271 assertNotNull(uc.getInputStream()); 1272 1273 ((HttpURLConnection) uc2).disconnect(); 1274 1275 assertNotNull(uc2.getInputStream()); 1276 1277 } 1278 1279 private URLConnection openGifURLConnection() throws IOException { 1280 String cts = System.getProperty("java.io.tmpdir"); 1281 File tmpDir = new File(cts); 1282 Support_Resources.copyFile(tmpDir, null, "Harmony.GIF"); 1283 URL fUrl1 = new URL("file:/" + tmpDir.getPath() 1284 + "/Harmony.GIF"); 1285 URLConnection con1 = fUrl1.openConnection(); 1286 return con1; 1287 } 1288 1289 private JarURLConnection openJarURLConnection() 1290 throws MalformedURLException, IOException { 1291 String cts = System.getProperty("java.io.tmpdir"); 1292 File tmpDir = new File(cts); 1293 Support_Resources.copyFile(tmpDir, null, "hyts_att.jar"); 1294 URL fUrl1 = new URL("jar:file:" + tmpDir.getPath() 1295 + "/hyts_att.jar!/"); 1296 JarURLConnection con1 = (JarURLConnection) fUrl1.openConnection(); 1297 return con1; 1298 } 1299 1300 private URLConnection openHTMLFile() throws IOException { 1301 String cts = System.getProperty("java.io.tmpdir"); 1302 File tmpDir = new File(cts); 1303 Support_Resources.copyFile(tmpDir, null, "hyts_htmltest.html"); 1304 URL fUrl1 = new URL("file:/" + tmpDir.getPath() 1305 + "/hyts_htmltest.html"); 1306 URLConnection con1 = fUrl1.openConnection(); 1307 return con1; 1308 } 1309 1310 private URL createTempHelloWorldFile() throws MalformedURLException { 1311 // create content to read 1312 File tmpDir = new File(System.getProperty("java.io.tmpdir")); 1313 File sampleFile = null; 1314 try { 1315 if (tmpDir.isDirectory()) { 1316 sampleFile = File.createTempFile("openStreamTest", ".txt", 1317 tmpDir); 1318 sampleFile.deleteOnExit(); 1319 } else { 1320 fail("Error in test setup tmpDir does not exist"); 1321 } 1322 1323 FileWriter fstream = new FileWriter(sampleFile); 1324 BufferedWriter out = new BufferedWriter(fstream, testString.getBytes().length); 1325 out.write(testString); 1326 // Close the output stream 1327 out.close(); 1328 } catch (Exception e) {// Catch exception if any 1329 fail("Error: in test setup" + e.getMessage()); 1330 } 1331 1332 // read content from file 1333 return sampleFile.toURL(); 1334 } 1335} 1336