package controllers.api;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import play.mvc.Http.StatusCode;
import play.mvc.Router;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import play.data.validation.Valid;
import play.mvc.Http.StatusCode;
import models.Subscriber;
import controllers.BaseController;
import controllers.Check;
import controllers.Data;
import controllers.Security;
import exceptions.ValidationException;
@Check(Security.ROOT_ROLE)
public class Subscribers extends ApiSecured {
public static void list(Integer offset, Integer limit) {
if(offset == null) offset = 0;
if(limit==null || limit > LIMIT || limit==0) {
limit = LIMIT;
}
Data<Subscriber> data = new Data<Subscriber>();
List<Subscriber> subscribers = Subscriber.paginate(Subscriber.all(), offset, limit);
data.total = Subscriber.count();
data.data = subscribers;
Type dataType = new TypeToken<Data<Subscriber>>(){}.getType();
renderJSON(gson().toJson(data, dataType));
}
public static void get(Long id) {
final Subscriber subscriber = Subscriber.get(id);
if(subscriber==null) {
response.status = StatusCode.NOT_FOUND;
return;
}
renderJSON(gson().toJson(subscriber));
}
public static void add(JsonObject body) throws ValidationException {
Subscriber subscriber = new Gson().fromJson(body, Subscriber.class);
validation.valid(subscriber);
if(validation.hasErrors()) {
throw new ValidationException(validation.errors());
}
subscriber.insert();
response.status = StatusCode.CREATED;
Map map = new HashMap();
map.put("id", subscriber.id);
String url = Router.reverse("api.Subscribers.get", map).url;// GET /clients/1541
response.setHeader("location", url);
renderJSON(gson().toJson(subscriber));
}
public static void edit(Long id, JsonObject body) {
Subscriber subscriber = new Gson().fromJson(body, Subscriber.class);
if(subscriber==null) {
response.status = StatusCode.NOT_FOUND;
return;
}
subscriber.update();
response.status = StatusCode.OK;
Map map = new HashMap();
map.put("id", subscriber.id);
String url = Router.reverse("api.Subscribers.get", map).url;// GET /clients/1541
response.setHeader("location", url);
}
public static void delete(Long id) {
final Subscriber subscriber = Subscriber.get(id);
if(subscriber==null) {
response.status = StatusCode.NOT_FOUND;
return;
}
subscriber.delete();
response.status = StatusCode.NO_RESPONSE;
}
}