Search in sources :

Example 1 with THUMBNAIL

use of org.alfresco.repo.rendition2.RenditionDefinition2.THUMBNAIL in project alfresco-remote-api by Alfresco.

the class RenditionsImpl method getRenditions.

@Override
public CollectionWithPagingInfo<Rendition> getRenditions(NodeRef nodeRef, String versionLabelId, Parameters parameters) {
    final NodeRef validatedNodeRef = validateNode(nodeRef.getStoreRef(), nodeRef.getId(), versionLabelId, parameters);
    ContentData contentData = getContentData(validatedNodeRef, true);
    String sourceMimetype = contentData.getMimetype();
    boolean includeCreated = true;
    boolean includeNotCreated = true;
    String status = getStatus(parameters);
    if (status != null) {
        includeCreated = RenditionStatus.CREATED.equals(RenditionStatus.valueOf(status));
        includeNotCreated = !includeCreated;
    }
    // List all available rendition definitions
    long size = contentData.getSize();
    RenditionDefinitionRegistry2 renditionDefinitionRegistry2 = renditionService2.getRenditionDefinitionRegistry2();
    Set<String> renditionNames = renditionDefinitionRegistry2.getRenditionNamesFrom(sourceMimetype, size);
    Map<String, Rendition> apiRenditions = new TreeMap<>();
    if (includeNotCreated) {
        for (String renditionName : renditionNames) {
            apiRenditions.put(renditionName, toApiRendition(renditionName));
        }
    }
    List<ChildAssociationRef> nodeRefRenditions = renditionService2.getRenditions(validatedNodeRef);
    if (!nodeRefRenditions.isEmpty()) {
        for (ChildAssociationRef childAssociationRef : nodeRefRenditions) {
            NodeRef renditionNodeRef = childAssociationRef.getChildRef();
            Rendition apiRendition = toApiRendition(renditionNodeRef);
            String renditionName = apiRendition.getId();
            if (renditionNames.contains(renditionName)) {
                if (includeCreated) {
                    // Replace/append any thumbnail definitions with created rendition info
                    apiRenditions.put(renditionName, apiRendition);
                } else {
                    // Remove any thumbnail definitions that has been created from the list,
                    // as the filter requires only the Not_Created renditions
                    apiRenditions.remove(renditionName);
                }
            } else {
                if (logger.isTraceEnabled()) {
                    logger.trace("Skip unknown rendition [" + renditionName + ", " + renditionNodeRef + "]");
                }
            }
        }
    }
    // Wrap paging info, as the core service doesn't support paging
    Paging paging = parameters.getPaging();
    PagingResults<Rendition> results = Util.wrapPagingResults(paging, apiRenditions.values());
    return CollectionWithPagingInfo.asPaged(paging, results.getPage(), results.hasMoreItems(), results.getTotalResultCount().getFirst());
}
Also used : Rendition(org.alfresco.rest.api.model.Rendition) Paging(org.alfresco.rest.framework.resource.parameters.Paging) RenditionDefinitionRegistry2(org.alfresco.repo.rendition2.RenditionDefinitionRegistry2) TreeMap(java.util.TreeMap) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentData(org.alfresco.service.cmr.repository.ContentData)

Example 2 with THUMBNAIL

use of org.alfresco.repo.rendition2.RenditionDefinition2.THUMBNAIL in project alfresco-remote-api by Alfresco.

the class NodesImpl method requestRenditions.

