Search in sources :

Example 6 with ApiException

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

the class RenditionsImpl method getContentNoValidation.

@Override
public BinaryResource getContentNoValidation(NodeRef sourceNodeRef, String renditionId, Parameters parameters) {
    NodeRef renditionNodeRef = getRenditionByName(sourceNodeRef, renditionId, parameters);
    // By default set attachment header (with rendition Id) unless attachment=false
    boolean attach = true;
    String attachment = parameters.getParameter("attachment");
    if (attachment != null) {
        attach = Boolean.valueOf(attachment);
    }
    final String attachFileName = (attach ? renditionId : null);
    if (renditionNodeRef == null) {
        boolean isPlaceholder = Boolean.valueOf(parameters.getParameter("placeholder"));
        if (!isPlaceholder) {
            throw new NotFoundException("Thumbnail was not found for [" + renditionId + ']');
        }
        String sourceNodeMimeType = null;
        try {
            sourceNodeMimeType = (sourceNodeRef != null ? getMimeType(sourceNodeRef) : null);
        } catch (InvalidArgumentException e) {
        // No content for node, e.g. ASSOC_AVATAR rather than ASSOC_PREFERENCE_IMAGE
        }
        // resource based on the content's mimeType and rendition id
        String phPath = scriptThumbnailService.getMimeAwarePlaceHolderResourcePath(renditionId, sourceNodeMimeType);
        if (phPath == null) {
            // 404 since no thumbnail was found
            throw new NotFoundException("Thumbnail was not found and no placeholder resource available for [" + renditionId + ']');
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Retrieving content from resource path [" + phPath + ']');
            }
            // get extension of resource
            String ext = "";
            int extIndex = phPath.lastIndexOf('.');
            if (extIndex != -1) {
                ext = phPath.substring(extIndex);
            }
            try {
                final String resourcePath = "classpath:" + phPath;
                InputStream inputStream = resourceLoader.getResource(resourcePath).getInputStream();
                // create temporary file
                File file = TempFileProvider.createTempFile(inputStream, "RenditionsApi-", ext);
                return new FileBinaryResource(file, attachFileName);
            } catch (Exception ex) {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("Couldn't load the placeholder." + ex.getMessage());
                }
                throw new ApiException("Couldn't load the placeholder.");
            }
        }
    }
    Map<QName, Serializable> nodeProps = nodeService.getProperties(renditionNodeRef);
    ContentData contentData = (ContentData) nodeProps.get(ContentModel.PROP_CONTENT);
    Date modified = (Date) nodeProps.get(ContentModel.PROP_MODIFIED);
    org.alfresco.rest.framework.resource.content.ContentInfo contentInfo = null;
    if (contentData != null) {
        contentInfo = new ContentInfoImpl(contentData.getMimetype(), contentData.getEncoding(), contentData.getSize(), contentData.getLocale());
    }
    // add cache settings
    CacheDirective cacheDirective = new CacheDirective.Builder().setNeverCache(false).setMustRevalidate(false).setLastModified(modified).setETag(modified != null ? Long.toString(modified.getTime()) : null).setMaxAge(// one year (in seconds)
    Long.valueOf(31536000)).build();
    return new NodeBinaryResource(renditionNodeRef, ContentModel.PROP_CONTENT, contentInfo, attachFileName, cacheDirective);
}
Also used : Serializable(java.io.Serializable) InputStream(java.io.InputStream) QName(org.alfresco.service.namespace.QName) NotFoundException(org.alfresco.rest.framework.core.exceptions.NotFoundException) FileBinaryResource(org.alfresco.rest.framework.resource.content.FileBinaryResource) NotFoundException(org.alfresco.rest.framework.core.exceptions.NotFoundException) ConstraintViolatedException(org.alfresco.rest.framework.core.exceptions.ConstraintViolatedException) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException) DisabledServiceException(org.alfresco.rest.framework.core.exceptions.DisabledServiceException) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) Date(java.util.Date) NodeBinaryResource(org.alfresco.rest.framework.resource.content.NodeBinaryResource) NodeRef(org.alfresco.service.cmr.repository.NodeRef) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) ContentData(org.alfresco.service.cmr.repository.ContentData) CacheDirective(org.alfresco.rest.framework.resource.content.CacheDirective) ContentInfoImpl(org.alfresco.rest.framework.resource.content.ContentInfoImpl) File(java.io.File) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException)

Example 7 with ApiException

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

the class NetworkWebScriptGet method execute.

@Override
public void execute(final Api api, final WebScriptRequest req, final WebScriptResponse res) throws IOException {
    try {
        transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {

            @Override
            public Void execute() throws Throwable {
                // apply content type
                res.setContentType(Format.JSON.mimetype() + ";charset=UTF-8");
                assistant.getJsonHelper().withWriter(res.getOutputStream(), new Writer() {

                    @Override
                    public void writeContents(JsonGenerator generator, ObjectMapper objectMapper) throws JsonGenerationException, JsonMappingException, IOException {
                        String personId = AuthenticationUtil.getFullyAuthenticatedUser();
                        String networkId = TenantUtil.getCurrentDomain();
                        PersonNetwork networkMembership = networks.getNetwork(personId, networkId);
                        if (networkMembership != null) {
                            // TODO this is not ideal, but the only way to populate the embedded network entities (this would normally be
                            // done automatically by the api framework).
                            Object wrapped = helper.processAdditionsToTheResponse(res, Api.ALFRESCO_PUBLIC, NetworksEntityResource.NAME, Params.valueOf(personId, null, req), networkMembership);
                            objectMapper.writeValue(generator, wrapped);
                        } else {
                            throw new EntityNotFoundException(networkId);
                        }
                    }
                });
                return null;
            }
        }, true, true);
    } catch (ApiException | WebScriptException apiException) {
        renderException(apiException, res, assistant);
    } catch (RuntimeException runtimeException) {
        renderException(runtimeException, res, assistant);
    }
}
Also used : EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) PersonNetwork(org.alfresco.rest.api.model.PersonNetwork) ResponseWriter(org.alfresco.rest.framework.tools.ResponseWriter) Writer(org.alfresco.rest.framework.jacksonextensions.JacksonHelper.Writer) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException)

