You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to sparkjava
Hello,Thank you for this tutorial!I have a question, can you help me?Thinking in Spark 2.6.0, I`m using the RouteGroup for map my routes:public class Service {
public static void main(String[] args) { ...
path("/areas", AreaRouteGroup.paths);
}}
And the "AreaRouteGroup" is look like this:public class AreaRouteGroup {
private static ResponseTransformer transformer = new JsonResponseTransformer();
private static String acceptType = "application/json";
public static RouteGroup paths = () -> {
get("", AreaController.listAll, transformer);
get("/:id", AreaController.findById, transformer);
post("", acceptType, AreaController.create, transformer);
put("/:id", acceptType, AreaController.change);
};
}An exemplo of the controller method is the create:public class AreaController { ...
public static Route create = (Request request, Response response) -> {
AreaPayload payload = JsonMapper.jsonToData(request.body(), AreaPayload.class);
Map<String, String> errors = payload.validate();
if (!errors.isEmpty()) {
return HttpResponse.badRequest(response, errors);
}
Area area = dao.create(payload.getName());
return HttpResponse.created(response, area);
};
...
}I`m trying to remove the boilerplate from lines 1-6 in the above controller method using the an interface PayloadHandler:public interface PayloadHandler<V extends Validable> extends Route {
@SuppressWarnings({ "unchecked", "unused" })
public default Object handle(Request request, Response response) throws Exception {
try {
// TODO: get the valueClass of generic type;
Class<?> valueClass = null;
V value = null;
if (valueClass == EmptyPayload.class) {
value = (V) JsonMapper.jsonToData(request.body(), valueClass);
}
Map<String, String> errors = value.validate();
if (!errors.isEmpty()) {
return HttpResponse.badRequest(response, errors);
} else {
return handle(value, request, response);
}
} catch (JsonMappingException e) {
System.out.println(e.getMessage());
String error = "Invalid JSON";
return HttpResponse.internalError(response, error);
} finally {
request.session().invalidate();
}
}
Object handle(V value, Request request, Response response);
}
But this solution is not working because I`m do not know how to get the valueClass of generic type in the first line after the try. I`m imagining a solution similar the Exception handler where is possible to say the class type of Exception:https://github.com/perwendel/spark/blob/master/src/main/java/spark/ExceptionHandler.javaexception(Exception.class, (exception, request, response) -> {
response.status(500);
response.body(exception.getMessage());
});Is it possible?Thank you again.