use of org.restlet.data.Reference in project qi4j-sdk by Qi4j.
the class DomainEventSourceResource method handle.
@Override
public void handle(Request request, Response response) {
long eventCount = source.count();
long pageSize = 10;
long startEvent = -1;
long endEvent = -1;
long limit = pageSize;
final List<UnitOfWorkDomainEventsValue> eventsValues = new ArrayList<UnitOfWorkDomainEventsValue>();
final Feed feed = new Feed();
feed.setBaseReference(request.getResourceRef().getParentRef());
List<Link> links = feed.getLinks();
String remainingPart = request.getResourceRef().getRemainingPart();
if (remainingPart.equals("/")) {
// Current set - always contains the last "pageSize" events
startEvent = Math.max(0, eventCount - pageSize - 1);
feed.setTitle(new Text("Current set"));
if (startEvent > 0) {
long previousStart = Math.max(0, startEvent - pageSize);
long previousEnd = startEvent - 1;
Link link = new Link(new Reference(previousStart + "," + previousEnd), new Relation("previous"), MediaType.APPLICATION_ATOM);
link.setTitle("Previous page");
links.add(link);
}
} else {
// Archive
String[] indices = remainingPart.substring(1).split(",");
if (indices.length == 1) {
// Working set
startEvent = Long.parseLong(indices[0]);
endEvent = startEvent + pageSize - 1;
limit = pageSize;
feed.setTitle(new Text("Working set"));
} else if (indices.length == 2) {
feed.setTitle(new Text("Archive page"));
startEvent = Long.parseLong(indices[0]);
endEvent = Long.parseLong(indices[1]);
limit = 1 + endEvent - startEvent;
} else
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
if (startEvent > 0) {
long previousStart = Math.max(0, startEvent - pageSize);
long previousEnd = startEvent - 1;
Link link = new Link(new Reference(previousStart + "," + previousEnd), new Relation("previous"), MediaType.APPLICATION_ATOM);
link.setTitle("Previous page");
links.add(link);
}
long nextStart = endEvent + 1;
long nextEnd = nextStart + pageSize - 1;
if (nextStart < eventCount)
if (nextEnd >= eventCount) {
Link next = new Link(new Reference(nextStart + ""), new Relation("next"), MediaType.APPLICATION_ATOM);
next.setTitle("Working set");
links.add(next);
} else {
Link next = new Link(new Reference(nextStart + "," + nextEnd), new Relation("next"), MediaType.APPLICATION_ATOM);
next.setTitle("Next page");
links.add(next);
}
}
try {
source.events(startEvent, limit).transferTo(Outputs.collection(eventsValues));
} catch (Throwable throwable) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, throwable);
}
Link last = new Link(new Reference("0," + (pageSize - 1)), new Relation("last"), MediaType.APPLICATION_ATOM);
last.setTitle("Last archive page");
links.add(last);
Link first = new Link(new Reference("."), new Relation("first"), MediaType.APPLICATION_ATOM);
first.setTitle("Current set");
links.add(first);
/*
if (previousPage != -1)
{
Link link = new Link( new Reference( ""+previousPage ), new Relation( "prev-archive" ), MediaType.APPLICATION_ATOM );
link.setTitle( "Previous archive page" );
links.add( link );
}
if (nextPage != -1)
{
Link link = new Link( new Reference( "" + nextPage ), new Relation( "next-archive" ), MediaType.APPLICATION_ATOM );
link.setTitle( "Next archive page" );
links.add( link );
}
else if (startEvent != workingSetOffset)
{
Link next = new Link( new Reference( "" ), new Relation( "next" ), MediaType.APPLICATION_ATOM );
next.setTitle( "Next page" );
links.add( next );
}
*/
Date lastModified = null;
for (UnitOfWorkDomainEventsValue eventsValue : eventsValues) {
Entry entry = new Entry();
entry.setTitle(new Text(eventsValue.usecase().get() + "(" + eventsValue.user().get() + ")"));
entry.setPublished(new Date(eventsValue.timestamp().get()));
entry.setModificationDate(lastModified = new Date(eventsValue.timestamp().get()));
entry.setId(Long.toString(startEvent + 1));
startEvent++;
Content content = new Content();
content.setInlineContent(new StringRepresentation(eventsValue.toString(), MediaType.APPLICATION_JSON));
entry.setContent(content);
feed.getEntries().add(entry);
}
feed.setModificationDate(lastModified);
MediaType mediaType = request.getClientInfo().getPreferredMediaType(Iterables.toList(iterable(MediaType.TEXT_HTML, MediaType.APPLICATION_ATOM)));
if (MediaType.APPLICATION_ATOM.equals(mediaType)) {
WriterRepresentation representation = new WriterRepresentation(MediaType.APPLICATION_ATOM) {
@Override
public void write(final Writer writer) throws IOException {
feed.write(writer);
}
};
representation.setCharacterSet(CharacterSet.UTF_8);
response.setEntity(representation);
} else {
WriterRepresentation representation = new WriterRepresentation(MediaType.TEXT_HTML) {
@Override
public void write(Writer writer) throws IOException {
writer.append("<html><head><title>Events</title></head><body>");
for (Link link : feed.getLinks()) {
writer.append("<a href=\"").append(link.getHref().getPath()).append("\">");
writer.append(link.getTitle());
writer.append("</a><br/>");
}
writer.append("<ol>");
for (Entry entry : feed.getEntries()) {
writer.append("<li>").append(entry.getTitle().toString()).append("</li>");
}
writer.append("</ol></body>");
}
};
representation.setCharacterSet(CharacterSet.UTF_8);
response.setEntity(representation);
}
/*
} else
{
throw new ResourceException( Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE );
}
*/
}
use of org.restlet.data.Reference in project qi4j-sdk by Qi4j.
the class ContextResourceClient method newClient.
public synchronized ContextResourceClient newClient(String relativePath) {
if (relativePath.startsWith("http://")) {
return contextResourceFactory.newClient(new Reference(relativePath));
}
Reference reference = this.reference.clone();
if (relativePath.startsWith("/")) {
reference.setPath(relativePath);
} else {
reference.setPath(reference.getPath() + relativePath);
reference = reference.normalize();
}
return contextResourceFactory.newClient(reference);
}
use of org.restlet.data.Reference in project qi4j-sdk by Qi4j.
the class ContextResourceClient method command.
// Commands
HandlerCommand command(Link link, Object commandRequest, ResponseHandler handler, ResponseHandler processingErrorHandler) {
if (handler == null)
handler = commandHandlers.get(link.rel().get());
if (processingErrorHandler == null)
processingErrorHandler = processingErrorHandlers.get(link.rel().get());
// Check if we should do POST or PUT
Method method;
if (LinksUtil.withClass("idempotent").satisfiedBy(link)) {
method = Method.PUT;
} else {
method = Method.POST;
}
Reference ref = new Reference(reference.toUri().toString() + link.href().get());
return invokeCommand(ref, method, commandRequest, handler, processingErrorHandler);
}
use of org.restlet.data.Reference 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
}
}
}
}
use of org.restlet.data.Reference 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);
}
}
}
Aggregations