|
| 1 | +package controllers; |
| 2 | +import models.*; |
| 3 | +import util.*; |
| 4 | +import play.mvc.*; |
| 5 | +import play.libs.Json; |
| 6 | +import play.libs.Json.*; |
| 7 | +import com.fasterxml.jackson.databind.JsonNode; |
| 8 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 9 | +import java.util.List; |
| 10 | + |
| 11 | +public class StudentController extends Controller { |
| 12 | + public Result create() { |
| 13 | + JsonNode json = request().body().asJson(); |
| 14 | + if(json == null) |
| 15 | + return badRequest(Util.createResponse("Expecting Json data",false)); |
| 16 | + Student student=StudentStore.getInstance().addStudent((Student)Json.fromJson(json,Student.class)); |
| 17 | + JsonNode jsonObject=Json.toJson(student); |
| 18 | + return created(Util.createResponse(jsonObject,true)); |
| 19 | + } |
| 20 | + public Result update() { |
| 21 | + JsonNode json = request().body().asJson(); |
| 22 | + if(json == null) |
| 23 | + return badRequest(Util.createResponse("Expecting Json data",false)); |
| 24 | + Student student=StudentStore.getInstance().updateStudent((Student)Json.fromJson(json,Student.class)); |
| 25 | + if(student==null){ |
| 26 | + return notFound(Util.createResponse("Student not found",false)); |
| 27 | + } |
| 28 | + |
| 29 | + JsonNode jsonObject=Json.toJson(student); |
| 30 | + return ok(Util.createResponse(jsonObject,true)); |
| 31 | + } |
| 32 | + public Result retrieve(int id) { |
| 33 | + Student student=StudentStore.getInstance().getStudent(id); |
| 34 | + if(student==null){ |
| 35 | + return notFound(Util.createResponse("Student with id:"+id+" not found",false)); |
| 36 | + } |
| 37 | + JsonNode jsonObjects=Json.toJson(student); |
| 38 | + return ok(Util.createResponse(jsonObjects,true)); |
| 39 | + } |
| 40 | + public Result listStudents() { |
| 41 | + List<Student> result=StudentStore.getInstance().getAllStudents(); |
| 42 | + ObjectMapper mapper = new ObjectMapper(); |
| 43 | + |
| 44 | + JsonNode jsonData=mapper.convertValue(result, JsonNode.class); |
| 45 | + return ok(Util.createResponse(jsonData,true)); |
| 46 | + |
| 47 | + } |
| 48 | + public Result delete(int id) { |
| 49 | + boolean status=StudentStore.getInstance().deleteStudent(id); |
| 50 | + if(!status){ |
| 51 | + return notFound(Util.createResponse("Student with id:"+id+" not found",false)); |
| 52 | + } |
| 53 | + return ok(Util.createResponse("Student with id:"+id+" deleted",true)); |
| 54 | + } |
| 55 | + |
| 56 | +} |
0 commit comments