Search in sources :

Example 51 with ResourceException

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();
}
Also used : PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) EntityStoreUnitOfWork(org.qi4j.spi.entitystore.EntityStoreUnitOfWork) ValueSerializationException(org.qi4j.api.value.ValueSerializationException) JSONEntityState(org.qi4j.spi.entitystore.helpers.JSONEntityState) EntityState(org.qi4j.spi.entity.EntityState) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException) ManyAssociationState(org.qi4j.spi.entity.ManyAssociationState) EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) ConcurrentEntityStateModificationException(org.qi4j.spi.entitystore.ConcurrentEntityStateModificationException) EntityReference(org.qi4j.api.entity.EntityReference) ResourceException(org.restlet.resource.ResourceException) Usecase(org.qi4j.api.usecase.Usecase)

Example 52 with ResourceException

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;
}
Also used : EntityReference(org.qi4j.api.entity.EntityReference) ResourceException(org.restlet.resource.ResourceException) JSONEntityState(org.qi4j.spi.entitystore.helpers.JSONEntityState) EntityState(org.qi4j.spi.entity.EntityState) EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException)

Example 53 with ResourceException

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();
    }
}
Also used : UnitOfWork(org.qi4j.api.unitofwork.UnitOfWork) Reference(org.restlet.data.Reference) Uniform(org.restlet.Uniform) StringRepresentation(org.restlet.representation.StringRepresentation) Representation(org.restlet.representation.Representation) ConcurrentEntityModificationException(org.qi4j.api.unitofwork.ConcurrentEntityModificationException) ResourceException(org.restlet.resource.ResourceException) Usecase(org.qi4j.api.usecase.Usecase)

Example 54 with ResourceException

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);
    }
}
Also used : WriterRepresentation(org.restlet.representation.WriterRepresentation) EntityFinderException(org.qi4j.spi.query.EntityFinderException) EntityReference(org.qi4j.api.entity.EntityReference) ResourceException(org.restlet.resource.ResourceException) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Example 55 with ResourceException

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;
}
Also used : HashMap(java.util.HashMap) TemplateException(freemarker.template.TemplateException) ValueDescriptor(org.qi4j.api.value.ValueDescriptor) Representation(org.restlet.representation.Representation) WriterRepresentation(org.restlet.representation.WriterRepresentation) IOException(java.io.IOException) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) ResourceException(org.restlet.resource.ResourceException) Template(freemarker.template.Template) WriterRepresentation(org.restlet.representation.WriterRepresentation) MediaType(org.restlet.data.MediaType) Writer(java.io.Writer)

Aggregations

ResourceException (org.restlet.resource.ResourceException)70 Representation (org.restlet.representation.Representation)20 PermissionException (org.vcell.util.PermissionException)20 VCellApiApplication (org.vcell.rest.VCellApiApplication)18 ObjectNotFoundException (org.vcell.util.ObjectNotFoundException)15 IOException (java.io.IOException)13 StringRepresentation (org.restlet.representation.StringRepresentation)12 ArrayList (java.util.ArrayList)10 Reference (org.restlet.data.Reference)8 BioModel (cbit.vcell.biomodel.BioModel)7 Writer (java.io.Writer)7 HashMap (java.util.HashMap)7 JSONObject (org.json.JSONObject)7 WriterRepresentation (org.restlet.representation.WriterRepresentation)7 XMLSource (cbit.vcell.xml.XMLSource)6 Response (org.restlet.Response)6 User (org.vcell.util.document.User)6 EntitlementException (com.sun.identity.entitlement.EntitlementException)4 EntityReference (org.qi4j.api.entity.EntityReference)4 EntityTypeNotFoundException (org.qi4j.api.unitofwork.EntityTypeNotFoundException)4