Search in sources :

Example 11 with ResourceWithMetadata

use of org.alfresco.rest.framework.core.ResourceWithMetadata in project alfresco-remote-api by Alfresco.

the class AbstractResourceWebScript method execute.

@SuppressWarnings("rawtypes")
@Override
public void execute(final Api api, final WebScriptRequest req, final WebScriptResponse res) throws IOException {
    try {
        final Map<String, Object> respons = new HashMap<String, Object>();
        final Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
        final ResourceWithMetadata resource = locator.locateResource(api, templateVars, httpMethod);
        final Params params = paramsExtractor.extractParams(resource.getMetaData(), req);
        final boolean isReadOnly = HttpMethod.GET == httpMethod;
        // This execution usually takes place in a Retrying Transaction (see subclasses)
        final Object toSerialize = execute(resource, params, res, isReadOnly);
        // Outside the transaction.
        if (toSerialize != null) {
            if (toSerialize instanceof BinaryResource) {
                // TODO review (experimental) - can we move earlier & wrap complete execute ? Also for QuickShare (in MT/Cloud) needs to be tenant for the nodeRef (TBC).
                boolean noAuth = false;
                if (BinaryResourceAction.Read.class.isAssignableFrom(resource.getResource().getClass())) {
                    noAuth = resource.getMetaData().isNoAuth(BinaryResourceAction.Read.class);
                } else if (RelationshipResourceBinaryAction.Read.class.isAssignableFrom(resource.getResource().getClass())) {
                    noAuth = resource.getMetaData().isNoAuth(RelationshipResourceBinaryAction.Read.class);
                } else {
                    logger.warn("Unexpected");
                }
                if (noAuth) {
                    String networkTenantDomain = TenantUtil.getCurrentDomain();
                    TenantUtil.runAsSystemTenant(new TenantUtil.TenantRunAsWork<Void>() {

                        public Void doWork() throws Exception {
                            streamResponse(req, res, (BinaryResource) toSerialize);
                            return null;
                        }
                    }, networkTenantDomain);
                } else {
                    streamResponse(req, res, (BinaryResource) toSerialize);
                }
            } else {
                renderJsonResponse(res, toSerialize, assistant.getJsonHelper());
            }
        }
    } catch (AlfrescoRuntimeException | ApiException | WebScriptException xception) {
        renderException(xception, res, assistant);
    } catch (RuntimeException runtimeException) {
        renderException(runtimeException, res, assistant);
    }
}
Also used : HashMap(java.util.HashMap) Params(org.alfresco.rest.framework.resource.parameters.Params) BinaryResourceAction(org.alfresco.rest.framework.resource.actions.interfaces.BinaryResourceAction) RelationshipResourceBinaryAction(org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceBinaryAction) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException) IOException(java.io.IOException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) FileBinaryResource(org.alfresco.rest.framework.resource.content.FileBinaryResource) NodeBinaryResource(org.alfresco.rest.framework.resource.content.NodeBinaryResource) BinaryResource(org.alfresco.rest.framework.resource.content.BinaryResource) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) TenantUtil(org.alfresco.repo.tenant.TenantUtil) ResourceWithMetadata(org.alfresco.rest.framework.core.ResourceWithMetadata) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException)

Example 12 with ResourceWithMetadata

use of org.alfresco.rest.framework.core.ResourceWithMetadata in project alfresco-remote-api by Alfresco.

the class ResourceWebScriptHelper method processAdditionsToTheResponse.

/**
 * Looks at the object passed in and recursively expands any @EmbeddedEntityResource annotations or related relationship.
 * {@link org.alfresco.rest.framework.resource.EmbeddedEntityResource EmbeddedEntityResource} is expanded by calling the ReadById method for this entity.
 *
 * Either returns a ExecutionResult object or a CollectionWithPagingInfo containing a collection of ExecutionResult objects.
 *
 * @param api Api
 * @param entityCollectionName String
 * @param params  Params
 * @param objectToWrap Object
 * @return Object - Either ExecutionResult or CollectionWithPagingInfo<ExecutionResult>
 */
