|
| 1 | +package com.baeldung.sparkjava; |
| 2 | + |
| 3 | +import static spark.Spark.delete; |
| 4 | +import static spark.Spark.get; |
| 5 | +import static spark.Spark.options; |
| 6 | +import static spark.Spark.post; |
| 7 | +import static spark.Spark.put; |
| 8 | + |
| 9 | +import com.google.gson.Gson; |
| 10 | + |
| 11 | +public class SparkRestExample { |
| 12 | + public static void main(String[] args) { |
| 13 | + final UserService userService = new UserServiceMapImpl(); |
| 14 | + |
| 15 | + post("/users", (request, response) -> { |
| 16 | + response.type("application/json"); |
| 17 | + |
| 18 | + User user = new Gson().fromJson(request.body(), User.class); |
| 19 | + userService.addUser(user); |
| 20 | + |
| 21 | + return new Gson().toJson(new StandardResponse(StatusResponse.SUCCESS)); |
| 22 | + }); |
| 23 | + |
| 24 | + get("/users", (request, response) -> { |
| 25 | + response.type("application/json"); |
| 26 | + |
| 27 | + return new Gson().toJson( |
| 28 | + new StandardResponse(StatusResponse.SUCCESS,new Gson() |
| 29 | + .toJsonTree(userService.getUsers()))); |
| 30 | + }); |
| 31 | + |
| 32 | + get("/users/:id", (request, response) -> { |
| 33 | + response.type("application/json"); |
| 34 | + |
| 35 | + return new Gson().toJson( |
| 36 | + new StandardResponse(StatusResponse.SUCCESS,new Gson() |
| 37 | + .toJsonTree(userService.getUser(request.params(":id"))))); |
| 38 | + }); |
| 39 | + |
| 40 | + put("/users/:id", (request, response) -> { |
| 41 | + response.type("application/json"); |
| 42 | + |
| 43 | + User toEdit = new Gson().fromJson(request.body(), User.class); |
| 44 | + User editedUser = userService.editUser(toEdit); |
| 45 | + |
| 46 | + if (editedUser != null) { |
| 47 | + return new Gson().toJson( |
| 48 | + new StandardResponse(StatusResponse.SUCCESS,new Gson() |
| 49 | + .toJsonTree(editedUser))); |
| 50 | + }else { |
| 51 | + return new Gson().toJson( |
| 52 | + new StandardResponse(StatusResponse.ERROR,new Gson() |
| 53 | + .toJson("User not found or error in edit"))); |
| 54 | + } |
| 55 | + }); |
| 56 | + |
| 57 | + delete("/users/:id", (request, response) -> { |
| 58 | + response.type("application/json"); |
| 59 | + |
| 60 | + userService.deleteUser(request.params(":id")); |
| 61 | + return new Gson().toJson( |
| 62 | + new StandardResponse(StatusResponse.SUCCESS, "user deleted")); |
| 63 | + }); |
| 64 | + |
| 65 | + options("/users/:id", (request, response) -> { |
| 66 | + response.type("application/json"); |
| 67 | + |
| 68 | + return new Gson().toJson( |
| 69 | + new StandardResponse(StatusResponse.SUCCESS, |
| 70 | + (userService.userExist( |
| 71 | + request.params(":id"))) ? "User exists" : "User does not exists" )); |
| 72 | + }); |
| 73 | + |
| 74 | + } |
| 75 | + |
| 76 | +} |
0 commit comments