Search in sources :

Example 1 with ContentData

use of org.alfresco.service.cmr.repository.ContentData in project alfresco-remote-api by Alfresco.

the class FormRestApiJsonPost_Test method testSimpleJsonPostRequest.

public void testSimpleJsonPostRequest() throws IOException, JSONException {
    // Retrieve and store the original property value.
    Serializable originalDescription = nodeService.getProperty(referencingDocNodeRef, ContentModel.PROP_DESCRIPTION);
    assertEquals(TEST_FORM_DESCRIPTION, originalDescription);
    // get the original mimetype
    String originalMimetype = null;
    ContentData content = (ContentData) this.nodeService.getProperty(referencingDocNodeRef, ContentModel.PROP_CONTENT);
    if (content != null) {
        originalMimetype = content.getMimetype();
    }
    // Construct some JSON to represent a new value.
    JSONObject jsonPostData = new JSONObject();
    final String proposedNewDescription = "Modified Description";
    jsonPostData.put(PROP_CM_DESCRIPTION, proposedNewDescription);
    jsonPostData.put(PROP_MIMETYPE, MimetypeMap.MIMETYPE_HTML);
    // Submit the JSON request.
    String jsonPostString = jsonPostData.toString();
    sendRequest(new PostRequest(referencingNodeUpdateUrl, jsonPostString, APPLICATION_JSON), 200);
    // The nodeService should give us the modified property.
    Serializable modifiedDescription = nodeService.getProperty(referencingDocNodeRef, ContentModel.PROP_DESCRIPTION);
    assertEquals(proposedNewDescription, modifiedDescription);
    // get the modified mimetype
    String modifiedMimetype = null;
    content = (ContentData) this.nodeService.getProperty(referencingDocNodeRef, ContentModel.PROP_CONTENT);
    if (content != null) {
        modifiedMimetype = content.getMimetype();
    }
    assertEquals(MimetypeMap.MIMETYPE_HTML, modifiedMimetype);
// The Rest API should also give us the modified property.
/*
        Response response = sendRequest(new GetRequest(referencingNodeUpdateUrl), 200);
        JSONObject jsonGetResponse = new JSONObject(response.getContentAsString());
        JSONObject jsonDataObj = (JSONObject)jsonGetResponse.get("data");
        assertNotNull(jsonDataObj);

        JSONObject formData = (JSONObject)jsonDataObj.get("formData");
        assertNotNull(formData);
        String retrievedValue = (String)formData.get(PROP_CM_DESCRIPTION);
        assertEquals(modifiedDescription, retrievedValue);
        String retrievedMimetype = (String)formData.get(PROP_MIMETYPE);
        assertEquals(MimetypeMap.MIMETYPE_HTML, modifiedMimetype);*/
}
Also used : Serializable(java.io.Serializable) PostRequest(org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest) ContentData(org.alfresco.service.cmr.repository.ContentData) JSONObject(org.json.JSONObject)

Example 2 with ContentData

use of org.alfresco.service.cmr.repository.ContentData in project alfresco-remote-api by Alfresco.

the class PutMethod method executeImpl.

/**
 * Execute the WebDAV request
 *
 * @exception WebDAVServerException
 */
