File: SplitResponse.java

package info (click to toggle)
openjdk-11 11.0.4%2B11-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 757,028 kB
  • sloc: java: 5,016,041; xml: 1,191,974; cpp: 934,731; ansic: 555,697; sh: 24,299; objc: 12,703; python: 3,602; asm: 3,415; makefile: 2,772; awk: 351; sed: 172; perl: 114; jsp: 24; csh: 3
file content (298 lines) | stat: -rw-r--r-- 11,455 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/*
 * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

import java.io.IOException;
import java.net.SocketException;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import javax.net.ssl.SSLContext;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLServerSocketFactory;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.stream.Stream;

import jdk.testlibrary.SimpleSSLContext;
import static java.lang.System.out;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.net.http.HttpResponse.BodyHandlers.ofString;

/**
 * @test
 * @bug 8087112
 * @library /lib/testlibrary
 * @build jdk.testlibrary.SimpleSSLContext
 * @build MockServer
 * @run main/othervm
 *     -Djdk.internal.httpclient.debug=true
 *     -Djdk.httpclient.HttpClient.log=all
 *     SplitResponse HTTP connection:CLOSE mode:SYNC
 */

/**
 * Similar test to QuickResponses except that each byte of the response
 * is sent in a separate packet, which tests the stability of the implementation
 * for receiving unusual packet sizes. Additionally, tests scenarios there
 * connections that are retrieved from the connection pool may reach EOF before
 * being reused.
 */
public class SplitResponse {

    static String response(String body, boolean serverKeepalive) {
        StringBuilder sb = new StringBuilder();
        sb.append("HTTP/1.1 200 OK\r\n");
        if (!serverKeepalive)
            sb.append("Connection: Close\r\n");

        sb.append("Content-length: ")
                .append(body.getBytes(ISO_8859_1).length)
                .append("\r\n");
        sb.append("\r\n");
        sb.append(body);
        return sb.toString();
    }

    static final String responses[] = {
        "Lorem ipsum",
        "dolor sit amet",
        "consectetur adipiscing elit, sed do eiusmod tempor",
        "quis nostrud exercitation ullamco",
        "laboris nisi",
        "ut",
        "aliquip ex ea commodo consequat." +
        "Duis aute irure dolor in reprehenderit in voluptate velit esse" +
        "cillum dolore eu fugiat nulla pariatur.",
        "Excepteur sint occaecat cupidatat non proident."
    };

    final ServerSocketFactory factory;
    final SSLContext context;
    final boolean useSSL;
    SplitResponse(boolean useSSL) throws IOException {
        this.useSSL = useSSL;
        context = new SimpleSSLContext().get();
        SSLContext.setDefault(context);
        factory = useSSL ? SSLServerSocketFactory.getDefault()
                         : ServerSocketFactory.getDefault();
    }

    public HttpClient newHttpClient() {
        HttpClient client;
        if (useSSL) {
            client = HttpClient.newBuilder()
                               .sslContext(context)
                               .build();
        } else {
            client = HttpClient.newHttpClient();
        }
        return client;
    }

    enum Protocol {
        HTTP, HTTPS
    }
    enum Connection {
        KEEP_ALIVE,
        CLOSE
    }
    enum Mode {
        SYNC, ASYNC
    }


    public static void main(String[] args) throws Exception {
        boolean useSSL = false;
        if (args != null && args.length >= 1) {
            useSSL = Protocol.valueOf(args[0]).equals(Protocol.HTTPS);
        } else {
            args = new String[] {"HTTP", "connection:KEEP_ALIVE:CLOSE", "mode:SYNC:ASYNC"};
        }

        LinkedHashSet<Mode> modes = new LinkedHashSet<>();
        LinkedHashSet<Connection> keepAlive = new LinkedHashSet<>();
        Stream.of(args).skip(1).forEach(s -> {
            if (s.startsWith("connection:")) {
                Stream.of(s.split(":")).skip(1).forEach(c -> {
                    keepAlive.add(Connection.valueOf(c));
                });
            } else if (s.startsWith("mode:")) {
                Stream.of(s.split(":")).skip(1).forEach(m -> {
                    modes.add(Mode.valueOf(m));
                });
            } else {
                System.err.println("Illegal argument: " + s);
                System.err.println("Allowed syntax is: HTTP|HTTPS [connection:KEEP_ALIVE[:CLOSE]] [mode:SYNC[:ASYNC]");
                throw new IllegalArgumentException(s);
            }
        });

        if (keepAlive.isEmpty()) keepAlive.addAll(EnumSet.allOf(Connection.class));
        if (modes.isEmpty()) modes.addAll(EnumSet.allOf(Mode.class));

        SplitResponse sp = new SplitResponse(useSSL);

        for (Version version : Version.values()) {
            for (Connection serverKeepalive : keepAlive) {
                // Note: the mock server doesn't support Keep-Alive, but
                // pretending that it might exercises code paths in and out of
                // the connection pool, and retry logic
                for (Mode mode : modes) {
                    sp.test(version,serverKeepalive == Connection.KEEP_ALIVE,mode == Mode.ASYNC);
                }
            }
        }
    }

