Search in sources :

Example 1 with ContentInfoImpl

use of org.alfresco.rest.framework.resource.content.ContentInfoImpl in project alfresco-remote-api by Alfresco.

the class NodesImpl method upload.

@Override
public Node upload(String parentFolderNodeId, FormData formData, Parameters parameters) {
    if (formData == null || !formData.getIsMultiPart()) {
        throw new InvalidArgumentException("The request content-type is not multipart: " + parentFolderNodeId);
    }
    NodeRef parentNodeRef = validateOrLookupNode(parentFolderNodeId, null);
    if (!nodeMatches(parentNodeRef, Collections.singleton(ContentModel.TYPE_FOLDER), null, false)) {
        throw new InvalidArgumentException("NodeId of folder is expected: " + parentNodeRef.getId());
    }
    String fileName = null;
    Content content = null;
    boolean autoRename = false;
    QName nodeTypeQName = ContentModel.TYPE_CONTENT;
    // If a fileName clashes for a versionable file
    boolean overwrite = false;
    Boolean versionMajor = null;
    String versionComment = null;
    String relativePath = null;
    String renditionNames = null;
    Map<String, Object> qnameStrProps = new HashMap<>();
    Map<QName, Serializable> properties = null;
    for (FormData.FormField field : formData.getFields()) {
        switch(field.getName().toLowerCase()) {
            case "name":
                String str = getStringOrNull(field.getValue());
                if ((str != null) && (!str.isEmpty())) {
                    fileName = str;
                }
                break;
            case "filedata":
                if (field.getIsFile()) {
                    fileName = (fileName != null ? fileName : field.getFilename());
                    content = field.getContent();
                }
                break;
            case "autorename":
                autoRename = Boolean.valueOf(field.getValue());
                break;
            case "nodetype":
                nodeTypeQName = createQName(getStringOrNull(field.getValue()));
                if (!isSubClass(nodeTypeQName, ContentModel.TYPE_CONTENT)) {
                    throw new InvalidArgumentException("Can only upload type of cm:content: " + nodeTypeQName);
                }
                break;
            case "overwrite":
                overwrite = Boolean.valueOf(field.getValue());
                break;
            case "majorversion":
                versionMajor = Boolean.valueOf(field.getValue());
                break;
            case "comment":
                versionComment = getStringOrNull(field.getValue());
                break;
            case "relativepath":
                relativePath = getStringOrNull(field.getValue());
                break;
            case "renditions":
                renditionNames = getStringOrNull(field.getValue());
                break;
            default:
                {
                    final String propName = field.getName();
                    if (propName.indexOf(QName.NAMESPACE_PREFIX) > -1) {
                        qnameStrProps.put(propName, field.getValue());
                    }
                }
        }
    }
    // result in a success message, but the files do not appear.
    if (formData.getFields().length == 0) {
        throw new ConstraintViolatedException("No disk space available");
    }
    // destination, or site + container or updateNodeRef
    if ((fileName == null) || fileName.isEmpty() || (content == null)) {
        throw new InvalidArgumentException("Required parameters are missing");
    }
    if (autoRename && overwrite) {
        throw new InvalidArgumentException("Both 'overwrite' and 'autoRename' should not be true when uploading a file");
    }
    // if requested, make (get or create) path
    parentNodeRef = getOrCreatePath(parentNodeRef, relativePath);
    final QName assocTypeQName = ContentModel.ASSOC_CONTAINS;
    final Set<String> renditions = getRequestedRenditions(renditionNames);
    try {
        // Map the given properties, if any.
        if (qnameStrProps.size() > 0) {
            properties = mapToNodeProperties(qnameStrProps);
        }
        /*
             * Existing file handling
             */
        NodeRef existingFile = nodeService.getChildByName(parentNodeRef, assocTypeQName, fileName);
        if (existingFile != null) {
            // File already exists, decide what to do
            if (autoRename) {
                // attempt to find a unique name
                fileName = findUniqueName(parentNodeRef, fileName);
            // drop-through !
            } else if (overwrite && nodeService.hasAspect(existingFile, ContentModel.ASPECT_VERSIONABLE)) {
                // overwrite existing (versionable) file
                BasicContentInfo contentInfo = new ContentInfoImpl(content.getMimetype(), content.getEncoding(), -1, null);
                return updateExistingFile(parentNodeRef, existingFile, fileName, contentInfo, content.getInputStream(), parameters, versionMajor, versionComment);
            } else {
                // name clash (and no autoRename or overwrite)
                throw new ConstraintViolatedException(fileName + " already exists.");
            }
        }
        // Note: pending REPO-159, we currently auto-enable versioning on new upload (but not when creating empty file)
        if (versionMajor == null) {
            versionMajor = true;
        }
        // Create a new file.
        NodeRef nodeRef = createNewFile(parentNodeRef, fileName, nodeTypeQName, content, properties, assocTypeQName, parameters, versionMajor, versionComment);
        // Create the response
        final Node fileNode = getFolderOrDocumentFullInfo(nodeRef, parentNodeRef, nodeTypeQName, parameters);
        // RA-1052
        try {
            List<ThumbnailDefinition> thumbnailDefs = getThumbnailDefs(renditions);
            requestRenditions(thumbnailDefs, fileNode);
        } catch (Exception ex) {
            // Note: The log level is not 'error' as it could easily fill out the log file, especially in the Cloud.
            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());
            }
        }
        return fileNode;
    // Do not clean formData temp files to allow for retries.
    // Temp files will be deleted later when GC call DiskFileItem#finalize() method or by temp file cleaner.
    } catch (AccessDeniedException ade) {
        throw new PermissionDeniedException(ade.getMessage());
    }