public Object processAdditionsToTheResponse(WebScriptResponse res, Api api, String entityCollectionName, Params params, Object objectToWrap) {
    PropertyCheck.mandatory(this, null, params);
    if (objectToWrap == null)
        return null;
    if (objectToWrap instanceof CollectionWithPagingInfo<?>) {
        CollectionWithPagingInfo<?> collectionToWrap = (CollectionWithPagingInfo<?>) objectToWrap;
        Object sourceEntity = executeIncludedSource(api, params, entityCollectionName, collectionToWrap);
        Collection<Object> resultCollection = new ArrayList(collectionToWrap.getCollection().size());
        if (!collectionToWrap.getCollection().isEmpty()) {
            for (Object obj : collectionToWrap.getCollection()) {
                resultCollection.add(processAdditionsToTheResponse(res, api, entityCollectionName, params, obj));
            }
        }
        return CollectionWithPagingInfo.asPaged(collectionToWrap.getPaging(), resultCollection, collectionToWrap.hasMoreItems(), collectionToWrap.getTotalItems(), sourceEntity, collectionToWrap.getContext());
    } else {
        if (BeanUtils.isSimpleProperty(objectToWrap.getClass()) || objectToWrap instanceof Collection) {
            // Simple property or Collection that can't be embedded so just return it.
            return objectToWrap;
        }
        final ExecutionResult execRes = new ExecutionResult(objectToWrap, params.getFilter());
        Map<String, Pair<String, Method>> embeddded = ResourceInspector.findEmbeddedResources(objectToWrap.getClass());
        if (embeddded != null && !embeddded.isEmpty()) {
            Map<String, Object> results = executeEmbeddedResources(api, params, objectToWrap, embeddded);
            execRes.addEmbedded(results);
        }
        if (params.getRelationsFilter() != null && !params.getRelationsFilter().isEmpty()) {
            Map<String, ResourceWithMetadata> relationshipResources = locator.locateRelationResource(api, entityCollectionName, params.getRelationsFilter().keySet(), HttpMethod.GET);
            String uniqueEntityId = ResourceInspector.findUniqueId(objectToWrap);
            Map<String, Object> relatedResources = executeRelatedResources(api, params, relationshipResources, uniqueEntityId);
            execRes.addRelated(relatedResources);
        }
        return execRes;
    }
}
Also used : ArrayList(java.util.ArrayList) CollectionWithPagingInfo(org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo) ExecutionResult(org.alfresco.rest.framework.jacksonextensions.ExecutionResult) Collection(java.util.Collection) ResourceWithMetadata(org.alfresco.rest.framework.core.ResourceWithMetadata) Pair(org.alfresco.util.Pair)

Example 13 with ResourceWithMetadata

use of org.alfresco.rest.framework.core.ResourceWithMetadata in project alfresco-remote-api by Alfresco.

the class InfoWebScriptGet method execute.

@Override
public void execute(final Api api, WebScriptRequest req, WebScriptResponse res) throws IOException {
    ResourceDictionary resourceDic = lookupDictionary.getDictionary();
    final Map<String, ResourceWithMetadata> apiResources = resourceDic.getAllResources().get(api);
    if (apiResources == null) {
        throw new InvalidArgumentException(InvalidArgumentException.DEFAULT_INVALID_API);
    }
    assistant.getJsonHelper().withWriter(res.getOutputStream(), new Writer() {

        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper) throws JsonGenerationException, JsonMappingException, IOException {
            List<ExecutionResult> entities = new ArrayList<ExecutionResult>();
            for (ResourceWithMetadata resource : apiResources.values()) {
                entities.add(new ExecutionResult(resource.getMetaData(), null));
            }
            Collections.sort(entities, new Comparator<ExecutionResult>() {

                public int compare(ExecutionResult r1, ExecutionResult r2) {
                    return ((ResourceMetadata) r1.getRoot()).getUniqueId().compareTo(((ResourceMetadata) r2.getRoot()).getUniqueId());
                }
            });
            objectMapper.writeValue(generator, CollectionWithPagingInfo.asPaged(Paging.DEFAULT, entities));
        }
    });
}
Also used : ResourceDictionary(org.alfresco.rest.framework.core.ResourceDictionary) ExecutionResult(org.alfresco.rest.framework.jacksonextensions.ExecutionResult) IOException(java.io.IOException) Comparator(java.util.Comparator) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ArrayList(java.util.ArrayList) List(java.util.List) JsonGenerationException(com.fasterxml.jackson.core.JsonGenerationException) ResourceWithMetadata(org.alfresco.rest.framework.core.ResourceWithMetadata) Writer(org.alfresco.rest.framework.jacksonextensions.JacksonHelper.Writer) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 14 with ResourceWithMetadata

