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.junit.Assert;
45  import org.junit.Before;
46  import org.junit.Test;
47  import org.mockito.ArgumentMatchers;
48  import org.mockito.Mock;
49  import org.mockito.Mockito;
50  import org.mockito.MockitoAnnotations;
51  
52  public class TestBHttpConnectionBase {
53  
54      @Mock
55      private Socket socket;
56  
57      private BHttpConnectionBase conn;
58  
59      @Before
60      public void setUp() throws Exception {
61          MockitoAnnotations.initMocks(this);
62          conn = new BHttpConnectionBase(H1Config.DEFAULT, null, null);
63      }
64  
65      @Test
66      public void testBasics() throws Exception {
67          Assert.assertFalse(conn.isOpen());
68          Assert.assertEquals(null, conn.getLocalAddress());
69          Assert.assertEquals(null, conn.getRemoteAddress());
70          Assert.assertEquals("[Not bound]", conn.toString());
71      }
72  
73      @Test
74      public void testSocketBind() throws Exception {
75          final InetAddress localAddress = InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
76          final int localPort = 8888;
77          final InetAddress remoteAddress = InetAddress.getByAddress(new byte[] {10, 0, 0, 2});
78          final int remotePort = 80;
79          final InetSocketAddress localSockAddress = new InetSocketAddress(localAddress, localPort);
80          final InetSocketAddress remoteSockAddress = new InetSocketAddress(remoteAddress, remotePort);
81          Mockito.when(socket.getLocalSocketAddress()).thenReturn(localSockAddress);
82          Mockito.when(socket.getRemoteSocketAddress()).thenReturn(remoteSockAddress);
83          Mockito.when(socket.getLocalAddress()).thenReturn(localAddress);
84          Mockito.when(socket.getLocalPort()).thenReturn(localPort);
85          Mockito.when(socket.getInetAddress()).thenReturn(remoteAddress);
86          Mockito.when(socket.getPort()).thenReturn(remotePort);
87          conn.bind(socket);
88  
89          Assert.assertEquals("127.0.0.1:8888<->10.0.0.2:80", conn.toString());
90          Assert.assertTrue(conn.isOpen());
91  
92          Assert.assertEquals(new InetSocketAddress(
93                  InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), 8888), conn.getLocalAddress());
94          Assert.assertEquals(new InetSocketAddress(
95                  InetAddress.getByAddress(new byte[] {10, 0, 0, 2}), 80), conn.getRemoteAddress());
96      }
97  
98      @Test
99      public void testConnectionClose() throws Exception {
100         final InputStream inStream = Mockito.mock(InputStream.class);
101         final OutputStream outStream = Mockito.mock(OutputStream.class);
102 
103         Mockito.when(socket.getInputStream()).thenReturn(inStream);
104         Mockito.when(socket.getOutputStream()).thenReturn(outStream);
105 
106         conn.bind(socket);
107         conn.ensureOpen();
108         conn.outbuffer.write(0, outStream);
109 
110         Assert.assertTrue(conn.isOpen());
111 
112         conn.close();
113 
114         Assert.assertFalse(conn.isOpen());
115 
116         Mockito.verify(outStream, Mockito.times(1)).write(
117                 ArgumentMatchers.<byte[]>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt());
118         Mockito.verify(socket, Mockito.times(1)).shutdownInput();
119         Mockito.verify(socket, Mockito.times(1)).shutdownOutput();
120         Mockito.verify(socket, Mockito.times(1)).close();
121 
122         conn.close();
123         Mockito.verify(socket, Mockito.times(1)).close();
124         Mockito.verify(outStream, Mockito.times(1)).write(
125                 ArgumentMatchers.<byte[]>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt());
126     }
127 
128     @Test
129     public void testConnectionShutdown() throws Exception {
130         final InputStream inStream = Mockito.mock(InputStream.class);
131         final OutputStream outStream = Mockito.mock(OutputStream.class);
132         Mockito.when(socket.getInputStream()).thenReturn(inStream);
133         Mockito.when(socket.getOutputStream()).thenReturn(outStream);
134 
135         conn.bind(socket);
136         conn.ensureOpen();
137         conn.outbuffer.write(0, outStream);
138 
139         Assert.assertTrue(conn.isOpen());
140 
141         conn.close(CloseMode.GRACEFUL);
142 
143         Assert.assertFalse(conn.isOpen());
144 
145         Mockito.verify(outStream, Mockito.never()).write(
146                 ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt());
147         Mockito.verify(socket, Mockito.never()).shutdownInput();
148         Mockito.verify(socket, Mockito.never()).shutdownOutput();
149         Mockito.verify(socket, Mockito.times(1)).close();
150 
151         conn.close();
152         Mockito.verify(socket, Mockito.times(1)).close();
153 
154         conn.close(CloseMode.GRACEFUL);
155         Mockito.verify(socket, Mockito.times(1)).close();
156     }
157 
158     @Test
159     public void testCreateEntityLengthDelimited() throws Exception {
160         final InputStream inStream = Mockito.mock(InputStream.class);
161         final ClassicHttpResponse message = new BasicClassicHttpResponse(200, "OK");
162         message.addHeader("Content-Length", "10");
163         message.addHeader("Content-Type", "stuff");
164         message.addHeader("Content-Encoding", "chunked");
165         final HttpEntity entity = conn.createIncomingEntity(message, conn.inBuffer, inStream, 10);
166         Assert.assertNotNull(entity);
167         Assert.assertFalse(entity.isChunked());
168         Assert.assertEquals(10, entity.getContentLength());
169         Assert.assertEquals("stuff", entity.getContentType());
170         Assert.assertEquals("chunked", entity.getContentEncoding());
171         final InputStream content = entity.getContent();
172         Assert.assertNotNull(content);
173         Assert.assertTrue((content instanceof ContentLengthInputStream));
174     }
175 
176     @Test
177     public void testCreateEntityInputChunked() throws Exception {
178         final InputStream inStream = Mockito.mock(InputStream.class);
179         final ClassicHttpResponse message = new BasicClassicHttpResponse(200, "OK");
180         final HttpEntity entity = conn.createIncomingEntity(message, conn.inBuffer, inStream, ContentLengthStrategy.CHUNKED);
181         Assert.assertNotNull(entity);
182         Assert.assertTrue(entity.isChunked());
183         Assert.assertEquals(-1, entity.getContentLength());
184         final InputStream content = entity.getContent();
185         Assert.assertNotNull(content);
186         Assert.assertTrue((content instanceof ChunkedInputStream));
187     }
188 
189     @Test
190     public void testCreateEntityInputUndefined() throws Exception {
191         final InputStream inStream = Mockito.mock(InputStream.class);
192         final ClassicHttpResponse message = new BasicClassicHttpResponse(200, "OK");
193         final HttpEntity entity = conn.createIncomingEntity(message, conn.inBuffer, inStream, ContentLengthStrategy.UNDEFINED);
194         Assert.assertNotNull(entity);
195         Assert.assertFalse(entity.isChunked());
196         Assert.assertEquals(-1, entity.getContentLength());
197         final InputStream content = entity.getContent();
198         Assert.assertNotNull(content);
199         Assert.assertTrue((content instanceof IdentityInputStream));
200     }
201 
202     @Test
203     public void testSetSocketTimeout() throws Exception {
204         conn.bind(socket);
205 
206         conn.setSocketTimeoutMillis(123);
207 
208         Mockito.verify(socket, Mockito.times(1)).setSoTimeout(123);
209     }
210 
211     @Test
212     public void testSetSocketTimeoutException() throws Exception {
213         conn.bind(socket);
214 
215         Mockito.doThrow(new SocketException()).when(socket).setSoTimeout(ArgumentMatchers.anyInt());
216 
217         conn.setSocketTimeoutMillis(123);
218 
219         Mockito.verify(socket, Mockito.times(1)).setSoTimeout(123);
220     }
221 
222     @Test
223     public void testGetSocketTimeout() throws Exception {
224         Assert.assertEquals(-1, conn.getSocketTimeoutMillis());
225 
226         Mockito.when(socket.getSoTimeout()).thenReturn(345);
227         conn.bind(socket);
228 
229         Assert.assertEquals(345, conn.getSocketTimeoutMillis());
230     }
231 
232     @Test
233     public void testGetSocketTimeoutException() throws Exception {
234         Assert.assertEquals(-1, conn.getSocketTimeoutMillis());
235 
236         Mockito.when(socket.getSoTimeout()).thenThrow(new SocketException());
237         conn.bind(socket);
238 
239         Assert.assertEquals(-1, conn.getSocketTimeoutMillis());
240     }
241 
242     @Test
243     public void testAwaitInputInBuffer() throws Exception {
244         final ByteArrayInputStream inStream = Mockito.spy(new ByteArrayInputStream(
245                 new byte[] {1, 2, 3, 4, 5}));
246         Mockito.when(socket.getInputStream()).thenReturn(inStream);
247 
248         conn.bind(socket);
249         conn.ensureOpen();
250         conn.inBuffer.read(inStream);
251 
252         Assert.assertTrue(conn.awaitInput(432));
253 
254         Mockito.verify(socket, Mockito.never()).setSoTimeout(ArgumentMatchers.anyInt());
255         Mockito.verify(inStream, Mockito.times(1)).read(
256                 ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt());
257     }
258 
259     @Test
260     public void testAwaitInputInSocket() throws Exception {
261         final ByteArrayInputStream inStream = Mockito.spy(new ByteArrayInputStream(
262                 new byte[] {1, 2, 3, 4, 5}));
263         Mockito.when(socket.getInputStream()).thenReturn(inStream);
264         Mockito.when(socket.getSoTimeout()).thenReturn(345);
265 
266         conn.bind(socket);
267         conn.ensureOpen();
268 
269         Assert.assertTrue(conn.awaitInput(432));
270 
271         Mockito.verify(socket, Mockito.times(1)).setSoTimeout(432);
272         Mockito.verify(socket, Mockito.times(1)).setSoTimeout(345);
273         Mockito.verify(inStream, Mockito.times(1)).read(
274                 ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt());
275     }
276 
277     @Test
278     public void testAwaitInputNoData() throws Exception {
279         final InputStream inStream = Mockito.mock(InputStream.class);
280         Mockito.when(socket.getInputStream()).thenReturn(inStream);
281         Mockito.when(inStream.read(ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
282             .thenReturn(-1);
283 
284         conn.bind(socket);
285         conn.ensureOpen();
286 
287         Assert.assertFalse(conn.awaitInput(432));
288     }
289 
290     @Test
291     public void testStaleWhenClosed() throws Exception {
292         final OutputStream outStream = Mockito.mock(OutputStream.class);
293 
294         Mockito.when(socket.getOutputStream()).thenReturn(outStream);
295 
296         conn.bind(socket);
297         conn.ensureOpen();
298         conn.close();
299         Assert.assertTrue(conn.isStale());
300     }
301 
302     @Test
303     public void testNotStaleWhenHasData() throws Exception {
304         final ByteArrayInputStream inStream = Mockito.spy(new ByteArrayInputStream(
305                 new byte[] {1, 2, 3, 4, 5}));
306         Mockito.when(socket.getInputStream()).thenReturn(inStream);
307 
308         conn.bind(socket);
309         conn.ensureOpen();
310 
311         Assert.assertFalse(conn.isStale());
312     }
313 
314     @Test
315     public void testStaleWhenEndOfStream() throws Exception {
316         final InputStream inStream = Mockito.mock(InputStream.class);
317         Mockito.when(socket.getInputStream()).thenReturn(inStream);
318         Mockito.when(inStream.read(ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
319             .thenReturn(-1);
320 
321         conn.bind(socket);
322         conn.ensureOpen();
323 
324         Assert.assertTrue(conn.isStale());
325     }
326 
327     @Test
328     public void testNotStaleWhenTimeout() throws Exception {
329         final InputStream inStream = Mockito.mock(InputStream.class);
330         Mockito.when(socket.getInputStream()).thenReturn(inStream);
331         Mockito.when(inStream.read(ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
332             .thenThrow(new SocketTimeoutException());
333 
334         conn.bind(socket);
335         conn.ensureOpen();
336 
337         Assert.assertFalse(conn.isStale());
338     }
339 
340     @Test
341     public void testStaleWhenIOError() throws Exception {
342         final InputStream inStream = Mockito.mock(InputStream.class);
343         Mockito.when(socket.getInputStream()).thenReturn(inStream);
344         Mockito.when(inStream.read(ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
345             .thenThrow(new SocketException());
346 
347         conn.bind(socket);
348         conn.ensureOpen();
349 
350         Assert.assertTrue(conn.isStale());
351     }
352 
353 }