/*
         * NOTE: Do not clean formData temp files to allow for retries. It's
         * possible for a temp file to remain if max retry attempts are
         * made, but this is rare, so leave to usual temp file cleanup.
         */
}
Also used : FormData(org.springframework.extensions.webscripts.servlet.FormData) Serializable(java.io.Serializable) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) QName(org.alfresco.service.namespace.QName) Node(org.alfresco.rest.api.model.Node) ConstraintViolatedException(org.alfresco.rest.framework.core.exceptions.ConstraintViolatedException) 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) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException) 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) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ThumbnailDefinition(org.alfresco.repo.thumbnail.ThumbnailDefinition) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) Content(org.springframework.extensions.surf.util.Content) ContentInfoImpl(org.alfresco.rest.framework.resource.content.ContentInfoImpl) BasicContentInfo(org.alfresco.rest.framework.resource.content.BasicContentInfo) PermissionDeniedException(org.alfresco.rest.framework.core.exceptions.PermissionDeniedException) FilterPropBoolean(org.alfresco.repo.node.getchildren.FilterPropBoolean)

Example 2 with ContentInfoImpl

use of org.alfresco.rest.framework.resource.content.ContentInfoImpl 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 3 with ContentInfoImpl

use of org.alfresco.rest.framework.resource.content.ContentInfoImpl in project alfresco-remote-api by Alfresco.

the class ResourceWebScriptPut method getContentInfo.

/**
 * Returns the basic content info from the request.
 * @param req WebScriptRequest
 * @return BasicContentInfo
 */
private BasicContentInfo getContentInfo(WebScriptRequest req) {
    String encoding = "UTF-8";
    String contentType = MimetypeMap.MIMETYPE_BINARY;
    if (StringUtils.isNotEmpty(req.getContentType())) {
        MediaType media = MediaType.parseMediaType(req.getContentType());
        contentType = media.getType() + '/' + media.getSubtype();
        if (media.getCharset() != null) {
            encoding = media.getCharset().toString();
        }
    }
    return new ContentInfoImpl(contentType, encoding, -1, Locale.getDefault());
}
Also used : MediaType(org.springframework.http.MediaType) ContentInfoImpl(org.alfresco.rest.framework.resource.content.ContentInfoImpl)

Example 4 with ContentInfoImpl

use of org.alfresco.rest.framework.resource.content.ContentInfoImpl in project alfresco-remote-api by Alfresco.

the class WithResponseTest method testSetters.

@Test
public void testSetters() throws Exception {
    WithResponse callBack = new WithResponse(Status.STATUS_OK, ResponseWriter.DEFAULT_JSON_CONTENT, ResponseWriter.CACHE_NEVER);
    callBack.setStatus(Status.STATUS_GONE);
    Cache myCache = new Cache(new Description.RequiredCache() {

        @Override
        public boolean getNeverCache() {
            return false;
        }

        @Override
        public boolean getIsPublic() {
            return true;
        }

        @Override
        public boolean getMustRevalidate() {
            return true;
        }
    });
    callBack.setCache(myCache);
    ContentInfo myContent = new ContentInfoImpl(Format.HTML.mimetype(), "UTF-16", 12, Locale.FRENCH);
    callBack.setContentInfo(myContent);
    assertEquals(Status.STATUS_GONE, callBack.getStatus());
    assertEquals(myCache, callBack.getCache());
    assertEquals(myContent, callBack.getContentInfo());
}
Also used : Description(org.springframework.extensions.webscripts.Description) WithResponse(org.alfresco.rest.framework.webscripts.WithResponse) ContentInfo(org.alfresco.rest.framework.resource.content.ContentInfo) ContentInfoImpl(org.alfresco.rest.framework.resource.content.ContentInfoImpl) Cache(org.springframework.extensions.webscripts.Cache) Test(org.junit.Test)

Aggregations

ContentInfoImpl (org.alfresco.rest.framework.resource.content.ContentInfoImpl)4 Serializable (java.io.Serializable)2 ApiException (org.alfresco.rest.framework.core.exceptions.ApiException)2 ConstraintViolatedException (org.alfresco.rest.framework.core.exceptions.ConstraintViolatedException)2 DisabledServiceException (org.alfresco.rest.framework.core.exceptions.DisabledServiceException)2 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)2 NotFoundException (org.alfresco.rest.framework.core.exceptions.NotFoundException)2 NodeRef (org.alfresco.service.cmr.repository.NodeRef)2 QName (org.alfresco.service.namespace.QName)2 File (java.io.File)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ContentLimitViolationException (org.alfresco.repo.content.ContentLimitViolationException)1 FilterPropBoolean (org.alfresco.repo.node.getchildren.FilterPropBoolean)1 IntegrityException (org.alfresco.repo.node.integrity.IntegrityException)1 AccessDeniedException (org.alfresco.repo.security.permissions.AccessDeniedException)1 ThumbnailDefinition (org.alfresco.repo.thumbnail.ThumbnailDefinition)1