use of org.restlet.data.MediaType 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.MediaType in project qi4j-sdk by Qi4j.
the class ContextResourceClientFactory method setAcceptedMediaTypes.
public void setAcceptedMediaTypes(MediaType... acceptedMediaTypes) {
List<Preference<MediaType>> mediatypes = new ArrayList<Preference<MediaType>>();
for (MediaType mediaType : acceptedMediaTypes) {
mediatypes.add(new Preference<MediaType>(mediaType));
}
info.setAcceptedMediaTypes(mediatypes);
}
use of org.restlet.data.MediaType 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.data.MediaType in project qi4j-sdk by Qi4j.
the class DefaultResponseWriter method writeResponse.
@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
if (MediaType.APPLICATION_JSON.equals(type)) {
if (result instanceof String || result instanceof Number || result instanceof Boolean) {
StringRepresentation representation = new StringRepresentation(result.toString(), MediaType.APPLICATION_JSON);
response.setEntity(representation);
return true;
}
}
return false;
}
use of org.restlet.data.MediaType 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