use of org.alfresco.rest.framework.core.ResourceWithMetadata in project alfresco-remote-api by Alfresco.

the class ExecutionTests method testInvokeDelete.

@Test
public void testInvokeDelete() throws IOException {
    ResourceWithMetadata grassResource = locator.locateEntityResource(api, "grass", HttpMethod.DELETE);
    AbstractResourceWebScript executor = getExecutor("executorOfDelete");
    Object result = executor.execute(grassResource, Params.valueOf("4", null, mock(WebScriptRequest.class)), mock(WebScriptResponse.class), false);
    assertNull(result);
    ResourceWithMetadata cowResource = locator.locateEntityResource(api, "cow", HttpMethod.DELETE);
    result = executor.execute(cowResource, Params.valueOf("4", null, mock(WebScriptRequest.class)), mock(WebScriptResponse.class), false);
    assertNull(result);
    cowResource = locator.locateRelationResource(api, "cow", "photo", HttpMethod.DELETE);
    result = executor.execute(cowResource, Params.valueOf("4", null, mock(WebScriptRequest.class)), mock(WebScriptResponse.class), false);
    assertNull(result);
    ResourceWithMetadata resource = locator.locateRelationResource(api, "sheep", "blacksheep", HttpMethod.DELETE);
    result = executor.execute(resource, Params.valueOf("4", null, mock(WebScriptRequest.class)), mock(WebScriptResponse.class), false);
    assertNull(result);
    ResourceWithMetadata calf = locator.locateRelationResource(api, "cow", "calf", HttpMethod.DELETE);
    result = executor.execute(calf, Params.valueOf("4", null, mock(WebScriptRequest.class)), mock(WebScriptResponse.class), false);
    assertNull(result);
    ResourceWithMetadata flockEntityResource = locator.locateRelationResource(api3, "flock", "photo", HttpMethod.DELETE);
    result = executor.execute(flockEntityResource, Params.valueOf("4", null, mock(WebScriptRequest.class)), mock(WebScriptResponse.class), false);
    assertNull(result);
    calf = locator.locateRelationResource(api, "cow/{entityId}/calf", "photo", HttpMethod.DELETE);
    result = executor.execute(calf, Params.valueOf("4", null, mock(WebScriptRequest.class)), mock(WebScriptResponse.class), false);
    assertNull(result);
    ResourceWithMetadata goatDelete = locator.locateRelationResource(api3, "goat/{entityId}/herd", "content", HttpMethod.DELETE);
    result = executor.execute(goatDelete, Params.valueOf("4", "56", mock(WebScriptRequest.class)), mock(WebScriptResponse.class), false);
    assertNull(result);
}
Also used : WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) AbstractResourceWebScript(org.alfresco.rest.framework.webscripts.AbstractResourceWebScript) WebScriptResponse(org.springframework.extensions.webscripts.WebScriptResponse) ResourceWithMetadata(org.alfresco.rest.framework.core.ResourceWithMetadata) Test(org.junit.Test)

Example 15 with ResourceWithMetadata

use of org.alfresco.rest.framework.core.ResourceWithMetadata in project alfresco-remote-api by Alfresco.

the class ExecutionTests method testInvokeGet.

