use of org.restlet.resource.ResourceException in project qi4j-sdk by Qi4j.
the class EntityResource method post.
@Override
public Representation post(Representation entityRepresentation, Variant variant) throws ResourceException {
Usecase usecase = UsecaseBuilder.newUsecase("Update entity");
EntityStoreUnitOfWork unitOfWork = entityStore.newUnitOfWork(usecase, module, System.currentTimeMillis());
EntityState entity = getEntityState(unitOfWork);
Form form = new Form(entityRepresentation);
try {
final EntityDescriptor descriptor = entity.entityDescriptor();
// Parse JSON into properties
for (PropertyDescriptor persistentProperty : descriptor.state().properties()) {
if (!persistentProperty.isImmutable()) {
String formValue = form.getFirstValue(persistentProperty.qualifiedName().name(), null);
if (formValue == null) {
entity.setPropertyValue(persistentProperty.qualifiedName(), null);
} else {
entity.setPropertyValue(persistentProperty.qualifiedName(), valueSerialization.deserialize(persistentProperty.valueType(), formValue));
}
}
}
for (AssociationDescriptor associationType : descriptor.state().associations()) {
String newStringAssociation = form.getFirstValue(associationType.qualifiedName().name());
if (newStringAssociation == null || newStringAssociation.equals("")) {
entity.setAssociationValue(associationType.qualifiedName(), null);
} else {
entity.setAssociationValue(associationType.qualifiedName(), EntityReference.parseEntityReference(newStringAssociation));
}
}
for (AssociationDescriptor associationType : descriptor.state().manyAssociations()) {
String newStringAssociation = form.getFirstValue(associationType.qualifiedName().name());
ManyAssociationState manyAssociation = entity.manyAssociationValueOf(associationType.qualifiedName());
if (newStringAssociation == null) {
// Remove "left-overs"
for (EntityReference entityReference : manyAssociation) {
manyAssociation.remove(entityReference);
}
continue;
}
BufferedReader bufferedReader = new BufferedReader(new StringReader(newStringAssociation));
String identity;
try {
// Synchronize old and new association
int index = 0;
while ((identity = bufferedReader.readLine()) != null) {
EntityReference reference = new EntityReference(identity);
if (manyAssociation.count() < index && manyAssociation.get(index).equals(reference)) {
continue;
}
try {
unitOfWork.entityStateOf(reference);
manyAssociation.remove(reference);
manyAssociation.add(index++, reference);
} catch (EntityNotFoundException e) {
// Ignore this entity - doesn't exist
}
}
// Remove "left-overs"
while (manyAssociation.count() > index) {
manyAssociation.remove(manyAssociation.get(index));
}
} catch (IOException e) {
// Ignore
}
}
} catch (ValueSerializationException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
} catch (IllegalArgumentException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
try {
unitOfWork.applyChanges().commit();
} catch (ConcurrentEntityStateModificationException e) {
throw new ResourceException(Status.CLIENT_ERROR_CONFLICT);
} catch (EntityNotFoundException e) {
throw new ResourceException(Status.CLIENT_ERROR_GONE);
}
getResponse().setStatus(Status.SUCCESS_RESET_CONTENT);
return new EmptyRepresentation();
}
use of org.restlet.resource.ResourceException in project qi4j-sdk by Qi4j.
the class EntityResource method getEntityState.
private EntityState getEntityState(EntityStoreUnitOfWork unitOfWork) throws ResourceException {
EntityState entityState;
try {
EntityReference entityReference = EntityReference.parseEntityReference(identity);
entityState = unitOfWork.entityStateOf(entityReference);
} catch (EntityNotFoundException e) {
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
}
return entityState;
}
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 EntitiesResource method representRdf.
private Representation representRdf() throws ResourceException {
try {
final Iterable<EntityReference> query = entityFinder.findEntities(EntityComposite.class, null, null, null, null, Collections.<String, Object>emptyMap());
WriterRepresentation representation = new WriterRepresentation(MediaType.APPLICATION_RDF_XML) {
@Override
public void write(Writer writer) throws IOException {
PrintWriter out = new PrintWriter(writer);
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<rdf:RDF\n" + "\txmlns=\"urn:qi4j:\"\n" + "\txmlns:qi4j=\"http://www.qi4j.org/rdf/model/1.0/\"\n" + "\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" + "\txmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">");
for (EntityReference qualifiedIdentity : query) {
out.println("<qi4j:entity rdf:about=\"" + getRequest().getResourceRef().getPath() + "/" + qualifiedIdentity.identity() + ".rdf\"/>");
}
out.println("</rdf:RDF>");
}
};
representation.setCharacterSet(CharacterSet.UTF_8);
return representation;
} catch (EntityFinderException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
}
use of org.restlet.resource.ResourceException in project qi4j-sdk by Qi4j.
the class ResourceTemplateResponseWriter method writeResponse.
@Override
public boolean writeResponse(final Object result, final Response response) throws ResourceException {
MediaType type = getVariant(response.getRequest(), ENGLISH, supportedMediaTypes).getMediaType();
if (type != null) {
// Try to find template for this specific resource
StringBuilder templateBuilder = (StringBuilder) response.getRequest().getAttributes().get("template");
String templateName = templateBuilder.toString();
if (result instanceof ValueDescriptor) {
templateName += "_form";
}
final String extension = metadataService.getExtension(type);
templateName += "." + extension;
// Have we failed on this one before, then don't try again
if (skip.contains(templateName)) {
return false;
}
try {
final Template template = cfg.getTemplate(templateName);
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 {
template.process(context, writer);
} catch (TemplateException e) {
throw new IOException(e);
}
}
};
response.setEntity(rep);
return true;
} catch (Exception e) {
skip.add(templateName);
// Ignore
}
}
return false;
}
Aggregations