private void requestRenditions(Set<String> renditionNames, Node fileNode) {
    if (renditionNames != null) {
        NodeRef sourceNodeRef = fileNode.getNodeRef();
        String mimeType = fileNode.getContent().getMimeType();
        long size = fileNode.getContent().getSizeInBytes();
        RenditionDefinitionRegistry2 renditionDefinitionRegistry2 = renditionService2.getRenditionDefinitionRegistry2();
        Set<String> availableRenditions = renditionDefinitionRegistry2.getRenditionNamesFrom(mimeType, size);
        for (String renditionName : renditionNames) {
            // RA-1052 (REPO-47)
            try {
                // File may be to big
                if (!availableRenditions.contains(renditionName)) {
                    throw new InvalidArgumentException("Unable to create thumbnail '" + renditionName + "' for " + mimeType + " as no transformer is currently available.");
                }
                renditionService2.render(sourceNodeRef, renditionName);
            } catch (Exception ex) {
                // Note: The log level is not 'error' as it could easily fill out the log file.
                if (logger.isDebugEnabled()) {
                    // Don't throw the exception as we don't want the the upload to fail, just log it.
                    logger.debug("Asynchronous request to create a rendition upon upload failed: " + ex.getMessage());
                }
            }
        }
    }
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) RenditionDefinitionRegistry2(org.alfresco.repo.rendition2.RenditionDefinitionRegistry2) FileExistsException(org.alfresco.service.cmr.model.FileExistsException) PermissionDeniedException(org.alfresco.rest.framework.core.exceptions.PermissionDeniedException) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) DuplicateChildNodeNameException(org.alfresco.service.cmr.repository.DuplicateChildNodeNameException) NotFoundException(org.alfresco.rest.framework.core.exceptions.NotFoundException) ConcurrencyFailureException(org.springframework.dao.ConcurrencyFailureException) ConstraintViolatedException(org.alfresco.rest.framework.core.exceptions.ConstraintViolatedException) IntegrityException(org.alfresco.repo.node.integrity.IntegrityException) IOException(java.io.IOException) RequestEntityTooLargeException(org.alfresco.rest.framework.core.exceptions.RequestEntityTooLargeException) DisabledServiceException(org.alfresco.rest.framework.core.exceptions.DisabledServiceException) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) ContentQuotaException(org.alfresco.service.cmr.usage.ContentQuotaException) UnsupportedMediaTypeException(org.alfresco.rest.framework.core.exceptions.UnsupportedMediaTypeException) AssociationExistsException(org.alfresco.service.cmr.repository.AssociationExistsException) InsufficientStorageException(org.alfresco.rest.framework.core.exceptions.InsufficientStorageException) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException) NodeLockedException(org.alfresco.service.cmr.lock.NodeLockedException) ContentIOException(org.alfresco.service.cmr.repository.ContentIOException) ContentLimitViolationException(org.alfresco.repo.content.ContentLimitViolationException)

Example 3 with THUMBNAIL

use of org.alfresco.repo.rendition2.RenditionDefinition2.THUMBNAIL in project alfresco-repository by Alfresco.

the class ScriptNode method createThumbnail.

/**
 * Creates a thumbnail for the content property of the node.
 *
 * The thumbnail name corresponds to pre-set thumbnail details stored in the
 * repository.
 *
 * If the thumbnail is created asynchronously then the result will be null and creation
 * of the thumbnail will occure at some point in the background.
 *
 * If foce param specified system.thumbnail.generate is ignoring. Could be used for preview creation
 *
 * @param  thumbnailName    the name of the thumbnail
 * @param  async            indicates whether the thumbnail is create asynchronously or not
 * @param  force            ignore system.thumbnail.generate=false
 * @return ScriptThumbnail  the newly create thumbnail node or null if async creation occures
 *
 * @deprecated The async flag in the method signature will not be applicable as all of
 * the future transformations will be asynchronous
 */