@Test
public void testInvokeGet() throws IOException {
    ResourceWithMetadata entityResource = locator.locateEntityResource(api, "sheep", HttpMethod.GET);
    AbstractResourceWebScript executor = getExecutor();
    Object result = executor.execute(entityResource, Params.valueOf((String) null, null, mock(WebScriptRequest.class)), mock(WebScriptResponse.class), true);
    assertNotNull(result);
    WebScriptResponse response = mock(WebScriptResponse.class);
    entityResource = locator.locateEntityResource(api, "cow", HttpMethod.GET);
    result = executor.execute(entityResource, Params.valueOf((String) null, null, mock(WebScriptRequest.class)), response, true);
    assertNotNull(result);
    verify(response, times(1)).setCache((Cache) ResponseWriter.CACHE_NEVER);
    response = mock(WebScriptResponse.class);
    result = executor.execute(entityResource, Params.valueOf("543", null, mock(WebScriptRequest.class)), response, true);
    assertNotNull(result);
    verify(response, times(1)).setCache((Cache) CowEntityResource.CACHE_COW);
    ResourceWithMetadata baa = locator.locateRelationResource(api, "sheep", "baaahh", HttpMethod.GET);
    result = executor.execute(baa, Params.valueOf("4", null, mock(WebScriptRequest.class)), mock(WebScriptResponse.class), true);
    assertNotNull(result);
    executor.execute(baa, Params.valueOf("4", "45", mock(WebScriptRequest.class)), mock(WebScriptResponse.class), true);
    assertNotNull(result);
    ResourceWithMetadata cowResource = locator.locateRelationResource(api, "cow", "photo", HttpMethod.GET);
    result = executor.execute(cowResource, Params.valueOf("4", null, mock(WebScriptRequest.class)), mock(WebScriptResponse.class), true);
    assertNull(result);
    ResourceWithMetadata calf = locator.locateRelationResource(api, "cow", "calf", HttpMethod.GET);
    result = executor.execute(calf, Params.valueOf("4", null, mock(WebScriptRequest.class)), mock(WebScriptResponse.class), true);
    assertNotNull(result);
    executor.execute(calf, Params.valueOf("4", "45", mock(WebScriptRequest.class)), mock(WebScriptResponse.class), true);
    assertNotNull(result);
    calf = locator.locateRelationResource(api, "cow/{entityId}/calf", "photo", HttpMethod.GET);
    executor.execute(calf, Params.valueOf("4", "45", mock(WebScriptRequest.class)), mock(WebScriptResponse.class), true);
    assertNotNull(result);
    ResourceWithMetadata baaPhoto = locator.locateRelationResource(api, "sheep/{entityId}/baaahh", "photo", HttpMethod.GET);
    executor.execute(baaPhoto, Params.valueOf("4", "45", mock(WebScriptRequest.class)), mock(WebScriptResponse.class), true);
    assertNotNull(result);
}
Also used : WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) AbstractResourceWebScript(org.alfresco.rest.framework.webscripts.AbstractResourceWebScript) WebScriptResponse(org.springframework.extensions.webscripts.WebScriptResponse) Matchers.anyString(org.mockito.Matchers.anyString) ResourceWithMetadata(org.alfresco.rest.framework.core.ResourceWithMetadata) Test(org.junit.Test)

Aggregations

ResourceWithMetadata (org.alfresco.rest.framework.core.ResourceWithMetadata)27 Test (org.junit.Test)21 HashMap (java.util.HashMap)10 Api (org.alfresco.rest.framework.Api)7 WebScriptResponse (org.springframework.extensions.webscripts.WebScriptResponse)7 AbstractResourceWebScript (org.alfresco.rest.framework.webscripts.AbstractResourceWebScript)5 NotFoundException (org.alfresco.rest.framework.core.exceptions.NotFoundException)4 UnsupportedResourceOperationException (org.alfresco.rest.framework.core.exceptions.UnsupportedResourceOperationException)4 Read (org.alfresco.rest.framework.resource.actions.interfaces.EntityResourceAction.Read)4 RelationshipResourceAction (org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction)4 WebScriptRequest (org.springframework.extensions.webscripts.WebScriptRequest)4 ResourceDictionary (org.alfresco.rest.framework.core.ResourceDictionary)3 EntityResourceAction (org.alfresco.rest.framework.resource.actions.interfaces.EntityResourceAction)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)2 ExecutionResult (org.alfresco.rest.framework.jacksonextensions.ExecutionResult)2 BinaryResourceAction (org.alfresco.rest.framework.resource.actions.interfaces.BinaryResourceAction)2 ReadById (org.alfresco.rest.framework.resource.actions.interfaces.EntityResourceAction.ReadById)2 RelationshipResourceBinaryAction (org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceBinaryAction)2