adjust the code
[vfc/nfvo/wfengine.git] / rest-client / src / test / java / org / openo / baseservice / roa / util / restclient / TestRestHttpContentExchange.java
1 /*
2  * Copyright (c) 2016, Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * 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
17 package org.openo.baseservice.roa.util.restclient;
18
19 import static org.junit.Assert.assertEquals;
20 import static org.junit.Assert.assertFalse;
21 import static org.junit.Assert.assertTrue;
22
23 import org.openo.baseservice.remoteservice.exception.ServiceException;
24
25 import org.apache.log4j.Level;
26 import org.apache.log4j.LogManager;
27 import org.eclipse.jetty.client.Address;
28 import org.eclipse.jetty.client.CachedExchange;
29 import org.eclipse.jetty.client.HttpDestination;
30 import org.eclipse.jetty.client.HttpExchange;
31 import org.eclipse.jetty.http.HttpFields;
32 import org.eclipse.jetty.http.HttpHeaders;
33 import org.eclipse.jetty.io.Buffer;
34 import org.eclipse.jetty.io.ByteArrayBuffer;
35 import org.eclipse.jetty.util.StringUtil;
36 import org.junit.After;
37 import org.junit.AfterClass;
38 import org.junit.Before;
39 import org.junit.BeforeClass;
40 import org.junit.Rule;
41 import org.junit.Test;
42 import org.junit.rules.ExpectedException;
43 import org.junit.runner.RunWith;
44
45 import java.io.ByteArrayInputStream;
46 import java.io.IOException;
47 import java.io.InputStream;
48 import java.io.InputStreamReader;
49 import java.lang.reflect.Field;
50 import java.util.ArrayList;
51 import java.util.List;
52 import java.util.concurrent.atomic.AtomicInteger;
53 import java.util.zip.GZIPInputStream;
54
55 import mockit.Mock;
56 import mockit.MockUp;
57 import mockit.Mocked;
58 import mockit.integration.junit4.JMockit;
59
60 /**
61  * <br/>
62  * <p>
63  * </p>
64  * 
65  * @author
66  * @version SDNO 0.5 20-Jun-2016
67  */
68 @RunWith(JMockit.class)
69 public class TestRestHttpContentExchange {
70
71     @Mocked
72     HttpDestination mockedDest;
73
74     @Rule
75     public ExpectedException thrown = ExpectedException.none();
76
77     /**
78      * <br/>
79      * 
80      * @throws java.lang.Exception
81      * @since SDNO 0.5
82      */
83     @BeforeClass
84     public static void setUpBeforeClass() throws Exception {
85     }
86
87     /**
88      * <br/>
89      * 
90      * @throws java.lang.Exception
91      * @since SDNO 0.5
92      */
93     @AfterClass
94     public static void tearDownAfterClass() throws Exception {
95     }
96
97     /**
98      * <br/>
99      * 
100      * @throws java.lang.Exception
101      * @since SDNO 0.5
102      */
103     @Before
104     public void setUp() throws Exception {
105     }
106
107     /**
108      * <br/>
109      * 
110      * @throws java.lang.Exception
111      * @since SDNO 0.5
112      */
113     @After
114     public void tearDown() throws Exception {
115         LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.ERROR);
116     }
117
118     /**
119      * <br/>
120      * 
121      * @throws IOException
122      * @since SDNO 0.5
123      */
124     @Test
125     public void testOnRequestCommitted() throws IOException {
126         final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
127         final Address address = new Address("localhost", 9999);
128         exchange.setAddress(address);
129         exchange.setRequestURI("/the/request/uri");
130         exchange.onRequestCommitted();
131
132         LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.DEBUG);
133         exchange.onRequestCommitted();
134     }
135
136     /**
137      * <br/>
138      * 
139      * @throws IOException
140      * @since SDNO 0.5
141      */
142     @Test
143     public void testOnRequestComplete() throws IOException {
144         final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
145         final Address address = new Address("localhost", 9999);
146         exchange.setAddress(address);
147         exchange.setRequestURI("/the/request/uri");
148         exchange.onRequestComplete();
149
150         LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.DEBUG);
151         exchange.onRequestComplete();
152     }
153
154     /**
155      * <br/>
156      * 
157      * @throws Exception
158      * @since SDNO 0.5
159      */
160     @Test
161     public void testOnResponseComplete() throws Exception {
162         RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
163         final Address address = new Address("localhost", 9999);
164         exchange.setAddress(address);
165         exchange.setRequestURI("/the/request/uri");
166         exchange.onResponseComplete();
167
168         LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.DEBUG);
169         exchange.onResponseComplete();
170
171         final AtomicInteger isCallback = new AtomicInteger(0);
172         final AtomicInteger isException = new AtomicInteger(0);
173         final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
174
175             @Override
176             public void callback(final RestfulResponse response) {
177                 isCallback.set(1);
178             }
179
180             @Override
181             public void handleExcepion(final Throwable e) {
182                 isException.set(1);
183             }
184
185         };
186
187         final Field statusField = HttpExchange.class.getDeclaredField("_status");
188         statusField.setAccessible(true);
189         exchange = new RestHttpContentExchange(false, callback);
190         statusField.set(exchange, new AtomicInteger(200));
191         exchange.setAddress(new Address("localhost", 9999));
192         exchange.setRequestURI("/the/request/uri");
193         exchange.onResponseComplete();
194         assertEquals(1, isCallback.get());
195         assertEquals(0, isException.get());
196     }
197
198     /**
199      * <br/>
200      * 
201      * @throws Exception
202      * @since SDNO 0.5
203      */
204     @Test
205     public void testDecompressGzipToStr() throws Exception {
206         final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
207         final Address address = new Address("localhost", 9999);
208         exchange.setAddress(address);
209         exchange.setRequestURI("/the/request/uri");
210
211         final InputStream stream = ClassLoader.getSystemResourceAsStream("sample.txt.gz");
212         final byte[] binaryData = new byte[1024];
213         stream.read(binaryData);
214         final String expected = "sample data.";
215
216         final String actual = exchange.decompressGzipToStr(binaryData);
217
218         System.out.println("actual: '" + actual + "'");
219         System.out.println("expected: '" + expected + "'");
220         assertEquals(actual, expected);
221
222         new MockUp<ByteArrayInputStream>() {
223
224             @Mock
225             public int read() throws Exception {
226                 throw new IOException();
227             }
228
229             @Mock
230             public int read(final byte abyte0[], final int i, final int j) {
231
232                 return -1;
233             }
234
235         };
236
237         thrown.expect(IOException.class);
238         exchange.decompressGzipToStr(binaryData);
239     }
240
241     /**
242      * <br/>
243      * 
244      * @throws Exception
245      * @since SDNO 0.5
246      */
247     @Test
248     public void testDecompressGzipToStrException() throws Exception {
249         final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
250         final Address address = new Address("localhost", 9999);
251         exchange.setAddress(address);
252         exchange.setRequestURI("/the/request/uri");
253
254         final InputStream stream = ClassLoader.getSystemResourceAsStream("sample.txt.gz");
255         final byte[] binaryData = new byte[1024];
256         stream.read(binaryData);
257         final String expected = "sample data.";
258
259         new MockUp<GZIPInputStream>() {
260
261             @Mock
262             public void close() throws IOException {
263                 throw new IOException();
264             }
265
266         };
267
268         new MockUp<InputStreamReader>() {
269
270             @Mock
271             public void close() throws IOException {
272                 throw new IOException();
273             }
274
275         };
276
277         new MockUp<ByteArrayInputStream>() {
278
279             @Mock
280             public void close() throws IOException {
281                 throw new IOException();
282             }
283
284         };
285
286         final String actual = exchange.decompressGzipToStr(binaryData);
287
288         System.out.println("actual: '" + actual + "'");
289         System.out.println("expected: '" + expected + "'");
290         assertEquals(actual, expected);
291     }
292
293     /**
294      * <br/>
295      * 
296      * @throws Exception
297      * @since SDNO 0.5
298      */
299     @Test
300     public void testDecompressGzipToStrNull() throws Exception {
301         final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
302         final Address address = new Address("localhost", 9999);
303         exchange.setAddress(address);
304         exchange.setRequestURI("/the/request/uri");
305         final String expected = "";
306         final String actual = exchange.decompressGzipToStr(null);
307
308         System.out.println("actual: '" + actual + "'");
309         System.out.println("expected: '" + expected + "'");
310         assertEquals(actual, expected);
311     }
312
313     /**
314      * <br/>
315      * 
316      * @throws Exception
317      * @since SDNO 0.5
318      */
319     @Test
320     public void testOnResponseHeaderBufferBuffer() throws Exception {
321         final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
322         final Address address = new Address("localhost", 9999);
323         exchange.setAddress(address);
324         exchange.setRequestURI("/the/request/uri");
325
326         final Buffer name = new ByteArrayBuffer("key");
327         final Buffer value = new ByteArrayBuffer("value");
328         exchange.onResponseHeader(name, value);
329
330         new MockUp<HttpHeaders>() {
331
332             @Mock
333             public int getOrdinal(final Buffer buffer) {
334                 return HttpHeaders.CONTENT_ENCODING_ORDINAL;
335             }
336
337         };
338         exchange.onResponseHeader(name, value);
339
340         new MockUp<StringUtil>() {
341
342             @Mock
343             public String asciiToLowerCase(final String s) {
344                 return "gzip";
345             }
346
347         };
348         exchange.onResponseHeader(name, value);
349
350     }
351
352     /**
353      * <br/>
354      * 
355      * @since SDNO 0.5
356      */
357     @Test
358     public void testOnExceptionThrowable() {
359         final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
360         final Address address = new Address("localhost", 9999);
361         exchange.setAddress(address);
362         exchange.setRequestURI("/the/request/uri");
363         exchange.onException(new Exception());
364     }
365
366     /**
367      * <br/>
368      * 
369      * @since SDNO 0.5
370      */
371     @Test
372     public void testOnExceptionThrowableWithCallback() {
373         final AtomicInteger isCallback = new AtomicInteger(0);
374         final AtomicInteger isException = new AtomicInteger(0);
375         final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
376
377             @Override
378             public void callback(final RestfulResponse response) {
379                 isCallback.set(1);
380             }
381
382             @Override
383             public void handleExcepion(final Throwable e) {
384                 isException.set(1);
385             }
386
387         };
388         final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback);
389         final Address address = new Address("localhost", 9999);
390         exchange.setAddress(address);
391         exchange.setRequestURI("/the/request/uri");
392         exchange.onException(new Exception());
393         assertEquals(0, isCallback.get());
394         assertEquals(1, isException.get());
395     }
396
397     /**
398      * <br/>
399      * 
400      * @since SDNO 0.5
401      */
402     @Test
403     public void testOnConnectionFailedThrowable() {
404         final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
405         final Address address = new Address("localhost", 9999);
406         exchange.setAddress(address);
407         exchange.setRequestURI("/the/request/uri");
408         exchange.onConnectionFailed(new Exception());
409     }
410
411     /**
412      * <br/>
413      * 
414      * @since SDNO 0.5
415      */
416     @Test
417     public void testOnConnectionFailedThrowableException() {
418         final AtomicInteger isCallback = new AtomicInteger(0);
419         final AtomicInteger isException = new AtomicInteger(0);
420         final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
421
422             @Override
423             public void callback(final RestfulResponse response) {
424                 isCallback.set(1);
425             }
426
427             @Override
428             public void handleExcepion(final Throwable e) {
429                 isException.set(1);
430             }
431
432         };
433         final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback);
434         final Address address = new Address("localhost", 9999);
435         exchange.setAddress(address);
436         exchange.setRequestURI("/the/request/uri");
437         exchange.onConnectionFailed(new Exception());
438         assertEquals(0, isCallback.get());
439         assertEquals(1, isException.get());
440     }
441
442     /**
443      * <br/>
444      * 
445      * @since SDNO 0.5
446      */
447     @Test
448     public void testExpireHttpDestination() {
449         final RestHttpContentExchange exchange = new RestHttpContentExchange(true, null);
450         final Address address = new Address("localhost", 9999);
451         exchange.setAddress(address);
452         exchange.setRequestURI("/the/request/uri");
453         exchange.expire(mockedDest);
454     }
455
456     /**
457      * <br/>
458      * 
459      * @throws Exception
460      * @since SDNO 0.5
461      */
462     @Test
463     public void testExpireHttpDestinationException() throws Exception {
464         final AtomicInteger isCallback = new AtomicInteger(0);
465         final AtomicInteger isException = new AtomicInteger(0);
466         final List<Throwable> thrSet = new ArrayList<Throwable>();
467         final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
468
469             @Override
470             public void callback(final RestfulResponse response) {
471                 isCallback.set(1);
472             }
473
474             @Override
475             public void handleExcepion(final Throwable e) {
476                 isException.set(1);
477                 thrSet.add(e);
478             }
479
480         };
481         final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback);
482         final Address address = new Address("localhost", 9999);
483         exchange.setAddress(address);
484         exchange.setRequestURI("/the/request/uri");
485         exchange.expire(mockedDest);
486         assertEquals(0, isCallback.get());
487         assertEquals(1, isException.get());
488         assertEquals(1, thrSet.size());
489         final Throwable t = thrSet.get(0);
490         assertEquals(ServiceException.class, t.getClass());
491     }
492
493     /**
494      * <br/>
495      * 
496      * @throws Exception
497      * @since SDNO 0.5
498      */
499     @Test
500     public void testIsGzip() throws Exception {
501         final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
502         final Address address = new Address("localhost", 9999);
503         exchange.setAddress(address);
504         exchange.setRequestURI("/the/request/uri");
505
506         final Buffer name = new ByteArrayBuffer("key");
507         final Buffer value = new ByteArrayBuffer("value");
508
509         new MockUp<HttpHeaders>() {
510
511             @Mock
512             public int getOrdinal(final Buffer buffer) {
513                 return HttpHeaders.CONTENT_ENCODING_ORDINAL;
514             }
515
516         };
517         exchange.onResponseHeader(name, value);
518         assertFalse(exchange.isGzip());
519
520         new MockUp<StringUtil>() {
521
522             @Mock
523             public String asciiToLowerCase(final String s) {
524                 return "gzip";
525             }
526
527         };
528         exchange.onResponseHeader(name, value);
529         assertTrue(exchange.isGzip());
530     }
531
532     /**
533      * <br/>
534      * 
535      * @throws Exception
536      * @since SDNO 0.5
537      */
538     @Test
539     public void testGetResponse() throws Exception {
540         final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
541         final Address address = new Address("localhost", 9999);
542         exchange.setAddress(address);
543         exchange.setRequestURI("/the/request/uri");
544
545         final Field statusField = HttpExchange.class.getDeclaredField("_status");
546         statusField.setAccessible(true);
547         statusField.set(exchange, new AtomicInteger(200));
548
549         RestfulResponse response = exchange.getResponse();
550         assertEquals(0, response.getStatus());
551
552         final HttpFields fields = new HttpFields();
553         final Field headerFields = CachedExchange.class.getDeclaredField("_responseFields");
554         headerFields.setAccessible(true);
555         headerFields.set(exchange, fields);
556         response = exchange.getResponse();
557         assertEquals(0, response.getStatus());
558         fields.add("Content-Type", "application/json");
559         fields.add("Content-Encode", "UTF-8");
560         response = exchange.getResponse();
561         assertEquals(0, response.getStatus());
562     }
563
564     /**
565      * <br/>
566      * 
567      * @throws Exception
568      * @since SDNO 0.5
569      */
570     @Test
571     public void testGetResponseGzip() throws Exception {
572         final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
573         final Address address = new Address("localhost", 9999);
574         exchange.setAddress(address);
575         exchange.setRequestURI("/the/request/uri");
576         new MockUp<RestHttpContentExchange>() {
577
578             @Mock
579             public boolean isGzip() {
580                 return true;
581             }
582         };
583         final Field statusField = HttpExchange.class.getDeclaredField("_status");
584         statusField.setAccessible(true);
585         statusField.set(exchange, new AtomicInteger(200));
586
587         final RestfulResponse response = exchange.getResponse();
588         assertEquals(0, response.getStatus());
589     }
590 }