by mmahmoodict on 14 May 2013 05:30
Developed a rest service using Play Framework 2.1.1
Download Play Framework from Here and extract zip file to /usr and set directory executable permission.
Set PLAY_HOME in .bashrc or /etc/bash.bashrc
export PLAY_HOME=/usr/play
export PATH=${JAVA_HOME}/bin:$PLAY_HOME:${PATH}
Check installation by -
$ play version
Create new project -
$ play new restapp
Import project to Eclipse -
$ play eclipse # run this inside project directory! and import as usual.
Go to project directory and run Play project -
$ play run
# it will run in 9000 port by default, if 9000 port already used try - $ play "run 7000"
Try following URL in Browser!
http://localhost:9000/
Map URL to controller (URL dispatcher) by adding entry in conf/routes, for example -
GET /medicine controllers.DrugInfoController.getMedicineList()
GET /medicine/:id controllers.DrugInfoController.getMedicine(id: Long)
PUT /user controllers.UserDetailController.changeUserPassword()
POST /accesstoken controllers.UserAuthController.generateAccessToken()
Enable MySQL (Edit conf. in conf/application.conf) by uncommenting -
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://localhost/restapp?characterEncoding=UTF-8"
db.default.user=root
db.default.password="root"
Add MySQL dependency in project/Build.scala - like
val appDependencies = Seq(
// Add your project dependencies here,
javaCore,
javaJdbc,
javaEbean,
"mysql" % "mysql-connector-java" % "5.1.18"
)
Enable EBean (An ORM like Hibernate, nice and handy!), here 'models' package will be scanned!
ebean.default="models.*"
Controller Example :-)
public class DrugInfoController extends Controller { @Cached(key = "medicineList") // How you cna cache response! public static Result getMedicineList() { // Find all PharmaceuticalBrand using EBean! List<PharmaceuticalBrand> pharmaceuticalBrandList = PharmaceuticalBrand.find.all(); // Busines code here... List<Medicine> allMedicineList = new ArrayList<Medicine>(); for (Medicine med : allMedicineMap.values()) { allMedicineList.add(med); } // Logger example Logger.debug(pharmaceuticalBrandList.size() + " " + allMedicineList.size()); // Json response! return ok(Json.toJson(allMedicineList)); } public static Result getMedicine(Long id) { // Get object in cache! String uriString = request().uri(); if (Cache.get(uriString) != null) { return ok((JsonNode) Cache.get(uriString)); } // Busines code here... // Set object in cache! JsonNode resJsonNode = Json.toJson(medicineDetail); Cache.set(uriString, resJsonNode); return ok(resJsonNode); } }
Model Example :-)
package models; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import play.db.ebean.Model; import beans.MedicineInteraction; import com.avaje.ebean.Ebean; @Entity @Table(name = "PharmaceuticalBrand") public class PharmaceuticalBrand extends Model { private static final long serialVersionUID = 1L; private Long id; // Other properties here @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Long getId() { return id; } public void setId(Long id) { this.id = id; } // Other setter/getter here // Use EBean Finder, handy ORM! Some Example below - public static Finder<Long, PharmaceuticalBrand> find = new Finder<Long, PharmaceuticalBrand>(Long.class, PharmaceuticalBrand.class); public static PharmaceuticalBrand load(Long id) { return Ebean.find(PharmaceuticalBrand.class, id); } public static List<PharmaceuticalBrand> getPharmaceuticalBrandListByAtc(String atc) { return find.where().eq("atc", atc).findList(); } }
Authentication Example :-)
package auth; import play.i18n.Messages; import play.libs.Json; import play.mvc.Http; import play.mvc.Result; import play.mvc.Security; import beans.ResponseStatus; import beans.ResponseStatus.ResponseType; public class Secured extends Security.Authenticator { @Override public String getUsername(Http.Context ctx) { // Every request pass through this method // which Annotated @Security.Authenticated(Secured.class) // Here Secured.class is this class! so, import from package // Check Authentication here // If request is valid return any String except 'null', even empty String! // If request is not valid return null (then, onUnauthorized() method will execute!) //Follow this pseudocode :-) if(AuthService.isValidReq(ctx.request())){ return AuthService.USERNAME; } else{ return null; } } @Override public Result onUnauthorized(Http.Context ctx) { // Sample code for put something on request scope! Very unusal right! Angry? yah :-( ctx.args.put("responseStatus", responseStatus); ResponseStatus responseStatus = (ResponseStatus) Http.Context.current().args.get("responseStatus"); // You can return error response! return ok(Json.toJson(responseStatus)); } }