Create a REST service using Play with Java for a User database

For a contact management sample application that I am building, I need a user REST service which I can use to validate users and use the UUID to search the contacts of this user (the contact database will be exposed by another REST service).
I decided to build this REST service using Play and implement that in Java.
This blog explains how I have build this REST service.

Prepare development system
Go to https://www.playframework.com/ and download and install the Typesafe Activator which I will use in building the REST service.
When using IntelliJ, make sure that you have the SBT plugin installed in IntelliJ. You might also want the SBT Executor and Scala plugin when you want to develop some more with Play.

Create the REST application from a template using activator
Use the activator to create a project named “user-service” from the template “play-java”.

cd c:workspaceakka-contacts
activator new user-service play-java

When the project is created you can start the application.

cd c:workspaceakka-contactsuser-service
activator run

You can now open this project in IntelliJ so we can modify the sample play application to be able to run it as a user microservice.

Enable ebean
I use ebean to persist my users. To enable ebean, add the following line to plugins.sbt:

addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "1.0.0")
Change in build.sbt the line which contains the “enablePlugins” into the following:
lazy val root = (project in file(".")).enablePlugins(PlayJava,PlayEbean)
Finally add the following lines to application.conf:
ebean.default = ["models.*"]
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
Note: I have frequently found that I needed to restart activator before he could find ebean!

Create model class for our user database

Create the file appsmodelsUser.java
package models;

import com.avaje.ebean.Model;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class User extends Model {
    @Id
    private Long id;
    private String name;
    private String uuid;

    public static Finder find = new Finder(User.class);

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }
}
Write the routes file
Change the routes file to the following:
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
POST /user       controllers.Application.addUser()
GET  /users      controllers.Application.getUsers()
GET  /user/:uuid   controllers.Application.getUser(id: String)
DELETE /user/:uuid controllers.Application.deleteUser(id: String)
Remove the unneeded files
remove index.scala.html and main.scala.html. They are not needed anymore and will give an arrer because we removed the assets route in the routes file.

You can also remove all js, css and image files from the public subfolder.
Write the controller
Change the Application.java to the following
package controllers;
import models.User;
import play.data.Form;
import play.mvc.*;
import java.util.List;
import static play.libs.Json.toJson;
public class Application extends Controller {

 public Result addUser(){
  User user = Form.form(User.class).bindFromRequest().get();
  user.save();
  return ok(toJson(user));
 }

 public Result getUsers(){
  List users = User.find.all();
  return ok(toJson(users));
 }

 public Result getUser(String uuid){
  List users = User.find.where().eq("uuid",uuid).findList();
  if (!users.isEmpty()){
   return ok(toJson(users.get(0)));
  }
  return notFound();
 }

 public Result deleteUser(String uuid){
  List users = User.find.where().eq("uuid",uuid).findList();
  if (!users.isEmpty()){
   users.get(0).delete();
   return ok();
  }
  return notFound();
 }
}
Use sample data in our H2 database
When running the application for the first time, evolutions will update the 1.sql for you and asks you to run the sql script to build the tables.
In this sample, I will modify the 1.sql myself so I can populate the user table with some users.
# --- !Ups
create table user (
 id bigint not null,
 name varchar(255),
 uuid varchar(255),
 constraint pk_user primary key (id))
;
create sequence user_seq;
INSERT INTO user(id, name, uuid) VALUES (user_seq.nextVal, 'Jeff','0001234');
INSERT INTO user(id, name, uuid) VALUES (user_seq.nextVal, 'Jack','0001235');
INSERT INTO user(id, name, uuid) VALUES (user_seq.nextVal, 'John','0001236');
# --- !Downs
SET REFERENTIAL_INTEGRITY FALSE;
drop table if exists user;
SET REFERENTIAL_INTEGRITY TRUE;
drop sequence if exists user_seq;
Test the application and create the schema
You might want to restart the application so the newly 1.sql will be executed.
The first time you open the application (e.g. opening http://localhost:9000/users) using a web browser you will see an error ‘database default needs evolution’.
Press the ‘apply this script now’ button to run the 1.sql sql sript.

After applying the script, the apllication will run and you will be able show all contacts with http://localhost:9000/users and a specific user with http://localhost:9000/user/2

Automatically apply the evolutions database scripts
Instead of manually apply the database script, you can also configure the system to automatically apply the database scripts by adding the following line in the applications.conf:

play.evolutions.autoApply=true


Run the application on another port then 9000
Instead of “activator run”, can can start the service with “activator -Dhttp.port=9090 run”.

Geef een reactie

Gelieve met een van deze methodes in te loggen om je reactie te plaatsen:

WordPress.com logo

Je reageert onder je WordPress.com account. Log uit /  Bijwerken )

Google+ photo

Je reageert onder je Google+ account. Log uit /  Bijwerken )

Twitter-afbeelding

Je reageert onder je Twitter account. Log uit /  Bijwerken )

Facebook foto

Je reageert onder je Facebook account. Log uit /  Bijwerken )

Verbinden met %s