/
HelloWorldJaxRsResource.java
323 lines (305 loc) · 13.6 KB
/
HelloWorldJaxRsResource.java
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/*
* Copyright © 2018, 2021 Apple Inc. and the ServiceTalk project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicetalk.examples.http.jaxrs;
import io.servicetalk.buffer.api.Buffer;
import io.servicetalk.buffer.api.BufferAllocator;
import io.servicetalk.buffer.api.CompositeBuffer;
import io.servicetalk.concurrent.api.Publisher;
import io.servicetalk.concurrent.api.Single;
import io.servicetalk.examples.http.jaxrs.client.ProtobufClient;
import io.servicetalk.tests.helloworld.HelloReply;
import io.servicetalk.tests.helloworld.HelloRequest;
import io.servicetalk.transport.api.ConnectionContext;
import org.glassfish.jersey.media.multipart.FormDataParam;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.Response;
import static io.servicetalk.concurrent.api.Publisher.from;
import static io.servicetalk.concurrent.api.Publisher.fromInputStream;
import static io.servicetalk.data.protobuf.jersey.ProtobufMediaTypes.APPLICATION_X_PROTOBUF;
import static io.servicetalk.data.protobuf.jersey.ProtobufMediaTypes.APPLICATION_X_PROTOBUF_VAR_INT;
import static java.lang.Math.random;
import static java.util.Collections.singletonMap;
import static java.util.concurrent.TimeUnit.SECONDS;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.MediaType.MULTIPART_FORM_DATA;
import static javax.ws.rs.core.MediaType.TEXT_PLAIN;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;
import static javax.ws.rs.core.Response.accepted;
import static javax.ws.rs.core.Response.ok;
import static javax.ws.rs.core.Response.status;
/**
* JAX-RS resource class that demonstrates some of the features supported by ServiceTalk's Jersey HTTP router.
*/
@Path("greetings")
public class HelloWorldJaxRsResource {
/**
* Resource that relies on the Publisher/OIO adapters to produce text responses.
* <p>
* Test with:
* <pre>
* curl http://localhost:8080/greetings/hello
* curl http://localhost:8080/greetings/hello?who=turnip
* </pre>
*
* @param who the recipient of the greetings.
* @return greetings as a {@link String}.
*/
@GET
@Path("hello")
@Produces(TEXT_PLAIN)
public String hello(@DefaultValue("world") @QueryParam("who") final String who) {
return "hello " + who;
}
/**
* Resource that relies on the Publisher/OIO adapters and Jackson to consume and produce JSON entities.
* This project uses ServiceTalk's Jackson provider for Jersey hence no OIO adaptation is involved.
* <p>
* Test with:
* <pre>
* curl -H 'content-type: application/json' -d '{}' http://localhost:8080/greetings/hello
* curl -H 'content-type: application/json' -d '{"who":"turnip"}' http://localhost:8080/greetings/hello
* </pre>
*
* @param salutation a {@link Map} that provides salutation data.
* @return greetings as a {@link Map}.
*/
@POST
@Path("hello")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Map<String, String> hello(final Map<String, String> salutation) {
return singletonMap("hello", salutation.getOrDefault("who", "world"));
}
/**
* Resource that relies on the Publisher/OIO adapters and Protobuf to consume and produce Protobuf entities.
* This project uses ServiceTalk's Protobuf provider for Jersey hence no OIO adaptation is involved.
* <p>
* Test with: {@link ProtobufClient}.
*
* @param request a {@link HelloRequest}.
* @return reply as a {@link HelloReply}.
*/
@POST
@Path("hello")
@Consumes(APPLICATION_X_PROTOBUF)
@Produces(APPLICATION_X_PROTOBUF)
public HelloReply hello(final HelloRequest request) {
return HelloReply.newBuilder().setMessage("hello " + request.getName()).build();
}
/**
* Resource that uses Java's CompletionStage to produce an async response.
* Note that the {@link ConnectionContext} could also be injected into a class-level {@code @Context} field.
* <p>
* Test with:
* <pre>
* curl http://localhost:8080/greetings/slow-hello
* curl http://localhost:8080/greetings/slow-hello?who=doctor
* </pre>
*
* @param who the recipient of the greetings.
* @param ctx the {@link ConnectionContext}.
* @return future greetings as a {@link CompletionStage} of {@link String}.
*/
@GET
@Path("slow-hello")
@Produces(TEXT_PLAIN)
public CompletionStage<String> slowHello(@DefaultValue("world") @QueryParam("who") final String who,
@Context final ConnectionContext ctx) {
final CompletableFuture<String> delayedResponse = new CompletableFuture<>();
ctx.executionContext().executor().timer(1, SECONDS)
.afterOnComplete(() -> delayedResponse.complete("well, hello " + who))
.subscribe();
return delayedResponse;
}
/**
* Resource that only relies on {@link Single}s for consuming and producing data, and operators for processing it.
* No OIO adaptation is involved when requests are dispatched to it,
* allowing it to fully benefit from ReactiveStream's features like flow control.
* Behind the scene, ServiceTalk's aggregation mechanism is used to provide the resource with a
* {@link Single Single<Buffer>} that contains the whole request entity as a {@link Buffer}.
* Note that the {@link ConnectionContext} could also be injected into a class-level {@code @Context} field.
* <p>
* Test with:
* <pre>
* curl -H 'content-type: text/plain' -d 'dolly' http://localhost:8080/greetings/hello
* </pre>
*
* @param who the recipient of the greetings.
* @param ctx the {@link ConnectionContext}.
* @return greetings as a {@link Single} {@link Buffer}.
*/
@POST
@Path("hello")
@Consumes(TEXT_PLAIN)
@Produces(TEXT_PLAIN)
public Single<Buffer> hello(final Single<Buffer> who,
@Context final ConnectionContext ctx) {
final BufferAllocator allocator = ctx.executionContext().bufferAllocator();
return who.map(b -> allocator.newCompositeBuffer()
.addBuffer(allocator.fromAscii("hello, "))
.addBuffer(b)
.addBuffer(allocator.fromAscii("!")));
}
/**
* Resource that relies on multi-part file upload on the consume side, and {@link Publisher} with
* operators for processing it on the produce side.
* <p>
* Test with:
* <pre>{@code
* echo "An empty file" > sample.txt && curl -vF "file=@sample.txt" \
* http://localhost:8080/greetings/multipart-hello
* }</pre>
*
* @param ctx the {@link ConnectionContext}.
* @param file the multi-part file contents.
* @return greetings as a {@link Single} {@link Buffer}.
*/
@POST
@Path("multipart-hello")
@Consumes(MULTIPART_FORM_DATA)
@Produces(TEXT_PLAIN)
public Single<Buffer> multipartHello(@Context final ConnectionContext ctx,
@FormDataParam("file") InputStream file) {
final BufferAllocator allocator = ctx.executionContext().bufferAllocator();
return from(allocator.fromAscii("Hello multipart! Content: "))
.concat(fromInputStream(file).map(allocator::wrap))
.collect(allocator::newCompositeBuffer,
(collector, item) -> ((CompositeBuffer) collector).addBuffer(item));
}
/**
* Resource that only relies on {@link Single}/{@link Publisher} for consuming and producing data,
* and returns a JAX-RS {@link Response} in order to set its status.
* No OIO adaptation is involved when requests are dispatched to it,
* allowing it to fully benefit from ReactiveStream's features like flow control.
* Behind the scene, ServiceTalk's aggregation mechanism is used to provide the resource with a
* {@link Single Single<Buffer>} that contains the whole request entity as a {@link Buffer}.
* Note that the {@link ConnectionContext} could also be injected into a class-level {@code @Context} field.
* <p>
* Test with:
* <pre>
* curl -i -H 'content-type: text/plain' -d 'kitty' http://localhost:8080/greetings/random-hello
* </pre>
*
* @param who the recipient of the greetings.
* @param ctx the {@link ConnectionContext}.
* @return greetings as a JAX-RS {@link Response}.
*/
@POST
@Path("random-hello")
@Consumes(TEXT_PLAIN)
@Produces(TEXT_PLAIN)
public Response randomHello(final Single<Buffer> who,
@Context final ConnectionContext ctx) {
if (random() < .5) {
return accepted("greetings accepted, call again for a response").build();
}
final BufferAllocator allocator = ctx.executionContext().bufferAllocator();
final Publisher<Buffer> payload = from(allocator.fromAscii("hello ")).concat(who);
// Wrap content Publisher to capture its generic type (i.e. Buffer) so it is handled correctly
final GenericEntity<Publisher<Buffer>> entity = new GenericEntity<Publisher<Buffer>>(payload) { };
return ok(entity).build();
}
/**
* Resource that relies on the {@link Single}/OIO adapters and Jackson to consume and produce JSON entities.
* This project uses ServiceTalk's Jackson provider for Jersey hence no OIO adaptation is involved.
* <p>
* Test with:
* <pre>
* curl -H 'content-type: application/json' -d '{}' http://localhost:8080/greetings/single-hello-status
* curl -H 'content-type: application/json' -d '{"who":"bob"}' http://localhost:8080/greetings/single-hello-status
* </pre>
*
* @param single a {@link Single} that provides a {@link Map} that provides salutation data.
* @return greetings as a {@link Map}.
*/
@POST
@Path("single-hello-status")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Single<Response> helloStatus(final Single<Map<String, String>> single) {
return single.map(request -> {
final String name = request.get("who");
return name == null ?
status(NOT_FOUND).entity(singletonMap("error", "key 'who' not found")).build() :
ok(singletonMap("hello", name)).build();
});
}
/**
* Resource that only relies on {@link Single}s for consuming and producing data, and operators for processing it.
* No OIO adaptation is involved when requests are dispatched to it, as it relies on ServiceTalk/Jackson
* non-blocking (de)serialization.
* <p>
* Test with:
* <pre>
* curl -H 'content-type: application/json' -d '{}' http://localhost:8080/greetings/single-hello
* curl -H 'content-type: application/json' -d '{"who":"turnip"}' http://localhost:8080/greetings/single-hello
* </pre>
*
* @param salutation a {@link Single Single<Map>} that provides salutation data.
* @return greetings as a {@link Single Single<Map>}.
*/
@POST
@Path("single-hello")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Single<Map<String, String>> singleHello(final Single<Map<String, String>> salutation) {
return salutation.map(m -> singletonMap("single hello", m.getOrDefault("who", "world")));
}
/**
* Resource that relies on the {@link Single}/OIO adapters and Protobuf to consume and produce Protobuf entities.
* This project uses ServiceTalk's Protobuf provider for Jersey hence no OIO adaptation is involved.
* <p>
* Test with: Test with: {@link ProtobufClient}.
*
* @param single a {@link Single} of {@link HelloRequest}.
* @return reply as a {@link Single} of {@link HelloReply}.
*/
@POST
@Path("single-hello")
@Consumes(APPLICATION_X_PROTOBUF)
@Produces(APPLICATION_X_PROTOBUF)
public Single<HelloReply> hello(final Single<HelloRequest> single) {
return single.map(request -> HelloReply.newBuilder().setMessage("hello " + request.getName()).build());
}
/**
* Resource that relies on the {@link Publisher}/OIO adapters and Protobuf to consume and produce Protobuf entities.
* This project uses ServiceTalk's Protobuf provider for Jersey hence no OIO adaptation is involved.
* <p>
* Test with: Test with: {@link ProtobufClient}.
*
* @param publisher a {@link Publisher} of {@link HelloRequest}.
* @return reply as a {@link Publisher} of {@link HelloReply}.
*/
@POST
@Path("publisher-hello")
@Consumes(APPLICATION_X_PROTOBUF_VAR_INT)
@Produces(APPLICATION_X_PROTOBUF_VAR_INT)
public Publisher<HelloReply> hello(final Publisher<HelloRequest> publisher) {
return publisher.map(request -> HelloReply.newBuilder().setMessage("hello " + request.getName()).build());
}
}