@Deprecated
public ScriptThumbnail createThumbnail(String thumbnailName, boolean async, boolean force) {
    final ThumbnailService thumbnailService = services.getThumbnailService();
    ScriptThumbnail result = null;
    // We need to create preview for node even if system.thumbnail.generate=false
    if (force || thumbnailService.getThumbnailsEnabled()) {
        // Use the thumbnail registy to get the details of the thumbail
        ThumbnailRegistry registry = thumbnailService.getThumbnailRegistry();
        ThumbnailDefinition details = registry.getThumbnailDefinition(thumbnailName);
        if (details == null) {
            // Throw exception
            throw new ScriptException("The thumbnail name '" + thumbnailName + "' is not registered");
        }
        // If there's nothing currently registered to generate thumbnails for the
        // specified mimetype, then log a message and bail out
        String nodeMimeType = getMimetype();
        Serializable value = this.nodeService.getProperty(nodeRef, ContentModel.PROP_CONTENT);
        ContentData contentData = DefaultTypeConverter.INSTANCE.convert(ContentData.class, value);
        if (!ContentData.hasContent(contentData)) {
            if (logger.isDebugEnabled())
                logger.debug("Unable to create thumbnail '" + details.getName() + "' as there is no content");
            return null;
        }
        if (!registry.isThumbnailDefinitionAvailable(contentData.getContentUrl(), nodeMimeType, getSize(), nodeRef, details)) {
            logger.info("Unable to create thumbnail '" + details.getName() + "' for " + nodeMimeType + " as no transformer is currently available.");
            return null;
        }
        // Have the thumbnail created
        if (async == false) {
            try {
                // Create the thumbnail
                NodeRef thumbnailNodeRef = thumbnailService.createThumbnail(this.nodeRef, ContentModel.PROP_CONTENT, details.getMimetype(), details.getTransformationOptions(), details.getName());
                // Create the thumbnail script object
                result = new ScriptThumbnail(thumbnailNodeRef, this.services, this.scope);
            } catch (AlfrescoRuntimeException e) {
                Throwable rootCause = e.getRootCause();
                if (rootCause instanceof UnimportantTransformException) {
                    logger.debug("Unable to create thumbnail '" + details.getName() + "' as " + rootCause.getMessage());
                    return null;
                }
                throw e;
            }
        } else {
            RenditionDefinition2 renditionDefinition = renditionDefinitionRegistry2.getRenditionDefinition(thumbnailName);
            if (renditionDefinition != null) {
                renditionService2.render(nodeRef, thumbnailName);
            } else {
                Action action = ThumbnailHelper.createCreateThumbnailAction(details, services);
                // Queue async creation of thumbnail
                this.services.getActionService().executeAction(action, this.nodeRef, true, true);
            }
        }
    }
    return result;
}
Also used : Serializable(java.io.Serializable) Action(org.alfresco.service.cmr.action.Action) ThumbnailService(org.alfresco.service.cmr.thumbnail.ThumbnailService) ThumbnailRegistry(org.alfresco.repo.thumbnail.ThumbnailRegistry) UnimportantTransformException(org.alfresco.repo.content.transform.UnimportantTransformException) ScriptException(org.alfresco.scripts.ScriptException) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ThumbnailDefinition(org.alfresco.repo.thumbnail.ThumbnailDefinition) ContentData(org.alfresco.service.cmr.repository.ContentData) ScriptThumbnail(org.alfresco.repo.thumbnail.script.ScriptThumbnail) RenditionDefinition2(org.alfresco.repo.rendition2.RenditionDefinition2) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException)

Example 4 with THUMBNAIL

use of org.alfresco.repo.rendition2.RenditionDefinition2.THUMBNAIL in project alfresco-remote-api by Alfresco.

the class RenditionsTest method testCreateRendition.

/**
 * Tests create rendition.
 * <p>POST:</p>
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/nodes/<nodeId>/renditions}
 */
