Search in sources :

Example 6 with MimetypeService

use of org.alfresco.service.cmr.repository.MimetypeService in project acs-community-packaging by Alfresco.

the class UploadContentServlet method doPut.

/**
 * @see javax.servlet.http.HttpServlet#doPut(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (logger.isDebugEnabled() == true) {
        String queryString = req.getQueryString();
        logger.debug("Authenticating request to URL: " + req.getRequestURI() + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
    }
    AuthenticationStatus status = servletAuthenticate(req, res, false);
    if (status == AuthenticationStatus.Failure || status == AuthenticationStatus.Guest) {
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }
    // Tokenise the URI
    String uri = req.getRequestURI();
    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();
    // skip servlet name
    t.nextToken();
    // get or calculate the noderef and filename to download as
    NodeRef nodeRef = null;
    String filename = null;
    QName propertyQName = null;
    if (tokenCount == 2) {
        // filename is the only token
        filename = t.nextToken();
    } else if (tokenCount == 4 || tokenCount == 5) {
        // assume 'workspace' or other NodeRef based protocol for remaining URL
        // elements
        StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
        String id = t.nextToken();
        // build noderef from the appropriate URL elements
        nodeRef = new NodeRef(storeRef, id);
        if (tokenCount == 5) {
            // filename is last remaining token
            filename = t.nextToken();
        }
        // get qualified of the property to get content from - default to
        // ContentModel.PROP_CONTENT
        propertyQName = ContentModel.PROP_CONTENT;
        String property = req.getParameter(ARG_PROPERTY);
        if (property != null && property.length() != 0) {
            propertyQName = QName.createQName(property);
        }
    } else {
        logger.debug("Upload URL did not contain all required args: " + uri);
        res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
        return;
    }
    // get the services we need to retrieve the content
    ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
    ContentService contentService = serviceRegistry.getContentService();
    PermissionService permissionService = serviceRegistry.getPermissionService();
    MimetypeService mimetypeService = serviceRegistry.getMimetypeService();
    NodeService nodeService = serviceRegistry.getNodeService();
    InputStream is = req.getInputStream();
    BufferedInputStream inputStream = new BufferedInputStream(is);
    // Sort out the mimetype
    String mimetype = req.getParameter(ARG_MIMETYPE);
    if (mimetype == null || mimetype.length() == 0) {
        mimetype = MIMETYPE_OCTET_STREAM;
        if (filename != null) {
            MimetypeService mimetypeMap = serviceRegistry.getMimetypeService();
            int extIndex = filename.lastIndexOf('.');
            if (extIndex != -1) {
                String ext = filename.substring(extIndex + 1);
                mimetype = mimetypeService.getMimetype(ext);
            }
        }
    }
    // Get the encoding
    String encoding = req.getParameter(ARG_ENCODING);
    if (encoding == null || encoding.length() == 0) {
        // Get the encoding
        ContentCharsetFinder charsetFinder = mimetypeService.getContentCharsetFinder();
        Charset charset = charsetFinder.getCharset(inputStream, mimetype);
        encoding = charset.name();
    }
    // Get the locale
    Locale locale = I18NUtil.parseLocale(req.getParameter(ARG_LOCALE));
    if (locale == null) {
        locale = I18NUtil.getContentLocale();
        if (nodeRef != null) {
            ContentData contentData = (ContentData) nodeService.getProperty(nodeRef, propertyQName);
            if (contentData != null) {
                locale = contentData.getLocale();
            }
        }
    }
    if (logger.isDebugEnabled()) {
        if (nodeRef != null) {
            logger.debug("Found NodeRef: " + nodeRef.toString());
        }
        logger.debug("For property: " + propertyQName);
        logger.debug("File name: " + filename);
        logger.debug("Mimetype: " + mimetype);
        logger.debug("Encoding: " + encoding);
        logger.debug("Locale: " + locale);
    }
    // Check that the user has the permissions to write the content
    if (permissionService.hasPermission(nodeRef, PermissionService.WRITE_CONTENT) == AccessStatus.DENIED) {
        if (logger.isDebugEnabled() == true) {
            logger.debug("User does not have permissions to wrtie content for NodeRef: " + nodeRef.toString());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Returning 403 Forbidden error...");
        }
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    // Try and get the content writer
    ContentWriter writer = contentService.getWriter(nodeRef, propertyQName, true);
    if (writer == null) {
        if (logger.isDebugEnabled() == true) {
            logger.debug("Content writer cannot be obtained for NodeRef: " + nodeRef.toString());
        }
        res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
        return;
    }
    // Set the mimetype, encoding and locale
    writer.setMimetype(mimetype);
    writer.setEncoding(encoding);
    if (locale != null) {
        writer.setLocale(locale);
    }
    // Stream the content into the repository
    writer.putContent(inputStream);
    if (logger.isDebugEnabled() == true) {
        logger.debug("Content details: " + writer.getContentData().toString());
    }
    // Set return status
    res.getWriter().write(writer.getContentData().toString());
    res.flushBuffer();
    if (logger.isDebugEnabled() == true) {
        logger.debug("UploadContentServlet done");
    }
}
Also used : Locale(java.util.Locale) StoreRef(org.alfresco.service.cmr.repository.StoreRef) QName(org.alfresco.service.namespace.QName) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) NodeService(org.alfresco.service.cmr.repository.NodeService) ContentCharsetFinder(org.alfresco.repo.content.encoding.ContentCharsetFinder) Charset(java.nio.charset.Charset) ContentService(org.alfresco.service.cmr.repository.ContentService) PermissionService(org.alfresco.service.cmr.security.PermissionService) NodeRef(org.alfresco.service.cmr.repository.NodeRef) StringTokenizer(java.util.StringTokenizer) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) ContentData(org.alfresco.service.cmr.repository.ContentData) BufferedInputStream(java.io.BufferedInputStream) MimetypeService(org.alfresco.service.cmr.repository.MimetypeService) ServiceRegistry(org.alfresco.service.ServiceRegistry)

Example 7 with MimetypeService

use of org.alfresco.service.cmr.repository.MimetypeService in project acs-community-packaging by Alfresco.

the class Repository method getMimeTypeForFile.

/**
 * Return the mimetype for the specified file, based on both the
 *  file name and the file's contents.
 * <p>
 * The file extension will be extracted from the filename and used
 *  along with the file contents to identify the mimetype.
 *
 * @param context       FacesContext
 * @param filename      Non-null filename to process
 * @param file          The File object (used to read the contents)
 *
 * @return mimetype for the specified filename - falls back to 'application/octet-stream' if not found.
 */