protected void executeImpl() throws WebDAVServerException, Exception {
    if (logger.isDebugEnabled()) {
        String path = getPath();
        String userName = getDAVHelper().getAuthenticationService().getCurrentUserName();
        logger.debug("Put node: \n" + "     user: " + userName + "\n" + "     path: " + path + "\n" + "noContent: " + noContent);
    }
    FileFolderService fileFolderService = getFileFolderService();
    // Get the status for the request path
    LockInfo nodeLockInfo = null;
    try {
        contentNodeInfo = getNodeForPath(getRootNodeRef(), getPath());
        // make sure that we are not trying to use a folder
        if (contentNodeInfo.isFolder()) {
            throw new WebDAVServerException(HttpServletResponse.SC_BAD_REQUEST);
        }
        nodeLockInfo = checkNode(contentNodeInfo);
        // 'Unhide' nodes hidden by us and behave as though we created them
        NodeRef contentNodeRef = contentNodeInfo.getNodeRef();
        if (fileFolderService.isHidden(contentNodeRef) && !getDAVHelper().isRenameShuffle(getPath())) {
            fileFolderService.setHidden(contentNodeRef, false);
            created = true;
        }
    } catch (FileNotFoundException e) {
        // the file doesn't exist - create it
        String[] paths = getDAVHelper().splitPath(getPath());
        try {
            FileInfo parentNodeInfo = getNodeForPath(getRootNodeRef(), paths[0]);
            // create file
            contentNodeInfo = getDAVHelper().createFile(parentNodeInfo, paths[1]);
            created = true;
        } catch (FileNotFoundException ee) {
            // bad path
            throw new WebDAVServerException(HttpServletResponse.SC_CONFLICT);
        } catch (FileExistsException ee) {
            // ALF-7079 fix, retry: it looks like concurrent access (file not found but file exists)
            throw new ConcurrencyFailureException("Concurrent access was detected.", ee);
        }
    }
    String userName = getDAVHelper().getAuthenticationService().getCurrentUserName();
    LockInfo lockInfo = getDAVLockService().getLockInfo(contentNodeInfo.getNodeRef());
    if (lockInfo != null) {
        if (lockInfo.isLocked() && !lockInfo.getOwner().equals(userName)) {
            if (logger.isDebugEnabled()) {
                String path = getPath();
                String owner = lockInfo.getOwner();
                logger.debug("Node locked: path=[" + path + "], owner=[" + owner + "], current user=[" + userName + "]");
            }
            // Indicate that the resource is locked
            throw new WebDAVServerException(WebDAV.WEBDAV_SC_LOCKED);
        }
    }
    // ALF-16808: We disable the versionable aspect if we are overwriting
    // empty content because it's probably part of a compound operation to
    // create a new single version
    boolean disabledVersioning = false;
    try {
        // Disable versioning if we are overwriting an empty file with content
        NodeRef nodeRef = contentNodeInfo.getNodeRef();
        ContentData contentData = (ContentData) getNodeService().getProperty(nodeRef, ContentModel.PROP_CONTENT);
        if ((contentData == null || contentData.getSize() == 0) && getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)) {
            getDAVHelper().getPolicyBehaviourFilter().disableBehaviour(nodeRef, ContentModel.ASPECT_VERSIONABLE);
            disabledVersioning = true;
        }
        // Access the content
        ContentWriter writer = fileFolderService.getWriter(contentNodeInfo.getNodeRef());
        // set content properties
        writer.guessMimetype(contentNodeInfo.getName());
        writer.guessEncoding();
        // Get the input stream from the request data
        InputStream is = m_request.getInputStream();
        // Write the new data to the content node
        writer.putContent(is);
        // - the node does not have any content (zero length binaries included)
        if (nodeLockInfo != null && nodeLockInfo.isExclusive() && !(ContentData.hasContent(contentData) && contentData.getSize() > 0)) {
            getNodeService().addAspect(contentNodeInfo.getNodeRef(), ContentModel.ASPECT_NO_CONTENT, null);
        }
        // Ask for the document metadata to be extracted
        Action extract = getActionService().createAction(ContentMetadataExtracter.EXECUTOR_NAME);
        if (extract != null) {
            extract.setExecuteAsynchronously(false);
            getActionService().executeAction(extract, contentNodeInfo.getNodeRef());
        }
        // from the original specified in the request, update it.
        if (m_strContentType == null || !m_strContentType.equals(writer.getMimetype())) {
            String oldMimeType = m_strContentType;
            m_strContentType = writer.getMimetype();
            if (logger.isDebugEnabled()) {
                logger.debug("Mimetype originally specified as " + oldMimeType + ", now guessed to be " + m_strContentType);
            }
        }
        // Record the uploaded file's size
        fileSize = writer.getSize();
        // Set the response status, depending if the node existed or not
        m_response.setStatus(created ? HttpServletResponse.SC_CREATED : HttpServletResponse.SC_NO_CONTENT);
    } catch (AccessDeniedException e) {
        throw new WebDAVServerException(HttpServletResponse.SC_FORBIDDEN, e);
    } catch (Throwable e) {
        // we are about to give up
        if (noContent && RetryingTransactionHelper.extractRetryCause(e) == null) {
            // remove the 0 bytes content if save operation failed or was cancelled
            final NodeRef nodeRef = contentNodeInfo.getNodeRef();
            getTransactionService().getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>() {

                public String execute() throws Throwable {
                    getNodeService().deleteNode(nodeRef);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Put failed. DELETE  " + getPath());
                    }
                    return null;
                }
            }, false, false);
        }
        throw new WebDAVServerException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    } finally {
        if (disabledVersioning) {
            getDAVHelper().getPolicyBehaviourFilter().enableBehaviour(contentNodeInfo.getNodeRef(), ContentModel.ASPECT_VERSIONABLE);
        }
    }
    postActivity();
}
Also used : Action(org.alfresco.service.cmr.action.Action) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) InputStream(java.io.InputStream) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) FileFolderService(org.alfresco.service.cmr.model.FileFolderService) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) ContentData(org.alfresco.service.cmr.repository.ContentData) FileInfo(org.alfresco.service.cmr.model.FileInfo) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) ConcurrencyFailureException(org.springframework.dao.ConcurrencyFailureException) FileExistsException(org.alfresco.service.cmr.model.FileExistsException)

