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.H1Config;
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(H1Config.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)).shutdownInput();
120         Mockito.verify(socket, Mockito.times(1)).shutdownOutput();
121         Mockito.verify(socket, Mockito.times(1)).close();
122 
123         conn.close();
124         Mockito.verify(socket, Mockito.times(1)).close();
125         Mockito.verify(outStream, Mockito.times(1)).write(
126                 ArgumentMatchers.<byte[]>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt());
127     }
128 
129     @Test
130     public void testConnectionShutdown() throws Exception {
131         final InputStream inStream = Mockito.mock(InputStream.class);
132         final OutputStream outStream = Mockito.mock(OutputStream.class);
133         Mockito.when(socket.getInputStream()).thenReturn(inStream);
134         Mockito.when(socket.getOutputStream()).thenReturn(outStream);
135 
136         conn.bind(socket);
137         conn.ensureOpen();
138         conn.outbuffer.write(0, outStream);
139 
140         Assert.assertTrue(conn.isOpen());
141 
142         conn.close(CloseMode.GRACEFUL);
143 
144         Assert.assertFalse(conn.isOpen());
145 
146         Mockito.verify(outStream, Mockito.never()).write(
147                 ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt());
148         Mockito.verify(socket, Mockito.never()).shutdownInput();
149         Mockito.verify(socket, Mockito.never()).shutdownOutput();
150         Mockito.verify(socket, Mockito.times(1)).close();
151 
152         conn.close();
153         Mockito.verify(socket, Mockito.times(1)).close();
154 
155         conn.close(CloseMode.GRACEFUL);
156         Mockito.verify(socket, Mockito.times(1)).close();
157     }
158 
159     @Test
160     public void testCreateEntityLengthDelimited() throws Exception {
161         final InputStream inStream = Mockito.mock(InputStream.class);
162         final ClassicHttpResponse message = new BasicClassicHttpResponse(200, "OK");
163         message.addHeader("Content-Length", "10");
164         message.addHeader("Content-Type", "stuff");
165         message.addHeader("Content-Encoding", "chunked");
166         final HttpEntity entity = conn.createIncomingEntity(message, conn.inBuffer, inStream, 10);
167         Assert.assertNotNull(entity);
168         Assert.assertFalse(entity.isChunked());
169         Assert.assertEquals(10, entity.getContentLength());
170         Assert.assertEquals("stuff", entity.getContentType());
171         Assert.assertEquals("chunked", entity.getContentEncoding());
172         final InputStream content = entity.getContent();
173         Assert.assertNotNull(content);
174         Assert.assertTrue((content instanceof ContentLengthInputStream));
175     }
176 
177     @Test
178     public void testCreateEntityInputChunked() throws Exception {
179         final InputStream inStream = Mockito.mock(InputStream.class);
180         final ClassicHttpResponse message = new BasicClassicHttpResponse(200, "OK");
181         final HttpEntity entity = conn.createIncomingEntity(message, conn.inBuffer, inStream, ContentLengthStrategy.CHUNKED);
182         Assert.assertNotNull(entity);
183         Assert.assertTrue(entity.isChunked());
184         Assert.assertEquals(-1, entity.getContentLength());
185         final InputStream content = entity.getContent();
186         Assert.assertNotNull(content);
187         Assert.assertTrue((content instanceof ChunkedInputStream));
188     }
189 
190     @Test
191     public void testCreateEntityInputUndefined() throws Exception {
192         final InputStream inStream = Mockito.mock(InputStream.class);
193         final ClassicHttpResponse message = new BasicClassicHttpResponse(200, "OK");
194         final HttpEntity entity = conn.createIncomingEntity(message, conn.inBuffer, inStream, ContentLengthStrategy.UNDEFINED);
195         Assert.assertNotNull(entity);
196         Assert.assertFalse(entity.isChunked());
197         Assert.assertEquals(-1, entity.getContentLength());
198         final InputStream content = entity.getContent();
199         Assert.assertNotNull(content);
200         Assert.assertTrue((content instanceof IdentityInputStream));
201     }
202 
203     @Test
204     public void testSetSocketTimeout() throws Exception {
205         conn.bind(socket);
206 
207         conn.setSocketTimeout(Timeout.ofMilliseconds(123));
208 
209         Mockito.verify(socket, Mockito.times(1)).setSoTimeout(123);
210     }
211 
212     @Test
213     public void testSetSocketTimeoutException() throws Exception {
214         conn.bind(socket);
215 
216         Mockito.doThrow(new SocketException()).when(socket).setSoTimeout(ArgumentMatchers.anyInt());
217 
218         conn.setSocketTimeout(Timeout.ofMilliseconds(123));
219 
220         Mockito.verify(socket, Mockito.times(1)).setSoTimeout(123);
221     }
222 
223     @Test
224     public void testGetSocketTimeout() throws Exception {
225         Assert.assertEquals(Timeout.DISABLED, conn.getSocketTimeout());
226 
227         Mockito.when(socket.getSoTimeout()).thenReturn(345);
228         conn.bind(socket);
229 
230         Assert.assertEquals(Timeout.ofMilliseconds(345), conn.getSocketTimeout());
231     }
232 
233     @Test
234     public void testGetSocketTimeoutException() throws Exception {
235         Assert.assertEquals(Timeout.DISABLED, conn.getSocketTimeout());
236 
237         Mockito.when(socket.getSoTimeout()).thenThrow(new SocketException());
238         conn.bind(socket);
239 
240         Assert.assertEquals(Timeout.DISABLED, conn.getSocketTimeout());
241     }
242 
243     @Test
244     public void testAwaitInputInBuffer() throws Exception {
245         final ByteArrayInputStream inStream = Mockito.spy(new ByteArrayInputStream(
246                 new byte[] {1, 2, 3, 4, 5}));
247         Mockito.when(socket.getInputStream()).thenReturn(inStream);
248 
249         conn.bind(socket);
250         conn.ensureOpen();
251         conn.inBuffer.read(inStream);
252 
253         Assert.assertTrue(conn.awaitInput(432));
254 
255         Mockito.verify(socket, Mockito.never()).setSoTimeout(ArgumentMatchers.anyInt());
256         Mockito.verify(inStream, Mockito.times(1)).read(
257                 ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt());
258     }
259 
260     @Test
261     public void testAwaitInputInSocket() throws Exception {
262         final ByteArrayInputStream inStream = Mockito.spy(new ByteArrayInputStream(
263                 new byte[] {1, 2, 3, 4, 5}));
264         Mockito.when(socket.getInputStream()).thenReturn(inStream);
265         Mockito.when(socket.getSoTimeout()).thenReturn(345);
266 
267         conn.bind(socket);
268         conn.ensureOpen();
269 
270         Assert.assertTrue(conn.awaitInput(432));
271 
272         Mockito.verify(socket, Mockito.times(1)).setSoTimeout(432);
273         Mockito.verify(socket, Mockito.times(1)).setSoTimeout(345);
274         Mockito.verify(inStream, Mockito.times(1)).read(
275                 ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt());
276     }
277 
278     @Test
279     public void testAwaitInputNoData() throws Exception {
280         final InputStream inStream = Mockito.mock(InputStream.class);
281         Mockito.when(socket.getInputStream()).thenReturn(inStream);
282         Mockito.when(inStream.read(ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
283             .thenReturn(-1);
284 
285         conn.bind(socket);
286         conn.ensureOpen();
287 
288         Assert.assertFalse(conn.awaitInput(432));
289     }
290 
291     @Test
292     public void testStaleWhenClosed() throws Exception {
293         final OutputStream outStream = Mockito.mock(OutputStream.class);
294 
295         Mockito.when(socket.getOutputStream()).thenReturn(outStream);
296 
297         conn.bind(socket);
298         conn.ensureOpen();
299         conn.close();
300         Assert.assertTrue(conn.isStale());
301     }
302 
303     @Test
304     public void testNotStaleWhenHasData() throws Exception {
305         final ByteArrayInputStream inStream = Mockito.spy(new ByteArrayInputStream(
306                 new byte[] {1, 2, 3, 4, 5}));
307         Mockito.when(socket.getInputStream()).thenReturn(inStream);
308 
309         conn.bind(socket);
310         conn.ensureOpen();
311 
312         Assert.assertFalse(conn.isStale());
313     }
314 
315     @Test
316     public void testStaleWhenEndOfStream() throws Exception {
317         final InputStream inStream = Mockito.mock(InputStream.class);
318         Mockito.when(socket.getInputStream()).thenReturn(inStream);
319         Mockito.when(inStream.read(ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
320             .thenReturn(-1);
321 
322         conn.bind(socket);
323         conn.ensureOpen();
324 
325         Assert.assertTrue(conn.isStale());
326     }
327 
328     @Test
329     public void testNotStaleWhenTimeout() throws Exception {
330         final InputStream inStream = Mockito.mock(InputStream.class);
331         Mockito.when(socket.getInputStream()).thenReturn(inStream);
332         Mockito.when(inStream.read(ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
333             .thenThrow(new SocketTimeoutException());
334 
335         conn.bind(socket);
336         conn.ensureOpen();
337 
338         Assert.assertFalse(conn.isStale());
339     }
340 
341     @Test
342     public void testStaleWhenIOError() throws Exception {
343         final InputStream inStream = Mockito.mock(InputStream.class);
344         Mockito.when(socket.getInputStream()).thenReturn(inStream);
345         Mockito.when(inStream.read(ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
346             .thenThrow(new SocketException());
347 
348         conn.bind(socket);
349         conn.ensureOpen();
350 
351         Assert.assertTrue(conn.isStale());
352     }
353 
354 }