Search in sources :

Example 6 with Content

use of org.springframework.extensions.surf.util.Content 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 7 with Content

use of org.springframework.extensions.surf.util.Content in project alfresco-remote-api by Alfresco.

the class BufferedRequest method getContent.

/* (non-Javadoc)
     * @see org.springframework.extensions.webscripts.WebScriptRequest#getContent()
     */
@Override
public Content getContent() {
    final Content wrapped = req.getContent();
    return new Content() {

        @Override
        public String getContent() throws IOException {
            return wrapped.getContent();
        }

        @Override
        public String getEncoding() {
            return wrapped.getEncoding();
        }

        @Override
        public String getMimetype() {
            return wrapped.getMimetype();
        }

        @Override
        public long getSize() {
            return wrapped.getSize();
        }

        @Override
        public InputStream getInputStream() {
            if (BufferedRequest.this.contentReader != null) {
                throw new IllegalStateException("Reader in use");
            }
            if (BufferedRequest.this.contentStream == null) {
                try {
                    BufferedRequest.this.contentStream = bufferInputStream();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return BufferedRequest.this.contentStream;
        }

        @Override
        public BufferedReader getReader() throws IOException {
            if (BufferedRequest.this.contentStream != null) {
                throw new IllegalStateException("Input Stream in use");
            }
            if (BufferedRequest.this.contentReader == null) {
                String encoding = wrapped.getEncoding();
                InputStream in = bufferInputStream();
                BufferedRequest.this.contentReader = new BufferedReader(new InputStreamReader(in, encoding == null ? "ISO-8859-1" : encoding));
            }
            return BufferedRequest.this.contentReader;
        }
    };
}
Also used : InputStreamReader(java.io.InputStreamReader) Content(org.springframework.extensions.surf.util.Content) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException)

Example 8 with Content

use of org.springframework.extensions.surf.util.Content in project alfresco-remote-api by Alfresco.

the class BulkMetadataGet method execute.

@Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    JSONObject jsonIn;
    JSONArray nodeRefsArray;
    try {
        Content c = req.getContent();
        if (c == null) {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Missing POST body.");
        }
        jsonIn = new JSONObject(c.getContent());
        nodeRefsArray = jsonIn.getJSONArray("nodeRefs");
        if (nodeRefsArray == null || nodeRefsArray.length() == 0) {
            throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Must provide node refs");
        }
        JSONWriter jsonOut = new JSONWriter(res.getWriter());
        res.setContentType("application/json");
        // TODO: Should be settable on JSONWriter
        res.setContentEncoding(Charset.defaultCharset().displayName());
        jsonOut.startObject();
        {
            jsonOut.startValue("nodes");
            {
                jsonOut.startArray();
                {
                    for (int i = 0; i < nodeRefsArray.length(); i++) {
                        NodeRef nodeRef = new NodeRef(nodeRefsArray.getString(i));
                        if (nodeService.exists(nodeRef)) {
                            NodeRef parentNodeRef = null;
                            ChildAssociationRef childAssocRef = nodeService.getPrimaryParent(nodeRef);
                            if (childAssocRef != null) {
                                parentNodeRef = childAssocRef.getParentRef();
                            }
                            QName type = nodeService.getType(nodeRef);
                            String shortType = type.toPrefixString(services.getNamespaceService());
                            Map<QName, Serializable> properties = nodeService.getProperties(nodeRef);
                            jsonOut.startObject();
                            {
                                jsonOut.writeValue("nodeRef", nodeRef.toString());
                                jsonOut.writeValue("parentNodeRef", parentNodeRef.toString());
                                jsonOut.writeValue("type", type.toString());
                                jsonOut.writeValue("shortType", shortType);
                                TypeDefinition typeDef = dictionaryService.getType(type);
                                jsonOut.writeValue("typeTitle", typeDef.getTitle(dictionaryService));
                                jsonOut.writeValue("name", (String) properties.get(ContentModel.PROP_NAME));
                                jsonOut.writeValue("title", (String) properties.get(ContentModel.PROP_TITLE));
                                jsonOut.writeValue("mimeType", getMimeType((ContentData) properties.get(ContentModel.PROP_CONTENT)));
                                jsonOut.writeValue("hasWritePermission", permissionService.hasPermission(nodeRef, PermissionService.WRITE) == AccessStatus.ALLOWED);
                                jsonOut.writeValue("hasDeletePermission", permissionService.hasPermission(nodeRef, PermissionService.DELETE) == AccessStatus.ALLOWED);
                            }
                            jsonOut.endObject();
                        } else {
                            jsonOut.startObject();
                            {
                                jsonOut.writeValue("nodeRef", nodeRef.toString());
                                jsonOut.writeValue("error", "true");
                                jsonOut.writeValue("errorCode", "invalidNodeRef");
                                jsonOut.writeValue("errorText", I18NUtil.getMessage("msg.invalidNodeRef", nodeRef.toString()));
                            }
                            jsonOut.endObject();
                        }
                    }
                }
                jsonOut.endArray();
            }
            jsonOut.endValue();
        }
        jsonOut.endObject();
    } catch (JSONException jErr) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Unable to parse JSON POST body: " + jErr.getMessage());
    }
    res.getWriter().close();
    res.setStatus(Status.STATUS_OK);
}
Also used : JSONWriter(org.springframework.extensions.webscripts.json.JSONWriter) QName(org.alfresco.service.namespace.QName) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) TypeDefinition(org.alfresco.service.cmr.dictionary.TypeDefinition) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentData(org.alfresco.service.cmr.repository.ContentData) JSONObject(org.json.JSONObject) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) Content(org.springframework.extensions.surf.util.Content) Map(java.util.Map)

