use of org.restlet.representation.Representation 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;
}
use of org.restlet.representation.Representation in project qi4j-sdk by Qi4j.
the class ValueDescriptorResponseWriter method writeResponse.
@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
if (result instanceof ValueDescriptor) {
MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
if (MediaType.APPLICATION_JSON.equals(type)) {
JSONObject json = new JSONObject();
ValueDescriptor vd = (ValueDescriptor) result;
try {
for (PropertyDescriptor propertyDescriptor : vd.state().properties()) {
Object o = propertyDescriptor.initialValue(module);
if (o == null) {
json.put(propertyDescriptor.qualifiedName().name(), JSONObject.NULL);
} else {
json.put(propertyDescriptor.qualifiedName().name(), o.toString());
}
}
} catch (JSONException e) {
throw new ResourceException(e);
}
StringRepresentation representation = new StringRepresentation(json.toString(), MediaType.APPLICATION_JSON);
response.setEntity(representation);
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("form.htm").process(context, writer);
} catch (TemplateException e) {
throw new IOException(e);
}
}
};
response.setEntity(rep);
return true;
}
}
return false;
}
use of org.restlet.representation.Representation in project qi4j-sdk by Qi4j.
the class EntitiesResource method representHtml.
private Representation representHtml() throws ResourceException {
try {
final Iterable<EntityReference> query = entityFinder.findEntities(EntityComposite.class, null, null, null, null, Collections.<String, Object>emptyMap());
Representation representation = new WriterRepresentation(MediaType.TEXT_HTML) {
@Override
public void write(Writer buf) throws IOException {
PrintWriter out = new PrintWriter(buf);
out.println("<html><head><title>All entities</title></head><body><h1>All entities</h1><ul>");
for (EntityReference entity : query) {
out.println("<li><a href=\"" + getRequest().getResourceRef().clone().addSegment(entity.identity() + ".html") + "\">" + entity.identity() + "</a></li>");
}
out.println("</ul></body></html>");
}
};
representation.setCharacterSet(CharacterSet.UTF_8);
return representation;
} catch (EntityFinderException e) {
throw new ResourceException(e);
}
}
use of org.restlet.representation.Representation in project qi4j-sdk by Qi4j.
the class ContextRestlet method handle.
@Override
public void handle(Request request, Response response) {
super.handle(request, response);
MDC.put("url", request.getResourceRef().toString());
try {
int tries = 0;
// TODO Make this number configurable
while (tries < 10) {
tries++;
// Root of the call
Reference ref = request.getResourceRef();
List<String> segments = ref.getScheme().equals("riap") ? ref.getRelativeRef(new Reference("riap://application/")).getSegments() : ref.getRelativeRef().getSegments();
// Handle conversion of verbs into standard interactions
if (segments.get(segments.size() - 1).equals("")) {
if (request.getMethod().equals(Method.DELETE)) {
// Translate DELETE into command "delete"
segments.set(segments.size() - 1, "delete");
} else if (request.getMethod().equals(Method.PUT)) {
// Translate PUT into command "update"
segments.set(segments.size() - 1, "update");
}
}
request.getAttributes().put("segments", segments);
request.getAttributes().put("template", new StringBuilder("/rest/"));
Usecase usecase = UsecaseBuilder.buildUsecase(getUsecaseName(request)).withMetaInfo(request.getMethod().isSafe() ? CacheOptions.ALWAYS : CacheOptions.NEVER).newUsecase();
UnitOfWork uow = module.newUnitOfWork(usecase);
ObjectSelection.newSelection();
try {
// Start handling the build-up for the context
Uniform resource = createRoot(request, response);
resource.handle(request, response);
if (response.getEntity() != null) {
if (response.getEntity().getModificationDate() == null) {
ResourceValidity validity = (ResourceValidity) Request.getCurrent().getAttributes().get(ContextResource.RESOURCE_VALIDITY);
if (validity != null) {
validity.updateResponse(response);
}
}
// Check if characterset is set
if (response.getEntity().getCharacterSet() == null) {
response.getEntity().setCharacterSet(CharacterSet.UTF_8);
}
// Check if language is set
if (response.getEntity().getLanguages().isEmpty()) {
response.getEntity().getLanguages().add(Language.ENGLISH);
}
uow.discard();
} else {
// Check if last modified and tag is set
ResourceValidity validity = null;
try {
validity = ObjectSelection.type(ResourceValidity.class);
} catch (IllegalArgumentException e) {
// Ignore
}
uow.complete();
Object result = commandResult.getResult();
if (result != null) {
if (result instanceof Representation) {
response.setEntity((Representation) result);
} else {
if (!responseWriter.writeResponse(result, response)) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Could not write result of type " + result.getClass().getName());
}
}
if (response.getEntity() != null) {
// Check if characterset is set
if (response.getEntity().getCharacterSet() == null) {
response.getEntity().setCharacterSet(CharacterSet.UTF_8);
}
// Check if language is set
if (response.getEntity().getLanguages().isEmpty()) {
response.getEntity().getLanguages().add(Language.ENGLISH);
}
// Check if last modified and tag should be set
if (validity != null) {
UnitOfWork lastModifiedUoW = module.newUnitOfWork();
try {
validity.updateEntity(lastModifiedUoW);
validity.updateResponse(response);
} finally {
lastModifiedUoW.discard();
}
}
}
}
return;
}
return;
} catch (ConcurrentEntityModificationException ex) {
uow.discard();
// Try again
ObjectSelection.newSelection();
} catch (Throwable e) {
uow.discard();
handleException(response, e);
return;
}
}
// Try again
} finally {
MDC.clear();
}
}
use of org.restlet.representation.Representation in project qi4j-sdk by Qi4j.
the class FormResponseWriter method writeResponse.
@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
if (result instanceof Form) {
MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
if (MediaType.APPLICATION_JSON.equals(type)) {
JSONObject json = new JSONObject();
Form form = (Form) result;
try {
for (Parameter parameter : form) {
String value = parameter.getValue();
if (value == null) {
json.put(parameter.getName(), JSONObject.NULL);
} else {
json.put(parameter.getName(), value);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
StringRepresentation representation = new StringRepresentation(json.toString(), MediaType.APPLICATION_JSON);
response.setEntity(representation);
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> root = new HashMap<String, Object>();
root.put("request", response.getRequest());
root.put("response", response);
root.put("result", result);
try {
Template formHtmlTemplate = cfg.getTemplate("form.htm");
formHtmlTemplate.process(root, writer);
} catch (TemplateException e) {
throw new IOException(e);
}
}
};
response.setEntity(rep);
return true;
}
}
return false;
}
Aggregations