Example 8 with ApiException

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

the class NetworksWebScriptGet method execute.

@Override
public void execute(final Api api, final WebScriptRequest req, final WebScriptResponse res) throws IOException {
    try {
        transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {

            @Override
            public Void execute() throws Throwable {
                final Paging paging = findPaging(req);
                // apply content type
                res.setContentType(Format.JSON.mimetype() + ";charset=UTF-8");
                assistant.getJsonHelper().withWriter(res.getOutputStream(), new Writer() {

                    @Override
                    public void writeContents(JsonGenerator generator, ObjectMapper objectMapper) throws JsonGenerationException, JsonMappingException, IOException {
                        List<Object> entities = new ArrayList<Object>();
                        String personId = AuthenticationUtil.getFullyAuthenticatedUser();
                        CollectionWithPagingInfo<PersonNetwork> networkMemberships = networks.getNetworks(personId, paging);
                        for (PersonNetwork networkMember : networkMemberships.getCollection()) {
                            // TODO this is not ideal, but the only way to populate the embedded network entities (this would normally be
                            // done automatically by the api framework).
                            Object wrapped = helper.processAdditionsToTheResponse(res, Api.ALFRESCO_PUBLIC, NetworksEntityResource.NAME, Params.valueOf(personId, null, req), networkMember);
                            entities.add(wrapped);
                        }
                        objectMapper.writeValue(generator, CollectionWithPagingInfo.asPaged(paging, entities));
                    }
                });
                return null;
            }
        }, true, true);
    } catch (ApiException | WebScriptException apiException) {
        renderException(apiException, res, assistant);
    } catch (RuntimeException runtimeException) {
        renderException(runtimeException, res, assistant);
    }
}
Also used : Paging(org.alfresco.rest.framework.resource.parameters.Paging) ArrayList(java.util.ArrayList) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) PersonNetwork(org.alfresco.rest.api.model.PersonNetwork) ResponseWriter(org.alfresco.rest.framework.tools.ResponseWriter) Writer(org.alfresco.rest.framework.jacksonextensions.JacksonHelper.Writer) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException)

Example 9 with ApiException

use of org.alfresco.rest.framework.core.exceptions.ApiException 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 10 with ApiException

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

the class ProcessDefinitionsImpl method createProcessDefinitionRest.

protected ProcessDefinition createProcessDefinitionRest(ProcessDefinitionEntity processDefinition) {
    ProcessDefinition processDefinitionRest = new ProcessDefinition(processDefinition);
    String localKey = getLocalProcessDefinitionKey(processDefinition.getKey());
    processDefinitionRest.setKey(localKey);
    String displayId = localKey + ".workflow";
    processDefinitionRest.setTitle(getLabel(displayId, "title"));
    processDefinitionRest.setDescription(getLabel(displayId, "description"));
    processDefinitionRest.setGraphicNotationDefined(processDefinition.isGraphicalNotationDefined());
    if (processDefinition.hasStartFormKey()) {
        try {
            StartFormData startFormData = activitiProcessEngine.getFormService().getStartFormData(processDefinition.getId());
            if (startFormData != null) {
                processDefinitionRest.setStartFormResourceKey(startFormData.getFormKey());
            }
        } catch (Exception e) {
            throw new ApiException("Error while retrieving start form key");
        }
    }
    return processDefinitionRest;
}
Also used : StartFormData(org.activiti.engine.form.StartFormData) ProcessDefinition(org.alfresco.rest.workflow.api.model.ProcessDefinition) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException) IOException(java.io.IOException) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException)

Aggregations

ApiException (org.alfresco.rest.framework.core.exceptions.ApiException)15 EntityNotFoundException (org.alfresco.rest.framework.core.exceptions.EntityNotFoundException)11 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)9 ConstraintViolatedException (org.alfresco.rest.framework.core.exceptions.ConstraintViolatedException)6 PermissionDeniedException (org.alfresco.rest.framework.core.exceptions.PermissionDeniedException)6 IOException (java.io.IOException)5 NodeRef (org.alfresco.service.cmr.repository.NodeRef)5 QName (org.alfresco.service.namespace.QName)5 FileBinaryResource (org.alfresco.rest.framework.resource.content.FileBinaryResource)4 File (java.io.File)3 InputStream (java.io.InputStream)3 NotFoundException (org.alfresco.rest.framework.core.exceptions.NotFoundException)3 WebScriptException (org.springframework.extensions.webscripts.WebScriptException)3 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 FileOutputStream (java.io.FileOutputStream)2 Serializable (java.io.Serializable)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 ActivitiObjectNotFoundException (org.activiti.engine.ActivitiObjectNotFoundException)2