Example 9 with Content

use of org.springframework.extensions.surf.util.Content in project alfresco-remote-api by Alfresco.

the class ChangePasswordPost method executeImpl.

/* (non-Javadoc)
     * @see org.alfresco.web.scripts.DeclarativeWebScript#executeImpl(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.Status)
     */
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
    // Extract user name from the URL - cannot be null or webscript desc would not match
    String userName = req.getExtensionPath();
    // Extract old and new password details from JSON POST
    Content c = req.getContent();
    if (c == null) {
        throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Missing POST body.");
    }
    JSONObject json;
    try {
        json = new JSONObject(c.getContent());
        String oldPassword = null;
        String newPassword;
        // admin users can change/set a password without knowing the old one
        boolean isAdmin = authorityService.hasAdminAuthority();
        if (!isAdmin || (userName.equalsIgnoreCase(authenticationService.getCurrentUserName()))) {
            if (!json.has(PARAM_OLDPW) || json.getString(PARAM_OLDPW).length() == 0) {
                throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Old password 'oldpw' is a required POST parameter.");
            }
            oldPassword = json.getString(PARAM_OLDPW);
        }
        if (!json.has(PARAM_NEWPW) || json.getString(PARAM_NEWPW).length() == 0) {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, "New password 'newpw' is a required POST parameter.");
        }
        newPassword = json.getString(PARAM_NEWPW);
        // an Admin user can update without knowing the original pass - but must know their own!
        if (!isAdmin || (userName.equalsIgnoreCase(authenticationService.getCurrentUserName()))) {
            authenticationService.updateAuthentication(userName, oldPassword.toCharArray(), newPassword.toCharArray());
        } else {
            authenticationService.setAuthentication(userName, newPassword.toCharArray());
        }
    } catch (AuthenticationException err) {
        throw new WebScriptException(Status.STATUS_UNAUTHORIZED, "Do not have appropriate auth or wrong auth details provided.");
    } catch (JSONException jErr) {
        throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Unable to parse JSON POST body: " + jErr.getMessage());
    } catch (IOException ioErr) {
        throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Unable to retrieve POST body: " + ioErr.getMessage());
    }
    Map<String, Object> model = new HashMap<String, Object>(1, 1.0f);
    model.put("success", Boolean.TRUE);
    return model;
}
Also used : WebScriptException(org.springframework.extensions.webscripts.WebScriptException) JSONObject(org.json.JSONObject) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) HashMap(java.util.HashMap) Content(org.springframework.extensions.surf.util.Content) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) IOException(java.io.IOException)

Example 10 with Content

use of org.springframework.extensions.surf.util.Content in project alfresco-remote-api by Alfresco.

the class AclsGet method buildModel.

private Map<String, Object> buildModel(WebScriptRequest req) throws JSONException, IOException {
    List<Long> aclChangeSetIds = null;
    Content content = req.getContent();
    if (content == null) {
        throw new WebScriptException("Request content is empty");
    }
    JSONObject o = new JSONObject(content.getContent());
    JSONArray aclChangeSetIdsJSON = o.has("aclChangeSetIds") ? o.getJSONArray("aclChangeSetIds") : null;
    if (aclChangeSetIdsJSON == null) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter 'aclChangeSetIds' not provided in request content.");
    } else if (aclChangeSetIdsJSON.length() == 0) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter 'aclChangeSetIds' must hold from 1 or more IDs.");
    }
    aclChangeSetIds = new ArrayList<Long>(aclChangeSetIdsJSON.length());
    for (int i = 0; i < aclChangeSetIdsJSON.length(); i++) {
        aclChangeSetIds.add(aclChangeSetIdsJSON.getLong(i));
    }
    String fromIdParam = req.getParameter("fromId");
    String maxResultsParam = req.getParameter("maxResults");
    Long fromId = (fromIdParam == null ? null : Long.valueOf(fromIdParam));
    int maxResults = (maxResultsParam == null ? 1024 : Integer.valueOf(maxResultsParam));
    // Request according to the paging query style required
    List<Acl> acls = solrTrackingComponent.getAcls(aclChangeSetIds, fromId, maxResults);
    Map<String, Object> model = new HashMap<String, Object>(1, 1.0f);
    model.put("acls", acls);
    if (logger.isDebugEnabled()) {
        logger.debug("Result: \n\tRequest: " + req + "\n\tModel: " + model);
    }
    return model;
}
Also used : HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) Acl(org.alfresco.repo.solr.Acl) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) JSONObject(org.json.JSONObject) Content(org.springframework.extensions.surf.util.Content) JSONObject(org.json.JSONObject)

Aggregations

Content (org.springframework.extensions.surf.util.Content)17 HashMap (java.util.HashMap)10 JSONObject (org.json.JSONObject)10 WebScriptException (org.springframework.extensions.webscripts.WebScriptException)9 IOException (java.io.IOException)7 JSONArray (org.json.JSONArray)6 JSONException (org.json.JSONException)6 WebScriptRequest (org.springframework.extensions.webscripts.WebScriptRequest)6 StringReader (java.io.StringReader)5 QName (org.alfresco.service.namespace.QName)4 Match (org.springframework.extensions.webscripts.Match)3 List (java.util.List)2 Params (org.alfresco.rest.framework.resource.parameters.Params)2 Farmer (org.alfresco.rest.framework.tests.api.mocks.Farmer)2 ResourceWebScriptPost (org.alfresco.rest.framework.webscripts.ResourceWebScriptPost)2 NodeRef (org.alfresco.service.cmr.repository.NodeRef)2 Test (org.junit.Test)2 BufferedReader (java.io.BufferedReader)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1