001: /*
002: * Licensed to the Apache Software Foundation (ASF) under one or more
003: * contributor license agreements. See the NOTICE file distributed with
004: * this work for additional information regarding copyright ownership.
005: * The ASF licenses this file to You under the Apache License, Version 2.0
006: * (the "License"); you may not use this file except in compliance with
007: * the License. You may obtain a copy of the License at
008: *
009: * http://www.apache.org/licenses/LICENSE-2.0
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS,
013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014: * See the License for the specific language governing permissions and
015: * limitations under the License.
016: */
017:
018: package org.apache.harmony.luni.tests.java.net;
019:
020: import java.io.IOException;
021: import java.io.InputStream;
022: import java.io.OutputStream;
023: import java.net.CacheRequest;
024: import java.net.CacheResponse;
025: import java.net.HttpURLConnection;
026: import java.net.MalformedURLException;
027: import java.net.ResponseCache;
028: import java.net.SocketPermission;
029: import java.net.URI;
030: import java.net.URL;
031: import java.net.URLConnection;
032: import java.security.Permission;
033: import java.util.ArrayList;
034: import java.util.Hashtable;
035: import java.util.List;
036: import java.util.Map;
037:
038: import tests.support.Support_Configuration;
039: import tests.support.Support_Jetty;
040:
041: public class HttpURLConnectionTest extends junit.framework.TestCase {
042:
043: URL url;
044:
045: HttpURLConnection uc;
046:
047: private boolean isGetCalled;
048:
049: private boolean isPutCalled;
050:
051: private boolean isCacheWriteCalled;
052:
053: private boolean isAbortCalled;
054:
055: private Map<String, List<String>> mockHeaderMap;
056:
057: private InputStream mockIs = new MockInputStream();
058:
059: private static int port;
060:
061: static {
062: // run-once set up
063: try {
064: port = Support_Jetty.startDefaultHttpServer();
065: } catch (Exception e) {
066: fail("Exception during setup jetty : " + e.getMessage());
067: }
068: }
069:
070: /**
071: * @tests java.net.HttpURLConnection#getResponseCode()
072: */
073: public void test_getResponseCode() {
074: try {
075: assertEquals("Wrong response", 200, uc.getResponseCode());
076: } catch (IOException e) {
077: fail("Unexpected exception : " + e.getMessage());
078: }
079: }
080:
081: /**
082: * @tests java.net.HttpURLConnection#getResponseMessage()
083: */
084: public void test_getResponseMessage() {
085: try {
086: assertTrue("Wrong response: " + uc.getResponseMessage(), uc
087: .getResponseMessage().equals("OK"));
088: } catch (IOException e) {
089: fail("Unexpected exception : " + e.getMessage());
090: }
091: }
092:
093: /**
094: * @tests java.net.HttpURLConnection#getHeaderFields()
095: */
096: public void test_getHeaderFields() {
097: try {
098: uc.getInputStream();
099: } catch (IOException e) {
100: fail();
101: }
102: Map headers = uc.getHeaderFields();
103: List list = (List) headers.get("Content-Length");
104: if (list == null) {
105: list = (List) headers.get("content-length");
106: }
107: assertNotNull(list);
108:
109: // content-length should always appear
110: String contentLength = (String) list.get(0);
111: assertNotNull(contentLength);
112:
113: // there should be at least 2 headers
114: assertTrue(headers.size() > 1);
115:
116: try {
117: // the map should be unmodifiable
118: headers.put("hi", "bye");
119: fail();
120: } catch (UnsupportedOperationException e) {
121: }
122:
123: try {
124: // the list should be unmodifiable
125: list.set(0, "whatever");
126: fail();
127: } catch (UnsupportedOperationException e) {
128: }
129: }
130:
131: /**
132: * @tests java.net.HttpURLConnection#getRequestProperties()
133: */
134: public void test_getRequestProperties() {
135: uc.setRequestProperty("whatever", "you like");
136: Map headers = uc.getRequestProperties();
137:
138: List newHeader = (List) headers.get("whatever");
139: assertNotNull(newHeader);
140:
141: assertEquals("you like", newHeader.get(0));
142:
143: try {
144: // the map should be unmodifiable
145: headers.put("hi", "bye");
146: fail();
147: } catch (UnsupportedOperationException e) {
148: }
149: }
150:
151: /**
152: * @tests java.net.HttpURLConnection#getRequestProperty(String)
153: */
154: public void test_getRequestPropertyLjava_lang_String_BeforeConnected()
155: throws MalformedURLException, IOException {
156: uc.setRequestProperty("whatever", "you like"); //$NON-NLS-1$//$NON-NLS-2$
157: String res = uc.getRequestProperty("whatever"); //$NON-NLS-1$
158: assertEquals("you like", res); //$NON-NLS-1$
159:
160: uc.setRequestProperty("", "you like"); //$NON-NLS-1$//$NON-NLS-2$
161: res = uc.getRequestProperty(""); //$NON-NLS-1$
162: assertEquals("you like", res); //$NON-NLS-1$
163:
164: uc.setRequestProperty("", null); //$NON-NLS-1$
165: res = uc.getRequestProperty(""); //$NON-NLS-1$
166: assertEquals(null, res);
167: try {
168: uc.setRequestProperty(null, "you like"); //$NON-NLS-1$
169: fail("Should throw NullPointerException"); //$NON-NLS-1$
170: } catch (NullPointerException e) {
171: // expected
172: }
173: }
174:
175: /**
176: * @tests java.net.HttpURLConnection#getRequestProperty(String)
177: */
178: public void test_getRequestPropertyLjava_lang_String_AfterConnected()
179: throws IOException {
180: uc.connect();
181: try {
182: uc.setRequestProperty("whatever", "you like"); //$NON-NLS-1$//$NON-NLS-2$
183: fail("Should throw IllegalStateException"); //$NON-NLS-1$
184: } catch (IllegalStateException e) {
185: // expected
186: }
187: try {
188: uc.setRequestProperty(null, "you like"); //$NON-NLS-1$
189: fail("Should throw IllegalStateException"); //$NON-NLS-1$
190: } catch (IllegalStateException e) {
191: // expected
192: }
193: String res = uc.getRequestProperty("whatever"); //$NON-NLS-1$
194: assertEquals(null, res);
195: res = uc.getRequestProperty(null);
196: assertEquals(null, res);
197: try {
198: uc.getRequestProperties();
199: fail("Should throw IllegalStateException"); //$NON-NLS-1$
200: } catch (IllegalStateException e) {
201: // expected
202: }
203: }
204:
205: /**
206: * @tests java.net.HttpURLConnection#setFixedLengthStreamingMode_I()
207: */
208: public void test_setFixedLengthStreamingModeI() throws Exception {
209: try {
210: uc.setFixedLengthStreamingMode(-1);
211: fail("should throw IllegalArgumentException");
212: } catch (IllegalArgumentException e) {
213: // correct
214: }
215: uc.setFixedLengthStreamingMode(0);
216: uc.setFixedLengthStreamingMode(1);
217: try {
218: uc.setChunkedStreamingMode(1);
219: fail("should throw IllegalStateException");
220: } catch (IllegalStateException e) {
221: // correct
222: }
223: uc.connect();
224: try {
225: uc.setFixedLengthStreamingMode(-1);
226: fail("should throw IllegalStateException");
227: } catch (IllegalStateException e) {
228: // correct
229: }
230: try {
231: uc.setChunkedStreamingMode(-1);
232: fail("should throw IllegalStateException");
233: } catch (IllegalStateException e) {
234: // correct
235: }
236: MockHttpConnection mock = new MockHttpConnection(url);
237: assertEquals(-1, mock.getFixedLength());
238: mock.setFixedLengthStreamingMode(0);
239: assertEquals(0, mock.getFixedLength());
240: mock.setFixedLengthStreamingMode(1);
241: assertEquals(1, mock.getFixedLength());
242: mock.setFixedLengthStreamingMode(0);
243: assertEquals(0, mock.getFixedLength());
244: }
245:
246: /**
247: * @tests java.net.HttpURLConnection#setChunkedStreamingMode_I()
248: */
249: public void test_setChunkedStreamingModeI() throws Exception {
250: uc.setChunkedStreamingMode(0);
251: uc.setChunkedStreamingMode(-1);
252: uc.setChunkedStreamingMode(-2);
253:
254: try {
255: uc.setFixedLengthStreamingMode(-1);
256: fail("should throw IllegalStateException");
257: } catch (IllegalStateException e) {
258: // correct
259: }
260: try {
261: uc.setFixedLengthStreamingMode(1);
262: fail("should throw IllegalStateException");
263: } catch (IllegalStateException e) {
264: // correct
265: }
266: uc.connect();
267: try {
268: uc.setFixedLengthStreamingMode(-1);
269: fail("should throw IllegalStateException");
270: } catch (IllegalStateException e) {
271: // correct
272: }
273: try {
274: uc.setChunkedStreamingMode(1);
275: fail("should throw IllegalStateException");
276: } catch (IllegalStateException e) {
277: // correct
278: }
279: MockHttpConnection mock = new MockHttpConnection(url);
280: assertEquals(-1, mock.getChunkLength());
281: mock.setChunkedStreamingMode(-1);
282: int defaultChunk = mock.getChunkLength();
283: assertTrue(defaultChunk > 0);
284: mock.setChunkedStreamingMode(0);
285: assertEquals(mock.getChunkLength(), defaultChunk);
286: mock.setChunkedStreamingMode(1);
287: assertEquals(1, mock.getChunkLength());
288: }
289:
290: /**
291: * @tests java.net.HttpURLConnection#setFixedLengthStreamingMode_I()
292: */
293: public void test_setFixedLengthStreamingModeI_effect()
294: throws Exception {
295: String posted = "just a test";
296: java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url
297: .openConnection();
298: conn.setDoOutput(true);
299: conn.setRequestMethod("POST");
300: conn.setFixedLengthStreamingMode(posted.length() - 1);
301: assertNull(conn.getRequestProperty("Content-length"));
302: conn.setRequestProperty("Content-length", String.valueOf(posted
303: .length()));
304: assertEquals(String.valueOf(posted.length()), conn
305: .getRequestProperty("Content-length"));
306: OutputStream out = conn.getOutputStream();
307: try {
308: out.write(posted.getBytes());
309: fail("should throw IOException");
310: } catch (IOException e) {
311: // correct, too many bytes written
312: }
313: try {
314: out.close();
315: fail("should throw IOException");
316: } catch (IOException e) {
317: // correct, too many bytes written
318: }
319: }
320:
321: /**
322: * @tests java.net.HttpURLConnection#setChunkedStreamingMode_I()
323: */
324: public void test_setChunkedStreamingModeI_effect() throws Exception {
325: String posted = "just a test";
326: // for test, use half length of the string
327: int chunkSize = posted.length() / 2;
328: java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url
329: .openConnection();
330: conn.setDoOutput(true);
331: conn.setRequestMethod("POST");
332: conn.setChunkedStreamingMode(chunkSize);
333: assertNull(conn.getRequestProperty("Transfer-Encoding"));
334: // does not take effect
335: conn.setRequestProperty("Content-length", String.valueOf(posted
336: .length() - 1));
337: assertEquals(conn.getRequestProperty("Content-length"), String
338: .valueOf(posted.length() - 1));
339: OutputStream out = conn.getOutputStream();
340: // no error occurs
341: out.write(posted.getBytes());
342: out.close();
343: // no assert here, pass if no exception thrown
344: assertTrue(conn.getResponseCode() > 0);
345: }
346:
347: public void test_getOutputStream_afterConnection() throws Exception {
348: uc.setDoOutput(true);
349: uc.connect();
350: assertNotNull(uc.getOutputStream());
351: }
352:
353: /**
354: * @tests java.net.URLConnection#setUseCaches() and its real implementation
355: * in HttpURLConnection using GetInputStream() and Connect()
356: */
357: public void test_UseCache_HttpURLConnection_Connect_GetInputStream()
358: throws Exception {
359: // set cache before URLConnection created, or it does not take effect
360: ResponseCache rc = new MockNonCachedResponseCache();
361: ResponseCache.setDefault(rc);
362: uc = (HttpURLConnection) url.openConnection();
363: assertFalse(isGetCalled);
364: uc.setUseCaches(true);
365: uc.setDoOutput(true);
366: uc.connect();
367: assertTrue(isGetCalled);
368: assertFalse(isPutCalled);
369: InputStream is = uc.getInputStream();
370: assertTrue(isPutCalled);
371: is.close();
372: ((HttpURLConnection) uc).disconnect();
373: }
374:
375: /**
376: * @tests java.net.URLConnection#setUseCaches() and its real implementation
377: * in HttpURLConnection using GetOutputStream() and Connect()
378: */
379: public void test_UseCache_HttpURLConnection_Connect_GetOutputStream()
380: throws Exception {
381: // set cache before URLConnection created, or it does not take effect
382: ResponseCache rc = new MockNonCachedResponseCache();
383: ResponseCache.setDefault(rc);
384: uc.setUseCaches(true);
385: URLConnection uc = url.openConnection();
386: uc.setDoOutput(true);
387: assertFalse(isGetCalled);
388: uc.connect();
389: assertTrue(isGetCalled);
390: assertFalse(isPutCalled);
391: OutputStream os = uc.getOutputStream();
392: assertFalse(isPutCalled);
393: os.close();
394: ((HttpURLConnection) uc).disconnect();
395: }
396:
397: /**
398: * @tests java.net.URLConnection#setUseCaches() and its real implementation
399: * in HttpURLConnection using GetOutputStream()
400: */
401: public void test_UseCache_HttpURLConnection_GetOutputStream()
402: throws Exception {
403: // set cache before URLConnection created, or it does not take effect
404: ResponseCache rc = new MockNonCachedResponseCache();
405: ResponseCache.setDefault(rc);
406: uc = (HttpURLConnection) url.openConnection();
407: assertFalse(isGetCalled);
408: uc.setDoOutput(true);
409: uc.setUseCaches(true);
410: OutputStream os = uc.getOutputStream();
411: assertTrue(isGetCalled);
412: assertFalse(isPutCalled);
413: os.write(1);
414: os.flush();
415: os.close();
416: ((HttpURLConnection) uc).getResponseCode();
417: assertTrue(isGetCalled);
418: assertTrue(isPutCalled);
419: isGetCalled = false;
420: isPutCalled = false;
421: InputStream is = uc.getInputStream();
422: assertFalse(isGetCalled);
423: assertFalse(isPutCalled);
424: is.close();
425: ((HttpURLConnection) uc).disconnect();
426: }
427:
428: /**
429: * @tests java.net.URLConnection#setUseCaches() and its real implementation
430: * in HttpURLConnection using GetInputStream()
431: */
432: public void test_UseCache_HttpURLConnection_GetInputStream()
433: throws Exception {
434: // set cache before URLConnection created, or it does not take effect
435: ResponseCache rc = new MockNonCachedResponseCache();
436: ResponseCache.setDefault(rc);
437: URLConnection uc = url.openConnection();
438: assertFalse(isGetCalled);
439: uc.setDoOutput(true);
440: uc.setUseCaches(true);
441: InputStream is = uc.getInputStream();
442: assertTrue(isGetCalled);
443: assertTrue(isPutCalled);
444: ((HttpURLConnection) uc).getResponseCode();
445: is.close();
446: ((HttpURLConnection) uc).disconnect();
447: }
448:
449: /**
450: * @tests java.net.URLConnection#setUseCaches() and its real implementation
451: * in HttpURLConnection using a MockResponseCache returns cache of
452: * null
453: */
454: public void test_UseCache_HttpURLConnection_NonCached()
455: throws IOException {
456: ResponseCache.setDefault(new MockNonCachedResponseCache());
457: uc = (HttpURLConnection) url.openConnection();
458:
459: // default useCaches is true
460: assertTrue(uc.getUseCaches());
461:
462: // make sure ResponseCache.get/put is called
463: isGetCalled = false;
464: isPutCalled = false;
465: InputStream is = uc.getInputStream();
466: assertFalse(is instanceof MockInputStream);
467: assertTrue(isGetCalled);
468: assertTrue(isPutCalled);
469:
470: // make sure protocol handler has tried to write to cache.
471: isCacheWriteCalled = false;
472: is.read();
473: assertTrue(isCacheWriteCalled);
474:
475: // make sure protocol handler has tried to write to cache.
476: isCacheWriteCalled = false;
477: byte[] buf = new byte[1];
478: is.read(buf);
479: assertTrue(isCacheWriteCalled);
480:
481: // make sure protocol handler has tried to write to cache.
482: isCacheWriteCalled = false;
483: buf = new byte[1];
484: is.read(buf, 0, 1);
485: assertTrue(isCacheWriteCalled);
486:
487: // make sure protocol handler has tried to call abort.
488: isAbortCalled = false;
489: is.close();
490: assertTrue(isAbortCalled);
491: uc.disconnect();
492: }
493:
494: /**
495: * @tests java.net.URLConnection#setUseCaches() and its real implementation
496: * in HttpURLConnection using a MockResponseCache returns a mock
497: * cache
498: */
499: public void test_UseCache_HttpURLConnection_Cached()
500: throws IOException {
501: ResponseCache.setDefault(new MockCachedResponseCache());
502: URL u = new URL("http://"
503: + Support_Configuration.InetTestAddress);
504: HttpURLConnection uc = (HttpURLConnection) u.openConnection();
505:
506: // default useCaches is true
507: assertTrue(uc.getUseCaches());
508:
509: // make sure ResponseCache.get/put is called
510: isGetCalled = false;
511: isPutCalled = false;
512: InputStream is = uc.getInputStream();
513: assertTrue(is instanceof MockInputStream);
514: assertTrue(isGetCalled);
515:
516: // make sure protocol handler doesn't try to write to cache, since
517: // it has been in cache already.
518: isCacheWriteCalled = false;
519: is.read();
520: assertFalse(isCacheWriteCalled);
521:
522: // make sure protocol handler doesn't try to write to cache, since
523: // it has been in cache already.
524: isCacheWriteCalled = false;
525: byte[] buf = new byte[1];
526: is.read(buf);
527: assertFalse(isCacheWriteCalled);
528:
529: // make sure protocol handler doesn't try to write to cache, since
530: // it has been in cache already.
531: isCacheWriteCalled = false;
532: buf = new byte[1];
533: is.read(buf, 0, 1);
534: assertFalse(isCacheWriteCalled);
535:
536: // make sure abort is not called since no write is performed
537: isAbortCalled = false;
538: is.close();
539: assertFalse(isAbortCalled);
540: uc.disconnect();
541: }
542:
543: /**
544: * @tests java.net.URLConnection#setUseCaches() and its real implementation
545: * in HttpURLConnection using getHeaderFields()
546: */
547: public void test_UseCache_HttpURLConnection_getHeaderFields()
548: throws IOException {
549: ResponseCache.setDefault(new MockCachedResponseCache());
550: URL u = new URL("http://"
551: + Support_Configuration.InetTestAddress);
552: HttpURLConnection uc = (HttpURLConnection) u.openConnection();
553: Map<String, List<String>> headerMap = uc.getHeaderFields();
554: assertTrue(isGetCalled);
555: assertFalse(isPutCalled);
556: assertEquals(mockHeaderMap, headerMap);
557: assertEquals(uc.getInputStream(), mockIs);
558: uc.disconnect();
559: }
560:
561: /**
562: * @tests java.net.URLConnection#setUseCaches() and its real implementation
563: * in HttpURLConnection using GetOutputStream()
564: */
565: public void test_UseCache_HttpURLConnection_NoCached_GetOutputStream()
566: throws Exception {
567: ResponseCache.setDefault(new MockNonCachedResponseCache());
568: uc = (HttpURLConnection) url.openConnection();
569: uc.setChunkedStreamingMode(10);
570: uc.setDoOutput(true);
571: uc.getOutputStream();
572: assertTrue(isGetCalled);
573: assertFalse(isPutCalled);
574: assertFalse(isAbortCalled);
575: uc.disconnect();
576: }
577:
578: /**
579: * @tests java.net.URLConnection#getErrorStream()
580: */
581: public void test_getErrorStream() throws Exception {
582: uc.setDoOutput(true);
583: uc.connect();
584: assertEquals(200, uc.getResponseCode());
585: // no error stream
586: assertNull(uc.getErrorStream());
587: uc.disconnect();
588: assertNull(uc.getErrorStream());
589: }
590:
591: /**
592: * @tests java.net.URLConnection#getPermission()
593: */
594: public void test_Permission() throws Exception {
595: uc.connect();
596: Permission permission = uc.getPermission();
597: assertNotNull(permission);
598: permission
599: .implies(new SocketPermission("localhost", "connect"));
600: }
601:
602: class MockNonCachedResponseCache extends ResponseCache {
603:
604: public CacheResponse get(URI arg0, String arg1, Map arg2)
605: throws IOException {
606: isGetCalled = true;
607: return null;
608: }
609:
610: public CacheRequest put(URI arg0, URLConnection arg1)
611: throws IOException {
612: isPutCalled = true;
613: return new MockCacheRequest();
614: }
615: }
616:
617: class MockCachedResponseCache extends ResponseCache {
618:
619: public CacheResponse get(URI arg0, String arg1, Map arg2)
620: throws IOException {
621: if (null == arg0 || null == arg1 || null == arg2) {
622: throw new NullPointerException();
623: }
624: isGetCalled = true;
625: return new MockCacheResponse();
626: }
627:
628: public CacheRequest put(URI arg0, URLConnection arg1)
629: throws IOException {
630: if (null == arg0 || null == arg1) {
631: throw new NullPointerException();
632: }
633: isPutCalled = true;
634: return new MockCacheRequest();
635: }
636: }
637:
638: class MockCacheRequest extends CacheRequest {
639:
640: public OutputStream getBody() throws IOException {
641: isCacheWriteCalled = true;
642: return new MockOutputStream();
643: }
644:
645: public void abort() {
646: isAbortCalled = true;
647: }
648:
649: }
650:
651: class MockCacheResponse extends CacheResponse {
652:
653: public Map<String, List<String>> getHeaders()
654: throws IOException {
655: return mockHeaderMap;
656: }
657:
658: public InputStream getBody() throws IOException {
659: return mockIs;
660: }
661: }
662:
663: class MockInputStream extends InputStream {
664:
665: public int read() throws IOException {
666: return 1;
667: }
668:
669: public int read(byte[] arg0, int arg1, int arg2)
670: throws IOException {
671: return 1;
672: }
673:
674: public int read(byte[] arg0) throws IOException {
675: return 1;
676: }
677:
678: }
679:
680: class MockOutputStream extends OutputStream {
681:
682: public void write(int b) throws IOException {
683: isCacheWriteCalled = true;
684: }
685:
686: public void write(byte[] b, int off, int len)
687: throws IOException {
688: isCacheWriteCalled = true;
689: }
690:
691: public void write(byte[] b) throws IOException {
692: isCacheWriteCalled = true;
693: }
694: }
695:
696: class MockHttpConnection extends HttpURLConnection {
697:
698: protected MockHttpConnection(URL url) {
699: super (url);
700: }
701:
702: public void disconnect() {
703: // do nothing
704: }
705:
706: public boolean usingProxy() {
707: return false;
708: }
709:
710: public void connect() throws IOException {
711: // do nothing
712: }
713:
714: public int getChunkLength() {
715: return super .chunkLength;
716: }
717:
718: public int getFixedLength() {
719: return super .fixedContentLength;
720: }
721:
722: }
723:
724: protected void setUp() {
725: try {
726: url = new URL("http://localhost:" + port + "/");
727: uc = (HttpURLConnection) url.openConnection();
728: } catch (Exception e) {
729: fail("Exception during setup : " + e.getMessage());
730: }
731: mockHeaderMap = new Hashtable<String, List<String>>();
732: List<String> valueList = new ArrayList<String>();
733: valueList.add("value1");
734: mockHeaderMap.put("field1", valueList);
735: mockHeaderMap.put("field2", valueList);
736: isGetCalled = false;
737: isPutCalled = false;
738: isCacheWriteCalled = false;
739: }
740:
741: protected void tearDown() {
742: uc.disconnect();
743: ResponseCache.setDefault(null);
744: }
745: }
|