public static String getMimeTypeForFile(FacesContext context, String filename, File file) {
    String mimetype = MimetypeMap.MIMETYPE_BINARY;
    MimetypeService mimetypeService = (MimetypeService) getServiceRegistry(context).getMimetypeService();
    // Use the file contents if available
    if (file != null) {
        FileContentReader reader;
        try {
            reader = new FileContentReader(file);
            mimetype = mimetypeService.guessMimetype(filename, reader);
            return mimetype;
        } catch (Throwable t) {
            // Not terminal
            logger.warn("Error identifying mimetype from file contents ", t);
        }
    }
    // If the contents aren't available, go with the filename,
    // falling back to the Binary Mimetype if needed
    mimetype = mimetypeService.guessMimetype(filename);
    return mimetype;
}
Also used : FileContentReader(org.alfresco.repo.content.filestore.FileContentReader) MimetypeService(org.alfresco.service.cmr.repository.MimetypeService)

Example 8 with MimetypeService

use of org.alfresco.service.cmr.repository.MimetypeService in project acs-community-packaging by Alfresco.

the class MimeTypeConverter method getAsString.

/**
 * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
 */
public String getAsString(FacesContext context, UIComponent component, Object value) {
    String result = null;
    if (value instanceof String) {
        MimetypeService mimetypeService = Repository.getServiceRegistry(context).getMimetypeService();
        result = mimetypeService.getDisplaysByMimetype().get(value.toString());
    } else if (value != null) {
        result = value.toString();
    }
    return result;
}
Also used : MimetypeService(org.alfresco.service.cmr.repository.MimetypeService)

Example 9 with MimetypeService

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

MimetypeService (org.alfresco.service.cmr.repository.MimetypeService)9 ServiceRegistry (org.alfresco.service.ServiceRegistry)6 SelectItem (javax.faces.model.SelectItem)3 NodeService (org.alfresco.service.cmr.repository.NodeService)3 QName (org.alfresco.service.namespace.QName)3 QuickSort (org.alfresco.web.data.QuickSort)3 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 StringTokenizer (java.util.StringTokenizer)2 FileContentReader (org.alfresco.repo.content.filestore.FileContentReader)2 FileInfo (org.alfresco.service.cmr.model.FileInfo)2 ContentData (org.alfresco.service.cmr.repository.ContentData)2 ContentService (org.alfresco.service.cmr.repository.ContentService)2 NodeRef (org.alfresco.service.cmr.repository.NodeRef)2 StoreRef (org.alfresco.service.cmr.repository.StoreRef)2 BufferedInputStream (java.io.BufferedInputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 Serializable (java.io.Serializable)1 Writer (java.io.Writer)1