View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.core5.http.impl.io;
28  
29  import java.io.ByteArrayInputStream;
30  import java.io.InputStream;
31  import java.io.OutputStream;
32  import java.net.InetAddress;
33  import java.net.InetSocketAddress;
34  import java.net.Socket;
35  import java.net.SocketException;
36  import java.net.SocketTimeoutException;
37  
38  import org.apache.hc.core5.http.ClassicHttpResponse;
39  import org.apache.hc.core5.http.ContentLengthStrategy;
40  import org.apache.hc.core5.http.HttpEntity;
41  import org.apache.hc.core5.http.config.Http1Config;
42  import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
43  import org.apache.hc.core5.io.CloseMode;
44  import org.apache.hc.core5.util.Timeout;
45  import org.junit.Assert;
46  import org.junit.Before;
47  import org.junit.Test;
48  import org.mockito.ArgumentMatchers;
49  import org.mockito.Mock;
50  import org.mockito.Mockito;
51  import org.mockito.MockitoAnnotations;
52  
53  public class TestBHttpConnectionBase {
54  
55      @Mock
56      private Socket socket;
57  
58      private BHttpConnectionBase conn;
59  
60      @Before
61      public void setUp() throws Exception {
62          MockitoAnnotations.initMocks(this);
63          conn = new BHttpConnectionBase(Http1Config.DEFAULT, null, null);
64      }
65  
66      @Test
67      public void testBasics() throws Exception {
68          Assert.assertFalse(conn.isOpen());
69          Assert.assertEquals(null, conn.getLocalAddress());
70          Assert.assertEquals(null, conn.getRemoteAddress());
71          Assert.assertEquals("[Not bound]", conn.toString());
72      }
73  
74      @Test
75      public void testSocketBind() throws Exception {
76          final InetAddress localAddress = InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
77          final int localPort = 8888;
78          final InetAddress remoteAddress = InetAddress.getByAddress(new byte[] {10, 0, 0, 2});
79          final int remotePort = 80;
80          final InetSocketAddress localSockAddress = new InetSocketAddress(localAddress, localPort);
81          final InetSocketAddress remoteSockAddress = new InetSocketAddress(remoteAddress, remotePort);
82          Mockito.when(socket.getLocalSocketAddress()).thenReturn(localSockAddress);
83          Mockito.when(socket.getRemoteSocketAddress()).thenReturn(remoteSockAddress);
84          Mockito.when(socket.getLocalAddress()).thenReturn(localAddress);
85          Mockito.when(socket.getLocalPort()).thenReturn(localPort);
86          Mockito.when(socket.getInetAddress()).thenReturn(remoteAddress);
87          Mockito.when(socket.getPort()).thenReturn(remotePort);
88          conn.bind(socket);
89  
90          Assert.assertEquals("127.0.0.1:8888<->10.0.0.2:80", conn.toString());
91          Assert.assertTrue(conn.isOpen());
92  
93          Assert.assertEquals(new InetSocketAddress(
94                  InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), 8888), conn.getLocalAddress());
95          Assert.assertEquals(new InetSocketAddress(
96                  InetAddress.getByAddress(new byte[] {10, 0, 0, 2}), 80), conn.getRemoteAddress());
97      }
98  
99      @Test
100     public void testConnectionClose() throws Exception {
101         final InputStream inStream = Mockito.mock(InputStream.class);
102         final OutputStream outStream = Mockito.mock(OutputStream.class);
103 
104         Mockito.when(socket.getInputStream()).thenReturn(inStream);
105         Mockito.when(socket.getOutputStream()).thenReturn(outStream);
106 
107         conn.bind(socket);
108         conn.ensureOpen();
109         conn.outbuffer.write(0, outStream);
110 
111         Assert.assertTrue(conn.isOpen());
112 
113         conn.close();
114 
115         Assert.assertFalse(conn.isOpen());
116 
117         Mockito.verify(outStream, Mockito.times(1)).write(
118                 ArgumentMatchers.<byte[]>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt());
119         Mockito.verify(socket, Mockito.times(1)).close();
120 
121         conn.close();
122         Mockito.verify(socket, Mockito.times(1)).close();
123         Mockito.verify(outStream, Mockito.times(1)).write(
124                 ArgumentMatchers.<byte[]>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt());
125     }
126 
127     @Test
128     public void testConnectionShutdown() throws Exception {
129         final InputStream inStream = Mockito.mock(InputStream.class);
130         final OutputStream outStream = Mockito.mock(OutputStream.class);
131         Mockito.when(socket.getInputStream()).thenReturn(inStream);
132         Mockito.when(socket.getOutputStream()).thenReturn(outStream);
133 
134         conn.bind(socket);
135         conn.ensureOpen();
136         conn.outbuffer.write(0, outStream);
137 
138         Assert.assertTrue(conn.isOpen());
139 
140         conn.close(CloseMode.GRACEFUL);
141 
142         Assert.assertFalse(conn.isOpen());
143 
144         Mockito.verify(outStream, Mockito.never()).write(
145                 ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt());
146         Mockito.verify(socket, Mockito.never()).shutdownInput();
147         Mockito.verify(socket, Mockito.never()).shutdownOutput();
148         Mockito.verify(socket, Mockito.times(1)).close();
149 
150         conn.close();
151         Mockito.verify(socket, Mockito.times(1)).close();
152 
153         conn.close(CloseMode.GRACEFUL);
154         Mockito.verify(socket, Mockito.times(1)).close();
155     }
156 
157     @Test
158     public void testCreateEntityLengthDelimited() throws Exception {
159         final InputStream inStream = Mockito.mock(InputStream.class);
160         final ClassicHttpResponse message = new BasicClassicHttpResponse(200, "OK");
161         message.addHeader("Content-Length", "10");
162         message.addHeader("Content-Type", "stuff");
163         message.addHeader("Content-Encoding", "chunked");
164         final HttpEntity entity = conn.createIncomingEntity(message, conn.inBuffer, inStream, 10);
165         Assert.assertNotNull(entity);
166         Assert.assertFalse(entity.isChunked());
167         Assert.assertEquals(10, entity.getContentLength());
168         Assert.assertEquals("stuff", entity.getContentType());
169         Assert.assertEquals("chunked", entity.getContentEncoding());
170         final InputStream content = entity.getContent();
171         Assert.assertNotNull(content);
172         Assert.assertTrue((content instanceof ContentLengthInputStream));
173     }
174 
175     @Test
176     public void testCreateEntityInputChunked() throws Exception {
177         final InputStream inStream = Mockito.mock(InputStream.class);
178         final ClassicHttpResponse message = new BasicClassicHttpResponse(200, "OK");
179         final HttpEntity entity = conn.createIncomingEntity(message, conn.inBuffer, inStream, ContentLengthStrategy.CHUNKED);
180         Assert.assertNotNull(entity);
181         Assert.assertTrue(entity.isChunked());
182         Assert.assertEquals(-1, entity.getContentLength());
183         final InputStream content = entity.getContent();
184         Assert.assertNotNull(content);
185         Assert.assertTrue((content instanceof ChunkedInputStream));
186     }
187 
188     @Test
189     public void testCreateEntityInputUndefined() throws Exception {
190         final InputStream inStream = Mockito.mock(InputStream.class);
191         final ClassicHttpResponse message = new BasicClassicHttpResponse(200, "OK");
192         final HttpEntity entity = conn.createIncomingEntity(message, conn.inBuffer, inStream, ContentLengthStrategy.UNDEFINED);
193         Assert.assertNotNull(entity);
194         Assert.assertFalse(entity.isChunked());
195         Assert.assertEquals(-1, entity.getContentLength());
196         final InputStream content = entity.getContent();
197         Assert.assertNotNull(content);
198         Assert.assertTrue((content instanceof IdentityInputStream));
199     }
200 
201     @Test
202     public void testSetSocketTimeout() throws Exception {
203         conn.bind(socket);
204 
205         conn.setSocketTimeout(Timeout.ofMilliseconds(123));
206 
207         Mockito.verify(socket, Mockito.times(1)).setSoTimeout(123);
208     }
209 
210     @Test
211     public void testSetSocketTimeoutException() throws Exception {
212         conn.bind(socket);
213 
214         Mockito.doThrow(new SocketException()).when(socket).setSoTimeout(ArgumentMatchers.anyInt());
215 
216         conn.setSocketTimeout(Timeout.ofMilliseconds(123));
217 
218         Mockito.verify(socket, Mockito.times(1)).setSoTimeout(123);
219     }
220 
221     @Test
222     public void testGetSocketTimeout() throws Exception {
223         Assert.assertEquals(Timeout.DISABLED, conn.getSocketTimeout());
224 
225         Mockito.when(socket.getSoTimeout()).thenReturn(345);
226         conn.bind(socket);
227 
228         Assert.assertEquals(Timeout.ofMilliseconds(345), conn.getSocketTimeout());
229     }
230 
231     @Test
232     public void testGetSocketTimeoutException() throws Exception {
233         Assert.assertEquals(Timeout.DISABLED, conn.getSocketTimeout());
234 
235         Mockito.when(socket.getSoTimeout()).thenThrow(new SocketException());
236         conn.bind(socket);
237 
238         Assert.assertEquals(Timeout.DISABLED, conn.getSocketTimeout());
239     }
240 
241     @Test
242     public void testAwaitInputInBuffer() throws Exception {
243         final ByteArrayInputStream inStream = new ByteArrayInputStream(
244                 new byte[] {1, 2, 3, 4, 5});
245         conn.bind(socket);
246         conn.ensureOpen();
247         conn.inBuffer.read(inStream);
248 
249         Assert.assertTrue(conn.awaitInput(Timeout.ofMilliseconds(432)));
250 
251         Mockito.verify(socket, Mockito.never()).setSoTimeout(ArgumentMatchers.anyInt());
252     }
253 
254     @Test
255     public void testAwaitInputInSocket() throws Exception {
256         final ByteArrayInputStream inStream = new ByteArrayInputStream(
257                 new byte[] {1, 2, 3, 4, 5});
258         Mockito.when(socket.getInputStream()).thenReturn(inStream);
259         Mockito.when(socket.getSoTimeout()).thenReturn(345);
260 
261         conn.bind(socket);
262         conn.ensureOpen();
263 
264         Assert.assertTrue(conn.awaitInput(Timeout.ofMilliseconds(432)));
265 
266         Mockito.verify(socket, Mockito.times(1)).setSoTimeout(432);
267         Mockito.verify(socket, Mockito.times(1)).setSoTimeout(345);
268     }
269 
270     @Test
271     public void testAwaitInputNoData() throws Exception {
272         final InputStream inStream = Mockito.mock(InputStream.class);
273         Mockito.when(socket.getInputStream()).thenReturn(inStream);
274         Mockito.when(inStream.read(ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
275             .thenReturn(-1);
276 
277         conn.bind(socket);
278         conn.ensureOpen();
279 
280         Assert.assertFalse(conn.awaitInput(Timeout.ofMilliseconds(432)));
281     }
282 
283     @Test
284     public void testStaleWhenClosed() throws Exception {
285         final OutputStream outStream = Mockito.mock(OutputStream.class);
286 
287         Mockito.when(socket.getOutputStream()).thenReturn(outStream);
288 
289         conn.bind(socket);
290         conn.ensureOpen();
291         conn.close();
292         Assert.assertTrue(conn.isStale());
293     }
294 
295     @Test
296     public void testNotStaleWhenHasData() throws Exception {
297         final ByteArrayInputStream inStream = new ByteArrayInputStream(
298                 new byte[] {1, 2, 3, 4, 5});
299         Mockito.when(socket.getInputStream()).thenReturn(inStream);
300 
301         conn.bind(socket);
302         conn.ensureOpen();
303 
304         Assert.assertFalse(conn.isStale());
305     }
306 
307     @Test
308     public void testStaleWhenEndOfStream() throws Exception {
309         final InputStream inStream = Mockito.mock(InputStream.class);
310         Mockito.when(socket.getInputStream()).thenReturn(inStream);
311         Mockito.when(inStream.read(ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
312             .thenReturn(-1);
313 
314         conn.bind(socket);
315         conn.ensureOpen();
316 
317         Assert.assertTrue(conn.isStale());
318     }
319 
320     @Test
321     public void testNotStaleWhenTimeout() throws Exception {
322         final InputStream inStream = Mockito.mock(InputStream.class);
323         Mockito.when(socket.getInputStream()).thenReturn(inStream);
324         Mockito.when(inStream.read(ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
325             .thenThrow(new SocketTimeoutException());
326 
327         conn.bind(socket);
328         conn.ensureOpen();
329 
330         Assert.assertFalse(conn.isStale());
331     }
332 
333     @Test
334     public void testStaleWhenIOError() throws Exception {
335         final InputStream inStream = Mockito.mock(InputStream.class);
336         Mockito.when(socket.getInputStream()).thenReturn(inStream);
337         Mockito.when(inStream.read(ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
338             .thenThrow(new SocketException());
339 
340         conn.bind(socket);
341         conn.ensureOpen();
342 
343         Assert.assertTrue(conn.isStale());
344     }
345 
346 }