Search in sources :

Example 31 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 32 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.isEmpty()) {
                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
            }
        }
        for (AssociationDescriptor associationType : descriptor.state().namedAssociations()) {
            String newStringAssociation = form.getFirstValue(associationType.qualifiedName().name());
            NamedAssociationState namedAssociation = entity.namedAssociationValueOf(associationType.qualifiedName());
            if (newStringAssociation == null) {
                // Remove "left-overs"
                for (String name : namedAssociation) {
                    namedAssociation.remove(name);
                }
                continue;
            }
            Set<String> names = new HashSet<>();
            BufferedReader bufferedReader = new BufferedReader(new StringReader(newStringAssociation));
            String line;
            try {
                while ((line = bufferedReader.readLine()) != null) {
                    String name = line;
                    line = bufferedReader.readLine();
                    if (line == null) {
                        break;
                    }
                    String identity = line;
                    EntityReference reference = new EntityReference(identity);
                    try {
                        unitOfWork.entityStateOf(reference);
                        namedAssociation.remove(name);
                        namedAssociation.put(name, reference);
                        names.add(name);
                    } catch (EntityNotFoundException e) {
                    // Ignore this entity - doesn't exist
                    }
                }
                // Remove "left-overs"
                for (String assocName : Iterables.toList(namedAssociation)) {
                    if (!names.contains(assocName)) {
                        namedAssociation.remove(assocName);
                    }
                }
            } catch (IOException e) {
            // Ignore
            }
        }
    } catch (ValueSerializationException | 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) Form(org.restlet.data.Form) NamedAssociationState(org.qi4j.spi.entity.NamedAssociationState) ValueSerializationException(org.qi4j.api.value.ValueSerializationException) EntityState(org.qi4j.spi.entity.EntityState) JSONEntityState(org.qi4j.spi.entitystore.helpers.JSONEntityState) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException) IOException(java.io.IOException) ManyAssociationState(org.qi4j.spi.entity.ManyAssociationState) EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) ConcurrentEntityStateModificationException(org.qi4j.spi.entitystore.ConcurrentEntityStateModificationException) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) EntityReference(org.qi4j.api.entity.EntityReference) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) ResourceException(org.restlet.resource.ResourceException) Usecase(org.qi4j.api.usecase.Usecase) HashSet(java.util.HashSet)

Example 33 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) EntityState(org.qi4j.spi.entity.EntityState) JSONEntityState(org.qi4j.spi.entitystore.helpers.JSONEntityState) EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException)

Example 34 with ResourceException

use of org.restlet.resource.ResourceException in project qi4j-sdk by Qi4j.

the class ContextResource method handleCommand.