Example 3 with ContentData

use of org.alfresco.service.cmr.repository.ContentData in project alfresco-remote-api by Alfresco.

the class NodesImpl method getContent.

@Override
public BinaryResource getContent(NodeRef nodeRef, Parameters parameters, boolean recordActivity) {
    if (!nodeMatches(nodeRef, Collections.singleton(ContentModel.TYPE_CONTENT), null, false)) {
        throw new InvalidArgumentException("NodeId of content is expected: " + nodeRef.getId());
    }
    Map<QName, Serializable> nodeProps = nodeService.getProperties(nodeRef);
    ContentData cd = (ContentData) nodeProps.get(ContentModel.PROP_CONTENT);
    String name = (String) nodeProps.get(ContentModel.PROP_NAME);
    org.alfresco.rest.framework.resource.content.ContentInfo ci = null;
    String mimeType = null;
    if (cd != null) {
        mimeType = cd.getMimetype();
        ci = new org.alfresco.rest.framework.resource.content.ContentInfoImpl(mimeType, cd.getEncoding(), cd.getSize(), cd.getLocale());
    }
    // By default set attachment header (with filename) unless attachment=false *and* content type is pre-configured as non-attach
    boolean attach = true;
    String attachment = parameters.getParameter("attachment");
    if (attachment != null) {
        Boolean a = Boolean.valueOf(attachment);
        if (!a) {
            if (nonAttachContentTypes.contains(mimeType)) {
                attach = false;
            } else {
                logger.warn("Ignored attachment=false for " + nodeRef.getId() + " since " + mimeType + " is not in the whitelist for non-attach content types");
            }
        }
    }
    String attachFileName = (attach ? name : null);
    if (recordActivity) {
        final ActivityInfo activityInfo = getActivityInfo(getParentNodeRef(nodeRef), nodeRef);
        postActivity(Activity_Type.DOWNLOADED, activityInfo, true);
    }
    return new NodeBinaryResource(nodeRef, ContentModel.PROP_CONTENT, ci, attachFileName);
}
Also used : ActivityInfo(org.alfresco.service.cmr.activities.ActivityInfo) Serializable(java.io.Serializable) QName(org.alfresco.service.namespace.QName) ContentInfoImpl(org.alfresco.rest.framework.resource.content.ContentInfoImpl) NodeBinaryResource(org.alfresco.rest.framework.resource.content.NodeBinaryResource) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) ContentData(org.alfresco.service.cmr.repository.ContentData) FilterPropBoolean(org.alfresco.repo.node.getchildren.FilterPropBoolean)

Example 4 with ContentData

use of org.alfresco.service.cmr.repository.ContentData in project alfresco-remote-api by Alfresco.

the class NodesImpl method getDocument.