    // @Test
    void test(Version version, boolean serverKeepalive, boolean async)
        throws Exception
    {
        out.println(format("*** version %s, serverKeepAlive: %s, async: %s ***",
                           version, serverKeepalive, async));
        MockServer server = new MockServer(0, factory);
        URI uri = new URI(server.getURL());
        out.println("server is: " + uri);
        server.start();


        // The following code can be uncommented to verify that the
        // MockServer will reject rogue requests whose URI does not
        // contain "/foo/".
        //
        //        Thread rogue = new Thread() {
        //            public void run() {
        //                try {
        //                    HttpClient client = newHttpClient();
        //                    URI uri2 = URI.create(uri.toString().replace("/foo/","/"));
        //                    HttpRequest request = HttpRequest
        //                        .newBuilder(uri2).version(version).build();
        //                    while (true) {
        //                        try {
        //                            client.send(request, HttpResponse.BodyHandlers.ofString());
        //                        } catch (IOException ex) {
        //                            System.out.println("Client rejected " + request);
        //                        }
        //                        sleep(250);
        //                    }
        //                } catch ( Throwable x) {
        //                }
        //            }
        //        };
        //        rogue.setDaemon(true);
        //        rogue.start();


        HttpClient client = newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(uri).version(version).build();
        HttpResponse<String> r;
        CompletableFuture<HttpResponse<String>> cf1;

        try {
            for (int i=0; i<responses.length; i++) {
                out.println("----- iteration " + i + " -----");
                String body = responses[i];
                Thread t = sendSplitResponse(response(body, serverKeepalive), server);

                if (async) {
                    out.println("send async: " + request);
                    cf1 = client.sendAsync(request, ofString());
                    r = cf1.get();
                } else { // sync
                    out.println("send sync: " + request);
                    r = client.send(request, ofString());
                }

                out.println("response " + r);
                String rxbody = r.body();
                out.println("response body:[" + rxbody + "]");

                if (r.statusCode() != 200)
                    throw new RuntimeException("Expected 200, got:" + r.statusCode());

                if (!rxbody.equals(body))
                    throw new RuntimeException(format("Expected:%s, got:%s", body, rxbody));

                t.join();
                conn.close();
            }
        } finally {
            server.close();
        }
        System.out.println("OK");
    }

    // required for cleanup
    volatile MockServer.Connection conn;

    // Sends the response, mostly, one byte at a time with a small delay
    // between bytes, to encourage that each byte is read in a separate read
    Thread sendSplitResponse(String s, MockServer server) {
        System.out.println("Server: creating new thread to send ... ");
        Thread t = new Thread(() -> {
            System.out.println("Server: waiting for server to receive headers");
            conn = server.activity();
            System.out.println("Server: Start sending response");

            try {
                int len = s.length();
                out.println("Server: going to send [" + s + "]");
                for (int i = 0; i < len; i++) {
                    String onechar = s.substring(i, i + 1);
                    try {
                        conn.send(onechar);
                    } catch(SocketException | SSLException x) {
                        if (!useSSL || i != len - 1) throw x;
                        if (x.getMessage().contains("closed by remote host")) {
                            String osname = System.getProperty("os.name", "unknown");
                            // On Solaris we can receive an exception when
                            // the client closes the connection after receiving
                            // the last expected char.
                            if (osname.contains("SunO")) {
                                System.out.println(osname + " detected");
                                System.out.println("WARNING: ignoring " + x);
                                System.err.println(osname + " detected");
                                System.err.println("WARNING: ignoring " + x);
                            }
                        }
                    }
                    Thread.sleep(10);
                }
                out.println("Server: sent [" + s + "]");
            } catch (IOException | InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t.setDaemon(true);
        t.start();
        return t;
    }
}