private void handleCommand(String segment) {
    Request request = Request.getCurrent();
    Response response = Response.getCurrent();
    // Check if this is a request to show the form for this command
    Method interactionMethod = resourceMethodCommands.get(segment);
    if (shouldShowCommandForm(interactionMethod)) {
        // Show form
        // TODO This should check if method is idempotent
        response.getAllowedMethods().add(org.restlet.data.Method.POST);
        try {
            // Check if there is a query with this name - if so invoke it
            Method queryMethod = resourceMethodQueries.get(segment);
            if (queryMethod != null) {
                result(queryMethod.invoke(this));
            } else {
                request.setMethod(org.restlet.data.Method.POST);
                response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY);
                result(formForMethod(interactionMethod));
            }
        } 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(interactionMethod, current(), module)) {
            throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
        }
        // Create argument
        Object[] arguments = requestReader.readRequest(Request.getCurrent(), interactionMethod);
        Request.getCurrent().getAttributes().put(ARGUMENTS, arguments);
        // Invoke method
        try {
            Object result = interactionMethod.invoke(this, arguments);
            if (result != null) {
                if (result instanceof Representation) {
                    response.setEntity((Representation) result);
                } else {
                    result(convert(result));
                }
            }
        } catch (Throwable e) {
            handleException(response, e);
        }
    }
}
Also used : Response(org.restlet.Response) Request(org.restlet.Request) ResourceException(org.restlet.resource.ResourceException) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) StringRepresentation(org.restlet.representation.StringRepresentation) Representation(org.restlet.representation.Representation) Method(java.lang.reflect.Method) EntityTypeNotFoundException(org.qi4j.api.unitofwork.EntityTypeNotFoundException) ResourceException(org.restlet.resource.ResourceException) InvocationTargetException(java.lang.reflect.InvocationTargetException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchEntityException(org.qi4j.api.unitofwork.NoSuchEntityException) ConstraintViolationException(org.qi4j.api.constraint.ConstraintViolationException)

Example 35 with ResourceException

use of org.restlet.resource.ResourceException in project qi4j-sdk by Qi4j.

the class ContextResource method handleException.

private void handleException(Response response, Throwable ex) {
    while (ex instanceof InvocationTargetException) {
        ex = ex.getCause();
    }
    try {
        throw ex;
    } catch (ResourceException e) {
        // IAE (or subclasses) are considered client faults
        response.setEntity(new StringRepresentation(e.getMessage()));
        response.setStatus(e.getStatus());
    } catch (ConstraintViolationException e) {
        try {
            ConstraintViolationMessages cvm = new ConstraintViolationMessages();
            // CVE are considered client faults
            String messages = "";
            Locale locale = ObjectSelection.type(Locale.class);
            for (ConstraintViolation constraintViolation : e.constraintViolations()) {
                if (!messages.isEmpty()) {
                    messages += "\n";
                }
                messages += cvm.getMessage(constraintViolation, locale);
            }
            response.setEntity(new StringRepresentation(messages));
            response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY);
        } catch (Exception e1) {
            response.setEntity(new StringRepresentation(e.getMessage()));
            response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY);
        }
    } catch (IllegalArgumentException e) {
        // IAE (or subclasses) are considered client faults
        response.setEntity(new StringRepresentation(e.getMessage()));
        response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY);
    } catch (RuntimeException e) {
        // RuntimeExceptions are considered server faults
        LoggerFactory.getLogger(getClass()).warn("Exception thrown during processing", e);
        response.setEntity(new StringRepresentation(e.getMessage()));
        response.setStatus(Status.SERVER_ERROR_INTERNAL);
    } catch (Exception e) {
        // Checked exceptions are considered client faults
        String s = e.getMessage();
        if (s == null) {
            s = e.getClass().getSimpleName();
        }
        response.setEntity(new StringRepresentation(s));
        response.setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY);
    } catch (Throwable e) {
        // Anything else are considered server faults
        LoggerFactory.getLogger(getClass()).error("Exception thrown during processing", e);
        response.setEntity(new StringRepresentation(e.getMessage()));
        response.setStatus(Status.SERVER_ERROR_INTERNAL);
    }
}
Also used : Locale(java.util.Locale) StringRepresentation(org.restlet.representation.StringRepresentation) ConstraintViolation(org.qi4j.api.constraint.ConstraintViolation) ConstraintViolationException(org.qi4j.api.constraint.ConstraintViolationException) ConstraintViolationMessages(org.qi4j.library.rest.server.restlet.ConstraintViolationMessages) ResourceException(org.restlet.resource.ResourceException) InvocationTargetException(java.lang.reflect.InvocationTargetException) EntityTypeNotFoundException(org.qi4j.api.unitofwork.EntityTypeNotFoundException) ResourceException(org.restlet.resource.ResourceException) InvocationTargetException(java.lang.reflect.InvocationTargetException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchEntityException(org.qi4j.api.unitofwork.NoSuchEntityException) ConstraintViolationException(org.qi4j.api.constraint.ConstraintViolationException)

Aggregations

ResourceException (org.restlet.resource.ResourceException)60 Representation (org.restlet.representation.Representation)19 VCellApiApplication (org.vcell.rest.VCellApiApplication)16 PermissionException (org.vcell.util.PermissionException)16 IOException (java.io.IOException)13 ObjectNotFoundException (org.vcell.util.ObjectNotFoundException)11 ArrayList (java.util.ArrayList)10 StringRepresentation (org.restlet.representation.StringRepresentation)9 Reference (org.restlet.data.Reference)8 Writer (java.io.Writer)7 WriterRepresentation (org.restlet.representation.WriterRepresentation)7 JSONObject (org.json.JSONObject)6 Response (org.restlet.Response)6 User (org.vcell.util.document.User)6 HashMap (java.util.HashMap)5 JsonRepresentation (org.restlet.ext.json.JsonRepresentation)5 EmptyRepresentation (org.restlet.representation.EmptyRepresentation)5 JSONException (org.json.JSONException)4 EntityReference (org.qi4j.api.entity.EntityReference)4 EntityTypeNotFoundException (org.qi4j.api.unitofwork.EntityTypeNotFoundException)4