use of org.restlet.representation.WriterRepresentation in project qi4j-sdk by Qi4j.
the class ValueCompositeRequestWriter method writeRequest.
@Override
public boolean writeRequest(Object requestObject, Request request) throws ResourceException {
if (requestObject instanceof ValueComposite) {
// Value as parameter
final ValueComposite valueObject = (ValueComposite) requestObject;
if (request.getMethod().equals(Method.GET)) {
StateHolder holder = spi.stateOf(valueObject);
final ValueDescriptor descriptor = spi.valueDescriptorFor(valueObject);
final Reference ref = request.getResourceRef();
ref.setQuery(null);
try {
for (PropertyDescriptor propertyDescriptor : descriptor.state().properties()) {
Object value = holder.propertyFor(propertyDescriptor.accessor()).get();
String param;
if (value == null) {
param = null;
} else {
param = valueSerializer.serialize(value);
}
ref.addQueryParameter(propertyDescriptor.qualifiedName().name(), param);
}
} catch (ValueSerializationException e) {
throw new ResourceException(e);
}
} else {
request.setEntity(new WriterRepresentation(MediaType.APPLICATION_JSON) {
@Override
public void write(Writer writer) throws IOException {
setCharacterSet(CharacterSet.UTF_8);
valueSerializer.serialize(valueObject, new WriterOutputStream(writer));
}
});
}
return true;
}
return false;
}
use of org.restlet.representation.WriterRepresentation in project qi4j-sdk by Qi4j.
the class ValueCompositeResponseWriter method writeResponse.
@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
if (result instanceof ValueComposite) {
MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
if (MediaType.APPLICATION_JSON.equals(type)) {
StringRepresentation representation = new StringRepresentation(valueSerializer.serialize(result), 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 {
// Look for type specific template
Template template;
try {
template = cfg.getTemplate("/rest/template/" + result.getClass().getInterfaces()[0].getSimpleName() + ".htm");
} catch (Exception e) {
// Use default
template = cfg.getTemplate("value.htm");
}
Map<String, Object> context = new HashMap<String, Object>();
context.put("request", response.getRequest());
context.put("response", response);
context.put("result", result);
context.put("util", this);
try {
template.process(context, writer);
} catch (TemplateException e) {
throw new IOException(e);
}
}
public boolean isSequence(Object obj) {
return obj instanceof Collection;
}
};
response.setEntity(rep);
return true;
}
}
return false;
}
use of org.restlet.representation.WriterRepresentation in project qi4j-sdk by Qi4j.
the class EntityResource method representHtml.
private Representation representHtml(final EntityState entity) {
return new WriterRepresentation(MediaType.TEXT_HTML) {
@Override
public void write(Writer writer) throws IOException {
PrintWriter out = new PrintWriter(writer);
out.println("<html><head><title>" + entity.identity() + "</title>" + "<link rel=\"alternate\" type=\"application/rdf+xml\" " + "href=\"" + entity.identity() + ".rdf\"/></head><body>");
out.println("<h1>" + entity.identity() + "</h1>");
out.println("<form method=\"post\" action=\"" + getRequest().getResourceRef().getPath() + "\">\n");
out.println("<fieldset><legend>Properties</legend>\n<table>");
final EntityDescriptor descriptor = entity.entityDescriptor();
for (PropertyDescriptor persistentProperty : descriptor.state().properties()) {
Object value = entity.propertyValueOf(persistentProperty.qualifiedName());
out.println("<tr><td>" + "<label for=\"" + persistentProperty.qualifiedName() + "\" >" + persistentProperty.qualifiedName().name() + "</label></td>\n" + "<td><input " + "size=\"80\" " + "type=\"text\" " + (persistentProperty.isImmutable() ? "readonly=\"true\" " : "") + "name=\"" + persistentProperty.qualifiedName() + "\" " + "value=\"" + (value == null ? "" : valueSerialization.serialize(value)) + "\"/></td></tr>");
}
out.println("</table></fieldset>\n");
out.println("<fieldset><legend>Associations</legend>\n<table>");
for (AssociationDescriptor associationType : descriptor.state().associations()) {
Object value = entity.associationValueOf(associationType.qualifiedName());
if (value == null) {
value = "";
}
out.println("<tr><td>" + "<label for=\"" + associationType.qualifiedName() + "\" >" + associationType.qualifiedName().name() + "</label></td>\n" + "<td><input " + "type=\"text\" " + "size=\"80\" " + "name=\"" + associationType.qualifiedName() + "\" " + "value=\"" + value + "\"/></td></tr>");
}
out.println("</table></fieldset>\n");
out.println("<fieldset><legend>ManyAssociations</legend>\n<table>");
for (AssociationDescriptor associationType : descriptor.state().manyAssociations()) {
ManyAssociationState identities = entity.manyAssociationValueOf(associationType.qualifiedName());
String value = "";
for (EntityReference identity : identities) {
value += identity.identity() + "\n";
}
out.println("<tr><td>" + "<label for=\"" + associationType.qualifiedName() + "\" >" + associationType.qualifiedName().name() + "</label></td>\n" + "<td><textarea " + "rows=\"10\" " + "cols=\"80\" " + "name=\"" + associationType.qualifiedName() + "\" >" + value + "</textarea></td></tr>");
}
out.println("</table></fieldset>\n");
out.println("<fieldset><legend>NamedAssociations</legend>\n<table>");
for (AssociationDescriptor associationType : descriptor.state().namedAssociations()) {
NamedAssociationState identities = entity.namedAssociationValueOf(associationType.qualifiedName());
String value = "";
for (String name : identities) {
value += name + "\n" + identities.get(name).identity() + "\n";
}
out.println("<tr><td>" + "<label for=\"" + associationType.qualifiedName() + "\" >" + associationType.qualifiedName().name() + "</label></td>\n" + "<td><textarea " + "rows=\"10\" " + "cols=\"80\" " + "name=\"" + associationType.qualifiedName() + "\" >" + value + "</textarea></td></tr>");
}
out.println("</table></fieldset>\n");
out.println("<input type=\"submit\" value=\"Update\"/></form>\n");
out.println("</body></html>\n");
}
};
}
use of org.restlet.representation.WriterRepresentation in project qi4j-sdk by Qi4j.
the class EntityResource method representRdfXml.
private Representation representRdfXml(final EntityState entity) throws ResourceException {
Representation representation = new WriterRepresentation(MediaType.APPLICATION_RDF_XML) {
@Override
public void write(Writer writer) throws IOException {
try {
Iterable<Statement> statements = entitySerializer.serialize(entity);
new RdfXmlSerializer().serialize(statements, writer);
} catch (RDFHandlerException e) {
throw new IOException(e);
}
}
};
representation.setCharacterSet(CharacterSet.UTF_8);
return representation;
}
use of org.restlet.representation.WriterRepresentation 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 );
}
*/
}
Aggregations