@Test
public void testCreateRendition() throws Exception {
    setRequestContext(networkN1.getId(), userOneN1.getId(), null);
    // Create a folder within the site document's library
    String folderName = "folder" + System.currentTimeMillis();
    String folder_Id = addToDocumentLibrary(userOneN1Site, folderName, TYPE_CM_FOLDER, userOneN1.getId());
    // Create multipart request
    String fileName = "quick.pdf";
    File file = getResourceFile(fileName);
    MultiPartBuilder multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData(fileName, file));
    MultiPartRequest reqBody = multiPartBuilder.build();
    // Upload quick.pdf file into 'folder'
    HttpResponse response = post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
    Document document = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
    String contentNodeId = document.getId();
    // pause briefly
    Thread.sleep(DELAY_IN_MS);
    // Get rendition (not created yet) information for node
    response = getSingle(getNodeRenditionsUrl(contentNodeId), "imgpreview", 200);
    Rendition rendition = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Rendition.class);
    assertNotNull(rendition);
    assertEquals(RenditionStatus.NOT_CREATED, rendition.getStatus());
    // Try to download non-existent rendition (and no placeholder)
    Map<String, String> params = new HashMap<>();
    params.put("placeholder", "false");
    getSingle(getNodeRenditionsUrl(contentNodeId), ("doclib/content"), params, 404);
    // Download placeholder instead
    params = new HashMap<>();
    params.put("placeholder", "true");
    response = getSingle(getNodeRenditionsUrl(contentNodeId), ("doclib/content"), params, 200);
    assertNotNull(response.getResponseAsBytes());
    // Create and get 'imgpreview' rendition
    rendition = createAndGetRendition(contentNodeId, "imgpreview");
    assertNotNull(rendition);
    assertEquals(RenditionStatus.CREATED, rendition.getStatus());
    ContentInfo contentInfo = rendition.getContent();
    assertNotNull(contentInfo);
    assertEquals(MimetypeMap.MIMETYPE_IMAGE_JPEG, contentInfo.getMimeType());
    assertEquals("JPEG Image", contentInfo.getMimeTypeName());
    assertNotNull(contentInfo.getEncoding());
    assertTrue(contentInfo.getSizeInBytes() > 0);
    // Create 'doclib' rendition request
    Rendition renditionRequest = new Rendition().setId("doclib");
    // Test only if OpenOffice is available
    if (isOpenOfficeAvailable()) {
        // Create a node without any content
        String emptyContentNodeId = addToDocumentLibrary(userOneN1Site, "emptyDoc.txt", TYPE_CM_CONTENT, userOneN1.getId());
        post(getNodeRenditionsUrl(emptyContentNodeId), toJsonAsString(renditionRequest), 202);
        // Rendition for binary content
        String content = "The quick brown fox jumps over the lazy dog.";
        file = TempFileProvider.createTempFile(new ByteArrayInputStream(content.getBytes()), getClass().getSimpleName(), ".bin");
        multiPartBuilder = MultiPartBuilder.create().setFileData(new FileData("binaryFileName", file));
        reqBody = multiPartBuilder.build();
        response = post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
        Document binaryDocument = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
        post(getNodeRenditionsUrl(binaryDocument.getId()), toJsonAsString(renditionRequest), 202);
    }
    // 
    // -ve Tests
    // 
    // The rendition requested already exists
    response = post(getNodeRenditionsUrl(contentNodeId), toJsonAsString(new Rendition().setId("imgpreview")), 409);
    ExpectedErrorResponse errorResponse = RestApiUtil.parseErrorResponse(response.getJsonResponse());
    assertNotNull(errorResponse);
    assertNotNull(errorResponse.getErrorKey());
    assertNotNull(errorResponse.getBriefSummary());
    assertNotNull(errorResponse.getStackTrace());
    assertNotNull(errorResponse.getDescriptionURL());
    assertEquals(409, errorResponse.getStatusCode());
    // nodeId in the path parameter does not represent a file
    post(getNodeRenditionsUrl(folder_Id), toJsonAsString(renditionRequest), 400);
    // nodeId in the path parameter does not exist
    response = post(getNodeRenditionsUrl(UUID.randomUUID().toString()), toJsonAsString(renditionRequest), 404);
    // EntityNotFoundException
    errorResponse = RestApiUtil.parseErrorResponse(response.getJsonResponse());
    assertNotNull(errorResponse);
    assertNotNull(errorResponse.getErrorKey());
    assertNotNull(errorResponse.getBriefSummary());
    assertNotNull(errorResponse.getStackTrace());
    assertNotNull(errorResponse.getDescriptionURL());
    assertEquals(404, errorResponse.getStatusCode());
    // renditionId is not registered
    final String randomRenditionId = "renditionId" + System.currentTimeMillis();
    post(getNodeRenditionsUrl(contentNodeId), toJsonAsString(new Rendition().setId(randomRenditionId)), 404);
    // renditionId is null
    post(getNodeRenditionsUrl(contentNodeId), toJsonAsString(new Rendition().setId(null)), 400);
    // renditionId is empty
    post(getNodeRenditionsUrl(contentNodeId), toJsonAsString(new Rendition().setId("")), 400);
    // Multiple rendition request (as of ACS 6.1)
    // Multiple rendition request, including an empty id
    List<Rendition> multipleRenditionRequest = new ArrayList<>(2);
    multipleRenditionRequest.add(new Rendition().setId(""));
    multipleRenditionRequest.add(new Rendition().setId("medium"));
    post(getNodeRenditionsUrl(contentNodeId), toJsonAsString(multipleRenditionRequest), 400);
    // Multiple rendition request. doclib has already been done
    multipleRenditionRequest = new ArrayList<>(3);
    multipleRenditionRequest.add(new Rendition().setId("doclib"));
    multipleRenditionRequest.add(new Rendition().setId("medium"));
    multipleRenditionRequest.add(new Rendition().setId("avatar,avatar32"));
    post(getNodeRenditionsUrl(contentNodeId), toJsonAsString(multipleRenditionRequest), 202);
    assertRenditionCreatedWithWait(contentNodeId, "doclib", "medium", "avatar", "avatar32");
    // Multiple rendition request. All have already been done.
    multipleRenditionRequest = new ArrayList<>(2);
    multipleRenditionRequest.add(new Rendition().setId("doclib"));
    multipleRenditionRequest.add(new Rendition().setId("medium"));
    multipleRenditionRequest.add(new Rendition().setId("avatar"));
    post(getNodeRenditionsUrl(contentNodeId), toJsonAsString(multipleRenditionRequest), 409);
    // Disable thumbnail generation
    RenditionService2Impl renditionService2 = applicationContext.getBean("renditionService2", RenditionService2Impl.class);
    renditionService2.setThumbnailsEnabled(false);
    try {
        // Create multipart request
        String txtFileName = "quick-1.txt";
        File txtFile = getResourceFile(fileName);
        reqBody = MultiPartBuilder.create().setFileData(new FileData(txtFileName, txtFile)).build();
        // Upload quick-1.txt file into 'folder'
        response = post(getNodeChildrenUrl(folder_Id), reqBody.getBody(), null, reqBody.getContentType(), 201);
        Document txtDocument = RestApiUtil.parseRestApiEntry(response.getJsonResponse(), Document.class);
        // Thumbnail generation has been disabled
        response = post(getNodeRenditionsUrl(txtDocument.getId()), toJsonAsString(renditionRequest), 501);
        errorResponse = RestApiUtil.parseErrorResponse(response.getJsonResponse());
        assertNotNull(errorResponse);
        assertNotNull(errorResponse.getErrorKey());
        assertNotNull(errorResponse.getBriefSummary());
        assertNotNull(errorResponse.getStackTrace());
        assertNotNull(errorResponse.getDescriptionURL());
        assertEquals(501, errorResponse.getStatusCode());
    } finally {
        renditionService2.setThumbnailsEnabled(true);
    }
}
Also used : ExpectedErrorResponse(org.alfresco.rest.api.tests.client.PublicApiClient.ExpectedErrorResponse) HashMap(java.util.HashMap) Rendition(org.alfresco.rest.api.tests.client.data.Rendition) ArrayList(java.util.ArrayList) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) RenditionService2Impl(org.alfresco.repo.rendition2.RenditionService2Impl) MultiPartRequest(org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest) RestApiUtil.toJsonAsString(org.alfresco.rest.api.tests.util.RestApiUtil.toJsonAsString) Document(org.alfresco.rest.api.tests.client.data.Document) MultiPartBuilder(org.alfresco.rest.api.tests.util.MultiPartBuilder) ContentInfo(org.alfresco.rest.api.tests.client.data.ContentInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) File(java.io.File) FileData(org.alfresco.rest.api.tests.util.MultiPartBuilder.FileData) Test(org.junit.Test)

