File: JavadocExamples.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 (293 lines) | stat: -rw-r--r-- 11,699 bytes parent folder | download | duplicates (6)
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
/*
 * Copyright (c) 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.io.InputStream;
import java.io.PrintStream;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Redirect;
import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodyHandlers;
import java.net.http.HttpResponse.BodySubscribers;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Flow;
import java.util.regex.Pattern;
import static java.nio.charset.StandardCharsets.UTF_8;

/*
 * THE CONTENTS OF THIS FILE HAVE TO BE IN SYNC WITH THE EXAMPLES USED IN THE
 * JAVADOC.
 *
 * @test
 * @compile JavadocExamples.java
 */
public class JavadocExamples {
    HttpRequest request = null;
    HttpClient client = null;
    Pattern p = null;

    void fromHttpClientClasslevelDescription() throws Exception {
        //Synchronous Example
        HttpClient client = HttpClient.newBuilder()
                .version(Version.HTTP_1_1)
                .followRedirects(Redirect.NORMAL)
                .connectTimeout(Duration.ofSeconds(20))
                .proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 80)))
                .authenticator(Authenticator.getDefault())
                .build();
        HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
        System.out.println(response.statusCode());
        System.out.println(response.body());

        //Asynchronous Example
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://foo.com/"))
                .timeout(Duration.ofMinutes(2))
                .header("Content-Type", "application/json")
                .POST(BodyPublishers.ofFile(Paths.get("file.json")))
                .build();
        client.sendAsync(request, BodyHandlers.ofString())
                .thenApply(HttpResponse::body)
                .thenAccept(System.out::println);
    }

    void fromHttpRequest() throws Exception {
        // HttpRequest class-level description
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://foo.com/"))
                .build();
        client.sendAsync(request, BodyHandlers.ofString())
                .thenApply(HttpResponse::body)
                .thenAccept(System.out::println)
                .join();

        // HttpRequest.BodyPublishers class-level description
        // Request body from a String
        HttpRequest request1 = HttpRequest.newBuilder()
                .uri(URI.create("https://foo.com/"))
                .header("Content-Type", "text/plain; charset=UTF-8")
                .POST(BodyPublishers.ofString("some body text"))
                .build();

        // Request body from a File
        HttpRequest request2 = HttpRequest.newBuilder()
                .uri(URI.create("https://foo.com/"))
                .header("Content-Type", "application/json")
                .POST(BodyPublishers.ofFile(Paths.get("file.json")))
                .build();

        // Request body from a byte array
        HttpRequest request3 = HttpRequest.newBuilder()
                .uri(URI.create("https://foo.com/"))
                .POST(BodyPublishers.ofByteArray(new byte[] { /*...*/ }))
                .build();
    }

    void fromHttpResponse() throws Exception {
        // HttpResponse class-level description
        HttpResponse<String> response = client
                .send(request, BodyHandlers.ofString());

        // HttpResponse.BodyHandler class-level description
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://www.foo.com/"))
                .build();
        client.sendAsync(request, BodyHandlers.ofFile(Paths.get("/tmp/f")))
                .thenApply(HttpResponse::body)
                .thenAccept(System.out::println);

        HttpRequest request1 = HttpRequest.newBuilder()
                .uri(URI.create("http://www.foo.com/"))
                .build();
        BodyHandler<Path> bodyHandler = (info) -> info.statusCode() == 200
                ? BodySubscribers.ofFile(Paths.get("/tmp/f"))
                : BodySubscribers.replacing(Paths.get("/NULL"));
        client.sendAsync(request, bodyHandler)
                .thenApply(HttpResponse::body)
                .thenAccept(System.out::println);


        // HttpResponse.BodyHandlers class-level description
        // Receives the response body as a String
        HttpResponse<String> response1 = client
                .send(request, BodyHandlers.ofString());

        // Receives the response body as a file
        HttpResponse<Path> response2 = client
                .send(request, BodyHandlers.ofFile(Paths.get("example.html")));

        // Receives the response body as an InputStream
        HttpResponse<InputStream> respons3 = client
                .send(request, BodyHandlers.ofInputStream());

        // Discards the response body
        HttpResponse<Void> respons4 = client
                .send(request, BodyHandlers.discarding());


        // HttpResponse.BodySubscribers class-level description
        // Streams the response body to a File
        HttpResponse<byte[]> response5 = client
                .send(request, responseInfo -> BodySubscribers.ofByteArray());

        // Accumulates the response body and returns it as a byte[]
        HttpResponse<byte[]> response6 = client
                .send(request, responseInfo -> BodySubscribers.ofByteArray());

        // Discards the response body
        HttpResponse<Void> response7 = client
                .send(request, responseInfo -> BodySubscribers.discarding());

        // Accumulates the response body as a String then maps it to its bytes
        HttpResponse<byte[]> response8 = client
                .send(request, responseInfo ->
                        BodySubscribers.mapping(BodySubscribers.ofString(UTF_8), String::getBytes));

    }

    /**
     * @apiNote This method can be used as an adapter between a {@code
     * BodySubscriber} and a text based {@code Flow.Subscriber} that parses
     * text line by line.
     *
     * <p> For example:
     * <pre> {@code  // A PrintSubscriber that implements Flow.Subscriber<String>
     *  // and print lines received by onNext() on System.out
     *  PrintSubscriber subscriber = new PrintSubscriber(System.out);
     *  client.sendAsync(request, BodyHandlers.fromLineSubscriber(subscriber))
     *      .thenApply(HttpResponse::statusCode)
     *      .thenAccept((status) -> {
     *          if (status != 200) {
     *              System.err.printf("ERROR: %d status received%n", status);
     *          }
     *      }); }</pre>
     */
    void fromLineSubscriber1() {
         // A PrintSubscriber that implements Flow.Subscriber<String>
         // and print lines received by onNext() on System.out
         PrintSubscriber subscriber = new PrintSubscriber(System.out);
         client.sendAsync(request, BodyHandlers.fromLineSubscriber(subscriber))
                 .thenApply(HttpResponse::statusCode)
                 .thenAccept((status) -> {
                     if (status != 200) {
                         System.err.printf("ERROR: %d status received%n", status);
                     }
                 });
    }

    /**
     * @apiNote This method can be used as an adapter between a {@code
     * BodySubscriber} and a text based {@code Flow.Subscriber} that parses
     * text line by line.
     *
     * <p> For example:
     * <pre> {@code  // A LineParserSubscriber that implements Flow.Subscriber<String>
     *  // and accumulates lines that match a particular pattern
     *  Pattern pattern = ...;
     *  LineParserSubscriber subscriber = new LineParserSubscriber(pattern);
     *  HttpResponse<List<String>> response = client.send(request,
     *      BodyHandlers.fromLineSubscriber(subscriber, s -> s.getMatchingLines(), "\n"));
     *  if (response.statusCode() != 200) {
     *      System.err.printf("ERROR: %d status received%n", response.statusCode());
     *  } }</pre>
     *
     */
    void fromLineSubscriber2() throws IOException, InterruptedException {
        // A LineParserSubscriber that implements Flow.Subscriber<String>
        // and accumulates lines that match a particular pattern
        Pattern pattern = p;
        LineParserSubscriber subscriber = new LineParserSubscriber(pattern);
        HttpResponse<List<String>> response = client.send(request,
                BodyHandlers.fromLineSubscriber(subscriber, s -> s.getMatchingLines(), "\n"));
        if (response.statusCode() != 200) {
            System.err.printf("ERROR: %d status received%n", response.statusCode());
        }
    }

    static final class PrintSubscriber implements Flow.Subscriber<String> {
        final PrintStream out;
        PrintSubscriber(PrintStream out) {
            this.out = out;
        }
        @Override
        public void onSubscribe(Flow.Subscription subscription) {
            subscription.request(Long.MAX_VALUE);
        }
        @Override
        public void onNext(String item) {
            out.println(item);
        }

        @Override
        public void onError(Throwable throwable) {
            throwable.printStackTrace();
        }
        @Override
        public void onComplete() {
        }
    }

    static final class LineParserSubscriber implements Flow.Subscriber<String> {
        final Pattern pattern;
        final CopyOnWriteArrayList<String> matches = new CopyOnWriteArrayList<>();
        LineParserSubscriber(Pattern pattern) {
            this.pattern = pattern;
        }
        @Override
        public void onSubscribe(Flow.Subscription subscription) {
            subscription.request(Long.MAX_VALUE);
        }
        @Override
        public void onNext(String item) {
            if (pattern.matcher(item).matches()) {
                matches.add(item);
            }
        }
        @Override
        public void onError(Throwable throwable) {
            throwable.printStackTrace();
        }
        @Override
        public void onComplete() {
        }

        public List<String> getMatchingLines() {
            return Collections.unmodifiableList(matches);
        }
    }

}