use of org.restlet.resource.ResourceException 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.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 handleQuery.
private void handleQuery(String segment) {
Request request = Request.getCurrent();
Response response = Response.getCurrent();
// Query
// Try to locate either the query method or command method that should be used
Method queryMethod = resourceMethodQueries.get(segment);
if (queryMethod == null) {
queryMethod = resourceMethodCommands.get(segment);
}
if (queryMethod == null) {
// Not found as interaction, try SubResource
Method resourceMethod = subResources.get(segment);
if (resourceMethod != null && resourceMethod.getAnnotation(SubResource.class) != null) {
// Found it! Redirect to it
response.setStatus(Status.REDIRECTION_FOUND);
response.setLocationRef(new Reference(request.getResourceRef().toString() + "/").toString());
return;
} else {
// 404
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
}
}
// Check if this is a request to show the form for this interaction
if ((request.getMethod().isSafe() && queryMethod.getParameterTypes().length != 0 && request.getResourceRef().getQuery() == null) || (!request.getMethod().isSafe() && queryMethod.getParameterTypes().length != 0 && !(request.getEntity().isAvailable() || request.getResourceRef().getQuery() != null || queryMethod.getParameterTypes()[0].equals(Response.class)))) {
// Show form
try {
// Tell client to try again
response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY);
response.getAllowedMethods().add(org.restlet.data.Method.GET);
response.getAllowedMethods().add(org.restlet.data.Method.POST);
result(formForMethod(queryMethod));
} 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(queryMethod, current(), module)) {
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
}
try {
// Create argument
Object[] arguments;
if (queryMethod.getParameterTypes().length > 0) {
try {
arguments = requestReader.readRequest(Request.getCurrent(), queryMethod);
if (arguments == null) {
// Show form
result(formForMethod(queryMethod));
return;
}
} catch (IllegalArgumentException e) {
// Still missing some values - show form
result(formForMethod(queryMethod));
return;
}
} else {
// No arguments to this query
arguments = new Object[0];
}
// Invoke method
Request.getCurrent().getAttributes().put(ARGUMENTS, arguments);
Object result = queryMethod.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 ContextResource method select.
protected <T> T select(Class<T> entityClass, String id) throws ResourceException {
try {
T composite = module.currentUnitOfWork().get(entityClass, id);
current().select(composite);
return composite;
} catch (EntityTypeNotFoundException | NoSuchEntityException e) {
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
}
}
use of org.restlet.resource.ResourceException in project qi4j-sdk by Qi4j.
the class ContextResourceClient method delete.
// Delete
public HandlerCommand delete(ResponseHandler responseHandler, ResponseHandler processingErrorHandler) throws ResourceException {
if (responseHandler == null)
responseHandler = deleteHandler;
Request request = new Request(Method.DELETE, new Reference(reference.toUri()).toString());
contextResourceFactory.updateCommandRequest(request);
int tries = 3;
while (true) {
Response response = new Response(request);
try {
contextResourceFactory.getClient().handle(request, response);
if (!response.getStatus().isSuccess()) {
return errorHandler.handleResponse(response, this);
} else {
// Reset modification date
contextResourceFactory.updateCache(response);
return responseHandler.handleResponse(response, this);
}
} catch (ResourceException e) {
if (e.getStatus().equals(Status.CONNECTOR_ERROR_COMMUNICATION) || e.getStatus().equals(Status.CONNECTOR_ERROR_CONNECTION)) {
if (tries == 0) {
// Give up
throw e;
} else {
// Try again
tries--;
continue;
}
} else {
// Abort
throw e;
}
} finally {
try {
response.getEntity().exhaust();
} catch (Throwable e) {
// Ignore
}
}
}
}
Aggregations