Search in sources :

Example 21 with ContentData

use of org.alfresco.service.cmr.repository.ContentData 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 22 with ContentData

use of org.alfresco.service.cmr.repository.ContentData 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 23 with ContentData

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

the class QuickShareThumbnailContentGet method executeImpl.

@Override
protected void executeImpl(NodeRef nodeRef, Map<String, String> templateVars, WebScriptRequest req, WebScriptResponse res, Map<String, Object> model) throws IOException {
    String thumbnailName = templateVars.get("thumbnailname");
    if (thumbnailName == null) {
        logger.error("Thumbnail name was not provided: " + nodeRef);
        throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find " + nodeRef);
    }
    // the latest thumbnail image.
    if (model == null) {
        model = new HashMap<String, Object>(1);
    }
    if (req.getParameter("lastModified") != null) {
        // note: must be String not boolean
        model.put("allowBrowserToCache", "true");
    } else {
        // note: must be String not boolean
        model.put("allowBrowserToCache", "false");
    }
    NodeRef thumbnailNodeRef = thumbnailService.getThumbnailByName(nodeRef, ContentModel.PROP_CONTENT, thumbnailName);
    if (thumbnailNodeRef == null) {
        // Get the queue/force create setting
        boolean qc = false;
        boolean fc = false;
        String c = req.getParameter("c");
        if (c != null) {
            if (c.equals("queue")) {
                qc = true;
            } else if (c.equals("force")) {
                fc = true;
            }
        }
        // Get the place holder flag
        boolean ph = false;
        String phString = req.getParameter("ph");
        if (phString != null) {
            ph = new Boolean(phString);
        }
        // note: required for ValueConverter (collection)
        Scriptable scope = new BaseScopableProcessorExtension().getScope();
        ScriptNode node = new ScriptNode(nodeRef, serviceRegistry, scope);
        // Queue the creation of the thumbnail if appropriate
        if (fc) {
            ScriptNode thumbnailNode = node.createThumbnail(thumbnailName, false);
            if (thumbnailNode != null) {
                thumbnailNodeRef = thumbnailNode.getNodeRef();
            }
        } else {
            if (qc) {
                node.createThumbnail(thumbnailName, true);
            }
        }
        if (thumbnailNodeRef == null) {
            if (ph == true) {
                // Try and get the place holder resource. We use a method in the thumbnail service
                // that by default gives us a resource based on the content's mime type.
                String phPath = null;
                ContentData contentData = (ContentData) this.serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_CONTENT);
                if (contentData != null) {
                    phPath = scriptThumbnailService.getMimeAwarePlaceHolderResourcePath(thumbnailName, contentData.getMimetype());
                }
                if (phPath == null) {
                    // 404 since no thumbnail was found
                    throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Thumbnail was not found and no place holder resource set for '" + thumbnailName + "'");
                } else {
                    // Set the resouce path in the model ready for the content stream to send back to the client
                    model.put("contentPath", phPath);
                }
            } else {
                // 404 since no thumbnail was found
                throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Thumbnail was not found");
            }
        }
    }
    super.executeImpl(thumbnailNodeRef, templateVars, req, res, model);
    if (logger.isDebugEnabled()) {
        logger.debug("QuickShare - retrieved thumbnail content: " + thumbnailNodeRef + " [" + nodeRef + "," + thumbnailName + "]");
    }
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentData(org.alfresco.service.cmr.repository.ContentData) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) BaseScopableProcessorExtension(org.alfresco.repo.jscript.BaseScopableProcessorExtension) Scriptable(org.mozilla.javascript.Scriptable) ScriptNode(org.alfresco.repo.jscript.ScriptNode)

Example 24 with ContentData

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

the class WebDAV method getDAVPropertyValue.

/**
 * Return the Alfresco property value for the specified WebDAV property
 *
 * @param davPropName String
 * @return Object
 */
public static Object getDAVPropertyValue(Map<QName, Serializable> props, String davPropName) {
    // Convert the WebDAV property name to the corresponding Alfresco property
    QName propName = _propertyNameMap.get(davPropName);
    if (propName == null)
        throw new AlfrescoRuntimeException("No mapping for WebDAV property " + davPropName);
    // Return the property value
    Object value = props.get(propName);
    if (value instanceof ContentData) {
        ContentData contentData = (ContentData) value;
        if (davPropName.equals(WebDAV.XML_GET_CONTENT_TYPE)) {
            value = contentData.getMimetype();
        } else if (davPropName.equals(WebDAV.XML_GET_CONTENT_LENGTH)) {
            value = new Long(contentData.getSize());
        }
    }
    return value;
}
Also used : ContentData(org.alfresco.service.cmr.repository.ContentData) QName(org.alfresco.service.namespace.QName) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException)

