-
Notifications
You must be signed in to change notification settings - Fork 13
/
PetStoreResource.java
522 lines (488 loc) · 14.9 KB
/
PetStoreResource.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
// ***************************************************************************************************************************
// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
// * to you 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 org.apache.juneau.petstore.rest;
import static org.apache.juneau.dto.swagger.ui.SwaggerUI.*;
import static org.apache.juneau.http.HttpMethodName.*;
import static org.apache.juneau.http.response.Ok.*;
import java.util.*;
import java.util.Map;
import javax.inject.*;
import org.apache.juneau.jsonschema.annotation.*;
import org.apache.juneau.petstore.*;
import org.apache.juneau.petstore.dto.*;
import org.apache.juneau.petstore.service.*;
import org.apache.juneau.*;
import org.apache.juneau.annotation.*;
import org.apache.juneau.html.annotation.*;
import org.apache.juneau.http.annotation.*;
import org.apache.juneau.rest.*;
import org.apache.juneau.rest.annotation.*;
import org.apache.juneau.http.exception.*;
import org.apache.juneau.rest.helper.*;
import org.apache.juneau.http.response.*;
import org.apache.juneau.rest.widget.*;
import org.apache.juneau.transforms.*;
import org.apache.juneau.rest.converters.*;
/**
* Sample Petstore application.
*
* <ul class='seealso'>
* <li class='extlink'>{@source}
* </ul>
*/
@Rest(
path="/petstore",
title="Petstore application",
description={
"This is a sample server Petstore server based on the Petstore sample at Swagger.io.",
"You can find out more about Swagger at http://swagger.io.",
},
properties= {
// Resolve recursive references when showing schema info in the swagger.
@Property(name=SWAGGERUI_resolveRefsMaxDepth, value="99")
},
swagger=@ResourceSwagger(
version="1.0.0",
title="Swagger Petstore",
termsOfService="You are on your own.",
contact=@Contact(
name="Juneau Development Team",
email="dev@juneau.apache.org",
url="http://juneau.apache.org"
),
license=@License(
name="Apache 2.0",
url="http://www.apache.org/licenses/LICENSE-2.0.html"
),
externalDocs=@ExternalDocs(
description="Find out more about Juneau",
url="http://juneau.apache.org"
),
tags={
@Tag(
name="pet",
description="Everything about your Pets",
externalDocs=@ExternalDocs(
description="Find out more",
url="http://juneau.apache.org"
)
),
@Tag(
name="store",
description="Access to Petstore orders"
),
@Tag(
name="user",
description="Operations about user",
externalDocs=@ExternalDocs(
description="Find out more about our store",
url="http://juneau.apache.org"
)
)
}
),
debug="true",
staticFiles={"htdocs:/htdocs"} // Expose static files in htdocs subpackage.
)
@HtmlDocConfig(
widgets={
ContentTypeMenuItem.class,
ThemeMenuItem.class,
},
navlinks={
"up: request:/..",
"options: servlet:/?method=OPTIONS",
"$W{ContentTypeMenuItem}",
"$W{ThemeMenuItem}",
"source: $C{Source/gitHub}/org/apache/juneau/petstore/rest/$R{servletClassSimple}.java"
},
head={
"<link rel='icon' href='$U{servlet:/htdocs/cat.png}'/>" // Add a cat icon to the page.
},
header={
"<h1>$R{resourceTitle}</h1>",
"<h2>$R{methodSummary}</h2>",
"$C{PetStore/headerImage}"
},
aside={
"<div style='max-width:400px' class='text'>",
" <p>This page shows a standard nested REST resource.</p>",
" <p>It shows how different properties can be rendered on the same bean in different views.</p>",
" <p>It also shows examples of HtmlRender classes and @BeanProperty(format) annotations.</p>",
" <p>It also shows how the Queryable converter and query widget can be used to create searchable interfaces.</p>",
"</div>"
},
stylesheet="servlet:/htdocs/themes/dark.css" // Use dark theme by default.
)
public class PetStoreResource extends BasicRest implements PetStore {
@Inject
private PetStoreService store;
/**
* Navigation page
*
* @return Navigation page contents.
*/
@RestMethod(
name=GET,
path="/",
summary="Navigation page"
)
@HtmlDocConfig(
style={
"INHERIT", // Flag for inheriting resource-level CSS.
"body { ",
"background-image: url('petstore/htdocs/background.jpg'); ",
"background-color: black; ",
"background-size: cover; ",
"background-attachment: fixed; ",
"}"
}
)
public ResourceDescriptions getTopPage() {
return new ResourceDescriptions()
.append("pet", "All pets in the store")
.append("store", "Orders and inventory")
.append("user", "Petstore users")
;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Pets
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@Override /* PetStore */
@RestMethod(
name=GET,
path="/pet",
summary="All pets in the store",
swagger=@MethodSwagger(
tags="pet",
parameters={
Queryable.SWAGGER_PARAMS // Documents searching.
}
),
converters={Queryable.class} // Searching support.
)
@BeanConfig(
bpx="Pet: tags,photo" // In this view, don't serialize tags/photos properties.
)
public Collection<Pet> getPets() throws NotAcceptable {
return store.getPets();
}
@Override /* PetStore */
@RestMethod(
name=GET,
path="/pet/{petId}",
summary="Find pet by ID",
description="Returns a single pet",
swagger=@MethodSwagger(
tags="pet"
)
)
public Pet getPet(long petId) throws IdNotFound, NotAcceptable {
return store.getPet(petId);
}
@Override /* PetStore */
@RestMethod(
name=POST,
path="/pet",
summary="Add a new pet to the store",
swagger=@MethodSwagger(
tags="pet"
)
//roleGuard="ROLE_ADMIN || (ROLE_USER && ROLE_WRITABLE)" // Restrict access to this method.
)
public long createPet(CreatePet pet) throws IdConflict, NotAcceptable, UnsupportedMediaType {
return store.create(pet).getId();
}
@Override /* PetStore */
@RestMethod(
name=PUT,
path="/pet/{petId}",
summary="Update an existing pet",
swagger=@MethodSwagger(
tags="pet"
)
)
public Ok updatePet(UpdatePet pet) throws IdNotFound, NotAcceptable, UnsupportedMediaType {
store.update(pet);
return OK;
}
@Override /* PetStore */
@RestMethod(
name=GET,
path="/pet/findByStatus",
summary="Finds Pets by status",
description="Multiple status values can be provided with comma separated strings.",
swagger=@MethodSwagger(
tags="pet"
)
)
public Collection<Pet> findPetsByStatus(PetStatus[] status) throws NotAcceptable {
return store.getPetsByStatus(status);
}
@Override /* PetStore */
@RestMethod(
name=GET,
path="/pet/findByTags",
summary="Finds Pets by tags",
description="Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.",
swagger=@MethodSwagger(
tags="pet"
)
)
@Deprecated
public Collection<Pet> findPetsByTags(String[] tags) throws InvalidTag, NotAcceptable {
return store.getPetsByTags(tags);
}
@Override /* PetStore */
@RestMethod(
name=DELETE,
path="/pet/{petId}",
summary="Deletes a pet",
swagger=@MethodSwagger(
tags="pet"
)
)
public Ok deletePet(String apiKey, long petId) throws IdNotFound, NotAcceptable {
store.removePet(petId);
return OK;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Orders
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/**
* Store navigation page.
*
* @return Store navigation page contents.
*/
@RestMethod(
summary="Store navigation page",
swagger=@MethodSwagger(
tags="store"
)
)
public ResourceDescriptions getStore() {
return new ResourceDescriptions()
.append("store/order", "Petstore orders")
.append("store/inventory", "Petstore inventory")
;
}
@Override
@RestMethod(
name=GET,
path="/store/order",
summary="Petstore orders",
swagger=@MethodSwagger(
tags="store"
)
)
@HtmlDocConfig(
widgets={
QueryMenuItem.class
},
navlinks={
"INHERIT", // Inherit links from class.
"[2]:$W{QueryMenuItem}", // Insert QUERY link in position 2.
"[3]:$W{AddOrderMenuItem}" // Insert ADD link in position 3.
}
)
public Collection<Order> getOrders() throws NotAcceptable {
return store.getOrders();
}
@Override
@RestMethod(
name=GET,
path="/store/order/{orderId}",
summary="Find purchase order by ID",
description="Returns a purchase order by ID.",
swagger=@MethodSwagger(
tags="store"
)
)
public Order getOrder(long orderId) throws InvalidId, IdNotFound, NotAcceptable {
if (orderId < 1 || orderId > 1000)
throw new InvalidId();
return store.getOrder(orderId);
}
@Override
@RestMethod(
name=POST,
path="/store/order",
summary="Place an order for a pet",
swagger=@MethodSwagger(
tags="store"
),
pojoSwaps={
TemporalDateSwap.IsoLocalDate.class
}
)
public long placeOrder(long petId, String username) throws IdConflict, NotAcceptable, UnsupportedMediaType {
CreateOrder co = new CreateOrder(petId, username);
return store.create(co).getId();
}
@Override
@RestMethod(
name=DELETE,
path="/store/order/{orderId}",
summary="Delete purchase order by ID",
description= {
"For valid response try integer IDs with positive integer value.",
"Negative or non-integer values will generate API errors."
},
swagger=@MethodSwagger(
tags="store"
)
)
public Ok deleteOrder(long orderId) throws InvalidId, IdNotFound, NotAcceptable {
if (orderId < 0)
throw new InvalidId();
store.removeOrder(orderId);
return OK;
}
@Override
@RestMethod(
name=GET,
path="/store/inventory",
summary="Returns pet inventories by status",
description="Returns a map of status codes to quantities",
swagger=@MethodSwagger(
tags="store",
responses={
"200:{ 'x-example':{AVAILABLE:123} }",
}
)
)
public Map<PetStatus,Integer> getStoreInventory() throws NotAcceptable {
return store.getInventory();
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Users
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@Override
@RestMethod(
name=GET,
path="/user",
summary="Petstore users",
bpx="User: email,password,phone",
swagger=@MethodSwagger(
tags="user"
)
)
public Collection<User> getUsers() throws NotAcceptable {
return store.getUsers();
}
@Override
@RestMethod(
name=GET,
path="/user/{username}",
summary="Get user by user name",
swagger=@MethodSwagger(
tags="user"
)
)
public User getUser(String username) throws InvalidUsername, IdNotFound, NotAcceptable {
return store.getUser(username);
}
@Override
@RestMethod(
name=POST,
path="/user",
summary="Create user",
description="This can only be done by the logged in user.",
swagger=@MethodSwagger(
tags="user"
)
)
public Ok createUser(User user) throws InvalidUsername, IdConflict, NotAcceptable, UnsupportedMediaType {
store.create(user);
return OK;
}
@Override
@RestMethod(
name=POST,
path="/user/createWithArray",
summary="Creates list of users with given input array",
swagger=@MethodSwagger(
tags="user"
)
)
public Ok createUsers(User[] users) throws InvalidUsername, IdConflict, NotAcceptable, UnsupportedMediaType {
for (User user : users)
store.create(user);
return OK;
}
@Override
@RestMethod(
name=PUT,
path="/user/{username}",
summary="Update user",
description="This can only be done by the logged in user.",
swagger=@MethodSwagger(
tags="user"
)
)
public Ok updateUser(String username, User user) throws InvalidUsername, IdNotFound, NotAcceptable, UnsupportedMediaType {
store.update(user);
return OK;
}
@Override
@RestMethod(
name=DELETE,
path="/user/{username}",
summary="Delete user",
description="This can only be done by the logged in user.",
swagger=@MethodSwagger(
tags="user"
)
)
public Ok deleteUser(String username) throws InvalidUsername, IdNotFound, NotAcceptable {
store.removeUser(username);
return OK;
}
@Override
@RestMethod(
name=GET,
path="/user/login",
summary="Logs user into the system",
swagger=@MethodSwagger(
tags="user"
)
)
public Ok login(
String username,
String password,
Value<Integer> rateLimit,
Value<ExpiresAfter> expiresAfter
) throws InvalidLogin, NotAcceptable {
RestRequest req = getRequest();
if (! store.isValid(username, password))
throw new InvalidLogin();
Date d = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
req.getSession().setAttribute("login-expires", d);
rateLimit.set(1000);
expiresAfter.set(new ExpiresAfter(d));
return OK;
}
@Override
@RestMethod(
name=GET,
path="/user/logout",
summary="Logs out current logged in user session",
swagger=@MethodSwagger(
tags="user"
)
)
public Ok logout() throws NotAcceptable {
getRequest().getSession().removeAttribute("login-expires");
return OK;
}
}