/**
 * @deprecated note: currently required for backwards compat' (Favourites API)
 */
@Override
public Document getDocument(NodeRef nodeRef) {
    Type type = getType(nodeRef);
    if ((type != null) && type.equals(Type.DOCUMENT)) {
        Map<QName, Serializable> properties = nodeService.getProperties(nodeRef);
        Document doc = new Document(nodeRef, getParentNodeRef(nodeRef), properties, null, sr);
        doc.setVersionLabel((String) properties.get(ContentModel.PROP_VERSION_LABEL));
        ContentData cd = (ContentData) properties.get(ContentModel.PROP_CONTENT);
        if (cd != null) {
            doc.setSizeInBytes(BigInteger.valueOf(cd.getSize()));
            doc.setMimeType((cd.getMimetype()));
        }
        setCommonProps(doc, nodeRef, properties);
        return doc;
    } else {
        throw new InvalidArgumentException("Node is not a file: " + nodeRef.getId());
    }
}
Also used : VersionType(org.alfresco.service.cmr.version.VersionType) ActivityType(org.alfresco.repo.activities.ActivityType) Serializable(java.io.Serializable) ContentData(org.alfresco.service.cmr.repository.ContentData) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) QName(org.alfresco.service.namespace.QName) Document(org.alfresco.rest.api.model.Document)

Example 5 with ContentData

use of org.alfresco.service.cmr.repository.ContentData in project alfresco-remote-api by Alfresco.

the class PropFindMethod method generateAllPropertiesResponse.

/**
 * Generates the XML response for a PROPFIND request that asks for all known
 * properties
 *
 * @param xml XMLWriter
 * @param nodeInfo FileInfo
 * @param isDir boolean
 */
