use of org.restlet.resource.ResourceException in project qi4j-sdk by Qi4j.
the class ResourceValidity method checkRequest.
public void checkRequest() throws ResourceException {
// Check command rules
Date modificationDate = request.getConditions().getUnmodifiedSince();
if (modificationDate != null) {
EntityState state = spi.entityStateOf(entity);
// Cut off milliseconds
Date lastModified = new Date((state.lastModified() / 1000) * 1000);
if (lastModified.after(modificationDate)) {
throw new ResourceException(Status.CLIENT_ERROR_CONFLICT);
}
}
// Check query rules
modificationDate = request.getConditions().getModifiedSince();
if (modificationDate != null) {
EntityState state = spi.entityStateOf(entity);
// Cut off milliseconds
Date lastModified = new Date((state.lastModified() / 1000) * 1000);
if (!lastModified.after(modificationDate)) {
throw new ResourceException(Status.REDIRECTION_NOT_MODIFIED);
}
}
}
use of org.restlet.resource.ResourceException in project qi4j-sdk by Qi4j.
the class ContextResource method handleCommand.
private void handleCommand(String segment) {
Request request = Request.getCurrent();
Response response = Response.getCurrent();
// Check if this is a request to show the form for this command
Method interactionMethod = resourceMethodCommands.get(segment);
if (shouldShowCommandForm(interactionMethod)) {
// Show form
// TODO This should check if method is idempotent
response.getAllowedMethods().add(org.restlet.data.Method.POST);
try {
// Check if there is a query with this name - if so invoke it
Method queryMethod = resourceMethodQueries.get(segment);
if (queryMethod != null) {
result(queryMethod.invoke(this));
} else {
request.setMethod(org.restlet.data.Method.POST);
response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY);
result(formForMethod(interactionMethod));
}
} catch (Exception e) {
handleException(response, e);
}
} else {
// Check timestamps
ResourceValidity validity = (ResourceValidity) request.getAttributes().get(RESOURCE_VALIDITY);
if (validity != null) {
validity.checkRequest();
}
// Check method constraints
if (!constraints.isValid(interactionMethod, current(), module)) {
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
}
// Create argument
Object[] arguments = requestReader.readRequest(Request.getCurrent(), interactionMethod);
Request.getCurrent().getAttributes().put(ARGUMENTS, arguments);
// Invoke method
try {
Object result = interactionMethod.invoke(this, arguments);
if (result != null) {
if (result instanceof Representation) {
response.setEntity((Representation) result);
} else {
result(convert(result));
}
}
} catch (Throwable e) {
handleException(response, e);
}
}
}
use of org.restlet.resource.ResourceException in project qi4j-sdk by Qi4j.
the class DefaultRequestReader method readRequest.
@Override
public Object[] readRequest(Request request, Method method) throws ResourceException {
if (request.getMethod().equals(org.restlet.data.Method.GET)) {
Object[] args = new Object[method.getParameterTypes().length];
Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm();
Form entityAsForm = null;
Representation representation = Request.getCurrent().getEntity();
if (representation != null && !EmptyRepresentation.class.isInstance(representation)) {
entityAsForm = new Form(representation);
} else {
entityAsForm = new Form();
}
if (queryAsForm.isEmpty() && entityAsForm.isEmpty()) {
// Nothing submitted yet - show form
return null;
}
if (args.length == 1) {
if (ValueComposite.class.isAssignableFrom(method.getParameterTypes()[0])) {
Class<?> valueType = method.getParameterTypes()[0];
args[0] = getValueFromForm((Class<ValueComposite>) valueType, queryAsForm, entityAsForm);
return args;
} else if (Form.class.equals(method.getParameterTypes()[0])) {
args[0] = queryAsForm.isEmpty() ? entityAsForm : queryAsForm;
return args;
} else if (Response.class.equals(method.getParameterTypes()[0])) {
args[0] = Response.getCurrent();
return args;
}
}
parseMethodArguments(method, args, queryAsForm, entityAsForm);
return args;
} else {
Object[] args = new Object[method.getParameterTypes().length];
Class<? extends ValueComposite> commandType = (Class<? extends ValueComposite>) method.getParameterTypes()[0];
if (method.getParameterTypes()[0].equals(Response.class)) {
return new Object[] { Response.getCurrent() };
}
Representation representation = Request.getCurrent().getEntity();
MediaType type = representation.getMediaType();
if (type == null) {
Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm(CharacterSet.UTF_8);
if (ValueComposite.class.isAssignableFrom(method.getParameterTypes()[0])) {
args[0] = getValueFromForm(commandType, queryAsForm, new Form());
} else {
parseMethodArguments(method, args, queryAsForm, new Form());
}
return args;
} else {
if (method.getParameterTypes()[0].equals(Representation.class)) {
// Command method takes Representation as input
return new Object[] { representation };
} else if (method.getParameterTypes()[0].equals(Form.class)) {
// Command method takes Form as input
return new Object[] { new Form(representation) };
} else if (ValueComposite.class.isAssignableFrom(method.getParameterTypes()[0])) {
// Need to parse input into ValueComposite
if (type.equals(MediaType.APPLICATION_JSON)) {
String json = Request.getCurrent().getEntityAsText();
if (json == null) {
LoggerFactory.getLogger(getClass()).error("Restlet bugg http://restlet.tigris.org/issues/show_bug.cgi?id=843 detected. Notify developers!");
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Bug in Tomcat encountered; notify developers!");
}
Object command = module.newValueFromSerializedState(commandType, json);
args[0] = command;
return args;
} else if (type.equals(MediaType.TEXT_PLAIN)) {
String text = Request.getCurrent().getEntityAsText();
if (text == null) {
LoggerFactory.getLogger(getClass()).error("Restlet bugg http://restlet.tigris.org/issues/show_bug.cgi?id=843 detected. Notify developers!");
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Bug in Tomcat encountered; notify developers!");
}
args[0] = text;
return args;
} else if (type.equals((MediaType.APPLICATION_WWW_FORM))) {
Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm();
Form entityAsForm;
if (representation != null && !EmptyRepresentation.class.isInstance(representation) && representation.isAvailable()) {
entityAsForm = new Form(representation);
} else {
entityAsForm = new Form();
}
Class<?> valueType = method.getParameterTypes()[0];
args[0] = getValueFromForm((Class<ValueComposite>) valueType, queryAsForm, entityAsForm);
return args;
} else {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Command has to be in JSON format");
}
} else if (method.getParameterTypes()[0].isInterface() && method.getParameterTypes().length == 1) {
Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm();
Form entityAsForm;
if (representation != null && !EmptyRepresentation.class.isInstance(representation) && representation.isAvailable()) {
entityAsForm = new Form(representation);
} else {
entityAsForm = new Form();
}
args[0] = module.currentUnitOfWork().get(method.getParameterTypes()[0], getValue("entity", queryAsForm, entityAsForm));
return args;
} else {
Form queryAsForm = Request.getCurrent().getResourceRef().getQueryAsForm();
Form entityAsForm;
if (representation != null && !EmptyRepresentation.class.isInstance(representation) && representation.isAvailable()) {
entityAsForm = new Form(representation);
} else {
entityAsForm = new Form();
}
parseMethodArguments(method, args, queryAsForm, entityAsForm);
return args;
}
}
}
}
use of org.restlet.resource.ResourceException 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.resource.ResourceException 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);
}
}
Aggregations