[BAEL-1659] Create REST microservices with javalin (#4145)

* [BAEL-1615] Code to support article.

* Adding example of provides...with

* Adding uses to main module

* [BAEL-1659] Creat REST microservices with javalin

* [BAEL-1659] Update article code based on feedback

* Revert parent pom change

* Using Optional instead of null
This commit is contained in:
christopherfranklin 2018-05-12 00:23:24 -04:00 committed by Grzegorz Piwowarek
parent 196223da51
commit ca5a7d2e40
5 changed files with 90 additions and 0 deletions

View File

@ -680,6 +680,12 @@
<version>${unirest.version}</version>
</dependency>
<!-- javalin -->
<dependency>
<groupId>io.javalin</groupId>
<artifactId>javalin</artifactId>
<version>1.6.0</version>
</dependency>
<!-- Atlassian Fugue -->
<dependency>
<groupId>io.atlassian.fugue</groupId>

View File

@ -0,0 +1,16 @@
package com.baeldung.javalin;
import com.baeldung.javalin.User.UserController;
import io.javalin.Javalin;
public class JavalinApp {
public static void main(String[] args) {
Javalin app = Javalin.create()
.port(7000)
.start();
app.get("/hello", ctx -> ctx.html("Hello, Javalin!"));
app.get("/users", UserController.fetchAllUsernames);
app.get("/users/:id", UserController.fetchById);
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.javalin.User;
public class User {
public final int id;
public final String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.javalin.User;
import io.javalin.Handler;
import java.util.Objects;
public class UserController {
public static Handler fetchAllUsernames = ctx -> {
UserDao dao = UserDao.instance();
Iterable<String> allUsers = dao.getAllUsernames();
ctx.json(allUsers);
};
public static Handler fetchById = ctx -> {
int id = Integer.parseInt(Objects.requireNonNull(ctx.param("id")));
UserDao dao = UserDao.instance();
User user = dao.getUserById(id);
if (user == null) {
ctx.html("Not Found");
} else {
ctx.json(user);
}
};
}

View File

@ -0,0 +1,33 @@
package com.baeldung.javalin.User;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
class UserDao {
private final List<User> users = Arrays.asList(
new User(0, "Steve Rogers"),
new User(1, "Tony Stark"),
new User(2, "Carol Danvers")
);
private static UserDao userDao = null;
private UserDao() {
}
static UserDao instance() {
if (userDao == null) {
userDao = new UserDao();
}
return userDao;
}
Optional<User> getUserById(int id) { return users.stream().filter(u -> u.id == id).findFirst(); }
Iterable<String> getAllUsernames() {
return users.stream().map(user -> user.name).collect(Collectors.toList());
}
}