protected void generateAllPropertiesResponse(XMLWriter xml, FileInfo nodeInfo, boolean isDir) throws Exception {
    // Get the properties for the node
    Map<QName, Serializable> props = nodeInfo.getProperties();
    // Output the start of the properties element
    Attributes nullAttr = getDAVHelper().getNullAttributes();
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT, nullAttr);
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP, nullAttr);
    // Generate a lock status report, if locked
    generateLockDiscoveryResponse(xml, nodeInfo, isDir);
    // Output the supported lock types
    writeLockTypes(xml);
    // If the node is a folder then return as a collection type
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_RESOURCE_TYPE, WebDAV.XML_NS_RESOURCE_TYPE, nullAttr);
    if (isDir)
        xml.write(DocumentHelper.createElement(WebDAV.XML_NS_COLLECTION));
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_RESOURCE_TYPE, WebDAV.XML_NS_RESOURCE_TYPE);
    // Get the node name
    Object davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_DISPLAYNAME);
    TypeConverter typeConv = DefaultTypeConverter.INSTANCE;
    // Output the node name
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_DISPLAYNAME, WebDAV.XML_NS_DISPLAYNAME, nullAttr);
    if (davValue != null) {
        String name = typeConv.convert(String.class, davValue);
        if (name == null || name.length() == 0) {
            logger.error("WebDAV name is null, value=" + davValue.getClass().getName() + ", node=" + nodeInfo.getNodeRef());
        }
        xml.write(name);
    }
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_DISPLAYNAME, WebDAV.XML_NS_DISPLAYNAME);
    // Output the source
    // 
    // NOTE: source is always a no content element in our implementation
    xml.write(DocumentHelper.createElement(WebDAV.XML_NS_SOURCE));
    // Get the creation date
    davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_CREATION_DATE);
    // Output the creation date
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_CREATION_DATE, WebDAV.XML_NS_CREATION_DATE, nullAttr);
    if (davValue != null)
        xml.write(WebDAV.formatCreationDate(typeConv.convert(Date.class, davValue)));
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_CREATION_DATE, WebDAV.XML_NS_CREATION_DATE);
    // Get the modifed date/time
    davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_GET_LAST_MODIFIED);
    // Output the last modified date of the node
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_LAST_MODIFIED, WebDAV.XML_NS_GET_LAST_MODIFIED, nullAttr);
    if (davValue != null)
        xml.write(WebDAV.formatModifiedDate(typeConv.convert(Date.class, davValue)));
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_LAST_MODIFIED, WebDAV.XML_NS_GET_LAST_MODIFIED);
    if (isDir == false) {
        // Get the content language
        // TODO:
        // Output the content language
        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LANGUAGE, WebDAV.XML_NS_GET_CONTENT_LANGUAGE, nullAttr);
        // TODO:
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LANGUAGE, WebDAV.XML_NS_GET_CONTENT_LANGUAGE);
        // Get the content type
        davValue = WebDAV.getDAVPropertyValue(props, WebDAV.XML_GET_CONTENT_TYPE);
        // Output the content type
        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_TYPE, WebDAV.XML_NS_GET_CONTENT_TYPE, nullAttr);
        if (davValue != null)
            xml.write(typeConv.convert(String.class, davValue));
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_TYPE, WebDAV.XML_NS_GET_CONTENT_TYPE);
        // Output the etag
        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_ETAG, WebDAV.XML_NS_GET_ETAG, nullAttr);
        xml.write(getDAVHelper().makeETag(nodeInfo));
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_ETAG, WebDAV.XML_NS_GET_ETAG);
    }
    // Get the content length, if it's not a folder
    long len = 0;
    if (isDir == false) {
        ContentData contentData = (ContentData) props.get(ContentModel.PROP_CONTENT);
        if (contentData != null)
            len = contentData.getSize();
    }
    // Output the content length
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LENGTH, WebDAV.XML_NS_GET_CONTENT_LENGTH, nullAttr);
    xml.write("" + len);
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_GET_CONTENT_LENGTH, WebDAV.XML_NS_GET_CONTENT_LENGTH);
    // Print out all the custom properties
    SessionUser davUser = (SessionUser) m_request.getSession().getAttribute(AuthenticationFilter.AUTHENTICATION_USER);
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_ALF_AUTHTICKET, WebDAV.XML_NS_ALF_AUTHTICKET, nullAttr);
    if (davUser != null)
        xml.write(davUser.getTicket());
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_ALF_AUTHTICKET, WebDAV.XML_NS_ALF_AUTHTICKET);
    // Close off the response
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP);
    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS, nullAttr);
    xml.write(WebDAV.HTTP1_1 + " " + HttpServletResponse.SC_OK + " " + WebDAV.SC_OK_DESC);
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS);
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT);
}
Also used : DefaultTypeConverter(org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter) TypeConverter(org.alfresco.service.cmr.repository.datatype.TypeConverter) Serializable(java.io.Serializable) SessionUser(org.alfresco.repo.SessionUser) ContentData(org.alfresco.service.cmr.repository.ContentData) QName(org.alfresco.service.namespace.QName) Attributes(org.xml.sax.Attributes) Date(java.util.Date)

Aggregations

ContentData (org.alfresco.service.cmr.repository.ContentData)29 Serializable (java.io.Serializable)14 QName (org.alfresco.service.namespace.QName)14 NodeRef (org.alfresco.service.cmr.repository.NodeRef)10 Date (java.util.Date)5 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)5 HashMap (java.util.HashMap)4 InputStream (java.io.InputStream)3 Map (java.util.Map)3 ContentInfo (org.alfresco.rest.api.model.ContentInfo)3 ConstraintViolatedException (org.alfresco.rest.framework.core.exceptions.ConstraintViolatedException)3 DisabledServiceException (org.alfresco.rest.framework.core.exceptions.DisabledServiceException)3 FileExistsException (org.alfresco.service.cmr.model.FileExistsException)3 ChildAssociationRef (org.alfresco.service.cmr.repository.ChildAssociationRef)3 ContentWriter (org.alfresco.service.cmr.repository.ContentWriter)3 InvalidNodeRefException (org.alfresco.service.cmr.repository.InvalidNodeRefException)3 Node (org.alfresco.web.bean.repository.Node)3 SessionUser (org.alfresco.repo.SessionUser)2 AccessDeniedException (org.alfresco.repo.security.permissions.AccessDeniedException)2 RetryingTransactionCallback (org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback)2