use of org.qi4j.library.rest.common.Resource in project qi4j-sdk by Qi4j.
the class ResourceResponseWriter method writeResponse.
@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
if (result instanceof Resource) {
Resource resourceValue = (Resource) result;
// Allowed methods
response.getAllowedMethods().add(Method.GET);
if (Iterables.matchesAny(LinksUtil.withRel("delete"), resourceValue.commands().get())) {
response.getAllowedMethods().add(Method.DELETE);
}
if (Iterables.matchesAny(LinksUtil.withRel("update"), resourceValue.commands().get())) {
response.getAllowedMethods().add(Method.PUT);
}
// Response according to what client accepts
MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
if (MediaType.APPLICATION_JSON.equals(type)) {
response.setEntity(new StringRepresentation(resourceValue.toString(), MediaType.APPLICATION_JSON));
return true;
} else if (MediaType.TEXT_HTML.equals(type)) {
Representation rep = new WriterRepresentation(MediaType.TEXT_HTML) {
@Override
public void write(Writer writer) throws IOException {
Map<String, Object> context = new HashMap<String, Object>();
context.put("request", response.getRequest());
context.put("response", response);
context.put("result", result);
try {
cfg.getTemplate("resource.htm").process(context, writer);
} catch (TemplateException e) {
throw new IOException(e);
}
}
};
response.setEntity(rep);
return true;
}
}
return false;
}
Aggregations