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