Example 5 with THUMBNAIL

use of org.alfresco.repo.rendition2.RenditionDefinition2.THUMBNAIL in project alfresco-repository by Alfresco.

the class ThumbnailRegistry method isThumbnailDefinitionAvailable.

/**
 * Checks to see if at this moment in time, the specified {@link ThumbnailDefinition}
 *  is able to thumbnail the source mimetype. Typically used with Thumbnail Definitions
 *  retrieved by name, and/or when dealing with transient {@link ContentTransformer}s.
 * @param sourceUrl The URL of the source (optional)
 * @param sourceMimetype The source mimetype
 * @param sourceSize the size (in bytes) of the source. Use -1 if unknown.
 * @param sourceNodeRef which is set in a copy of the thumbnailDefinition transformation options,
 *        so that it may be used by transformers and debug.
 * @param thumbnailDefinition The {@link ThumbnailDefinition} to check for
 */
public boolean isThumbnailDefinitionAvailable(String sourceUrl, String sourceMimetype, long sourceSize, NodeRef sourceNodeRef, ThumbnailDefinition thumbnailDefinition) {
    // Use RenditionService2 if it knows about the definition, otherwise use localTransformServiceRegistry.
    // Needed as disabling local transforms should not disable thumbnails if they can be done remotely.
    boolean supported = false;
    String targetMimetype = thumbnailDefinition.getMimetype();
    RenditionDefinition2 renditionDefinition = getEquivalentRenditionDefinition2(thumbnailDefinition);
    if (renditionDefinition != null) {
        Map<String, String> options = renditionDefinition.getTransformOptions();
        String renditionName = renditionDefinition.getRenditionName();
        supported = transformServiceRegistry.isSupported(sourceMimetype, sourceSize, targetMimetype, options, renditionName);
    } else {
        boolean orig = TransformerDebug.setDebugOutput(false);
        try {
            TransformationOptions transformationOptions = thumbnailDefinition.getTransformationOptions();
            String renditionName = thumbnailDefinition.getName();
            Map<String, String> options = converter.getOptions(transformationOptions, sourceMimetype, targetMimetype);
            supported = localTransformServiceRegistry.isSupported(sourceMimetype, sourceSize, targetMimetype, options, renditionName);
        } finally {
            TransformerDebug.setDebugOutput(orig);
        }
    }
    return supported;
}
Also used : RenditionDefinition2(org.alfresco.repo.rendition2.RenditionDefinition2) TransformationOptions(org.alfresco.service.cmr.repository.TransformationOptions)

Aggregations

NodeRef (org.alfresco.service.cmr.repository.NodeRef)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 RenditionDefinition2 (org.alfresco.repo.rendition2.RenditionDefinition2)2 RenditionDefinitionRegistry2 (org.alfresco.repo.rendition2.RenditionDefinitionRegistry2)2 ContentData (org.alfresco.service.cmr.repository.ContentData)2 TransformationOptions (org.alfresco.service.cmr.repository.TransformationOptions)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 IOException (java.io.IOException)1 Serializable (java.io.Serializable)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 StringJoiner (java.util.StringJoiner)1 TreeMap (java.util.TreeMap)1 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)1