Example 25 with ContentData

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

the class GetMethod method generateDirectoryListing.

/**
 * Generates a HTML representation of the contents of the path represented by the given node
 *
 * @param fileInfo the file to use
 */
private void generateDirectoryListing(FileInfo fileInfo) {
    MimetypeService mimeTypeService = getMimetypeService();
    NodeService nodeService = getNodeService();
    Writer writer = null;
    try {
        writer = m_response.getWriter();
        boolean wasLink = false;
        if (fileInfo.isLink()) {
            fileInfo = getFileFolderService().getFileInfo(fileInfo.getLinkNodeRef());
            wasLink = true;
        }
        // Get the list of child nodes for the parent node
        List<FileInfo> childNodeInfos = getDAVHelper().getChildren(fileInfo);
        // Send back the start of the HTML
        writer.write("<html><head><title>");
        writer.write(WebDAVHelper.encodeHTML(I18NUtil.getMessage("webdav.repository_title")));
        writer.write("</title>");
        writer.write("<style>");
        writer.write("body { font-family: Arial, Helvetica; font-size: 12pt; background-color: white; }\n");
        writer.write("table { font-family: Arial, Helvetica; font-size: 12pt; background-color: white; }\n");
        writer.write(".listingTable { border: solid black 1px; }\n");
        writer.write(".textCommand { font-family: verdana; font-size: 10pt; }\n");
        writer.write(".textLocation { font-family: verdana; font-size: 11pt; font-weight: bold; color: #2a568f; }\n");
        writer.write(".textData { font-family: verdana; font-size: 10pt; }\n");
        writer.write(".tableHeading { font-family: verdana; font-size: 10pt; font-weight: bold; color: white; background-color: #2a568f; }\n");
        writer.write(".rowOdd { background-color: #eeeeee; }\n");
        writer.write(".rowEven { background-color: #dddddd; }\n");
        writer.write("</style></head>\n");
        writer.flush();
        // Send back the table heading
        writer.write("<body>\n");
        writer.write("<table cellspacing='2' cellpadding='3' border='0' width='100%'>\n");
        writer.write("<tr><td colspan='4' class='textLocation'>");
        writer.write(WebDAVHelper.encodeHTML(I18NUtil.getMessage("webdav.directory_listing")));
        writer.write(' ');
        writer.write(WebDAVHelper.encodeHTML(getPath()));
        writer.write("</td></tr>\n");
        writer.write("<tr><td height='10' colspan='4'></td></tr></table>");
        writer.write("<table cellspacing='2' cellpadding='3' border='0' width='100%' class='listingTable'>\n");
        writer.write("<tr><td class='tableHeading' width='*'>");
        writer.write(WebDAVHelper.encodeHTML(I18NUtil.getMessage("webdav.column.name")));
        writer.write("</td>");
        writer.write("<td class='tableHeading' width='10%'>");
        writer.write(WebDAVHelper.encodeHTML(I18NUtil.getMessage("webdav.column.size")));
        writer.write("</td>");
        writer.write("<td class='tableHeading' width='20%'>");
        writer.write(WebDAVHelper.encodeHTML(I18NUtil.getMessage("webdav.column.type")));
        writer.write("</td>");
        writer.write("<td class='tableHeading' width='25%'>");
        writer.write(WebDAVHelper.encodeHTML(I18NUtil.getMessage("webdav.column.modifieddate")));
        writer.write("</td>");
        writer.write("</tr>\n");
        // Get the URL for the root path
        String rootURL = getURLForPath(m_request, getPath(), true);
        if (rootURL.endsWith(WebDAVHelper.PathSeperator) == false) {
            rootURL = rootURL + WebDAVHelper.PathSeperator;
        }
        if (wasLink) {
            Path pathToNode = nodeService.getPath(fileInfo.getNodeRef());
            if (pathToNode.size() > 2) {
                pathToNode = pathToNode.subPath(2, pathToNode.size() - 1);
            }
            rootURL = getURLForPath(m_request, pathToNode.toDisplayPath(nodeService, getPermissionService()), true);
            if (rootURL.endsWith(WebDAVHelper.PathSeperator) == false) {
                rootURL = rootURL + WebDAVHelper.PathSeperator;
            }
            rootURL = rootURL + WebDAVHelper.encodeURL(fileInfo.getName(), m_userAgent) + WebDAVHelper.PathSeperator;
        }
        // Start with a link to the parent folder so we can navigate back up, unless we are at the root level
        if (!getDAVHelper().isRootPath(getPath(), getServletPath())) {
            writer.write("<tr class='rowOdd'>");
            writer.write("<td colspan='4' class='textData'><a href=\"");
            // Strip the last folder from the path
            String parentFolderUrl = parentFolder(rootURL);
            writer.write(parentFolderUrl);
            writer.write("\">");
            writer.write("[");
            writer.write(WebDAVHelper.encodeHTML(I18NUtil.getMessage("webdav.column.navigate_up")));
            writer.write("]</a>");
            writer.write("</tr>\n");
        }
        // Send back what we have generated so far
        writer.flush();
        int rowId = 0;
        for (FileInfo childNodeInfo : childNodeInfos) {
            // Output the details for the current node
            writer.write("<tr class='");
            if ((rowId++ & 1) == 1) {
                writer.write("rowOdd");
            } else {
                writer.write("rowEven");
            }
            writer.write("'><td class='textData'><a href=\"");
            writer.write(rootURL);
            // name field
            String fname = childNodeInfo.getName();
            writer.write(WebDAVHelper.encodeURL(fname, m_userAgent));
            writer.write("\">");
            writer.write(WebDAVHelper.encodeHTML(fname));
            writer.write("</a>");
            // size field
            writer.write("</td><td class='textData'>");
            ContentData contentData = null;
            if (!childNodeInfo.isFolder()) {
                Serializable contentPropertyName = nodeService.getProperty(childNodeInfo.getNodeRef(), ContentModel.PROP_CONTENT_PROPERTY_NAME);
                QName contentPropertyQName = DefaultTypeConverter.INSTANCE.convert(QName.class, contentPropertyName);
                if (null == contentPropertyQName) {
                    contentPropertyQName = ContentModel.PROP_CONTENT;
                }
                Serializable contentProperty = nodeService.getProperty(childNodeInfo.getNodeRef(), contentPropertyQName);
                if (contentProperty instanceof ContentData) {
                    contentData = (ContentData) contentProperty;
                }
            }
            if (childNodeInfo.isFolder()) {
                writer.write("&nbsp;");
            } else {
                if (null != contentData) {
                    writer.write(formatSize(Long.toString(contentData.getSize())));
                } else {
                    writer.write("&nbsp;");
                }
            }
            writer.write("</td><td class='textData'>");
            // mimetype field
            if (childNodeInfo.isFolder()) {
                writer.write("&nbsp;");
            } else {
                String mimetype = "&nbsp;";
                if (null != contentData) {
                    mimetype = contentData.getMimetype();
                    String displayType = mimeTypeService.getDisplaysByMimetype().get(mimetype);
                    if (displayType != null) {
                        mimetype = displayType;
                    }
                }
                writer.write(mimetype);
            }
            writer.write("</td><td class='textData'>");
            // modified date field
            Date modifiedDate = childNodeInfo.getModifiedDate();
            if (modifiedDate != null) {
                writer.write(WebDAV.formatHeaderDate(DefaultTypeConverter.INSTANCE.longValue(modifiedDate)));
            } else {
                writer.write("&nbsp;");
            }
            writer.write("</td></tr>\n");
            // flush every few rows
            if ((rowId & 15) == 0) {
                writer.flush();
            }
        }
        writer.write("</table></body></html>");
    } catch (Throwable e) {
        logger.error(e);
        if (writer != null) {
            try {
                writer.write("</table><table><tr><td style='color:red'>");
                writer.write(WebDAVHelper.encodeHTML(I18NUtil.getMessage("webdav.err.dir")));
                writer.write("</td></tr></table></body></html>");
                writer.flush();
            } catch (IOException ioe) {
            }
        }
    }
}
Also used : Path(org.alfresco.service.cmr.repository.Path) Serializable(java.io.Serializable) QName(org.alfresco.service.namespace.QName) NodeService(org.alfresco.service.cmr.repository.NodeService) IOException(java.io.IOException) Date(java.util.Date) ContentData(org.alfresco.service.cmr.repository.ContentData) FileInfo(org.alfresco.service.cmr.model.FileInfo) MimetypeService(org.alfresco.service.cmr.repository.MimetypeService) Writer(java.io.Writer)

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