org.alfresco.service.cmr.repository.MimetypeService

Here are the examples of the java api class org.alfresco.service.cmr.repository.MimetypeService taken from open source projects.

1. UIMimeTypeSelector#createList()

Project: community-edition
File: UIMimeTypeSelector.java
/**
    * Creates the list of SelectItem components to represent the list
    * of MIME types the user can select from
    * 
    * @return List of SelectItem components
    */
protected List<SelectItem> createList() {
    List<SelectItem> items = new ArrayList<SelectItem>(80);
    ServiceRegistry registry = Repository.getServiceRegistry(FacesContext.getCurrentInstance());
    MimetypeService mimetypeService = registry.getMimetypeService();
    // get the mime type display names
    Map<String, String> mimeTypes = mimetypeService.getDisplaysByMimetype();
    for (String mimeType : mimeTypes.keySet()) {
        items.add(new SelectItem(mimeType, mimeTypes.get(mimeType)));
    }
    // make sure the list is sorted by the values
    QuickSort sorter = new QuickSort(items, "label", true, IDataContainer.SORT_CASEINSENSITIVE);
    sorter.sort();
    return items;
}

2. Repository#getMimeTypeForFile()

Project: community-edition
File: Repository.java
/**
    * 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) {
            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;
}

3. BaseContentWizard#getSummaryMimeType()

Project: community-edition
File: BaseContentWizard.java
/**
    * Returns the display label for the mime type currently chosen
    * 
    * @param mimeType The mime type to get the display label of 
    * @return The human readable version of the content type
    */
protected String getSummaryMimeType(String mimeType) {
    ServiceRegistry registry = Repository.getServiceRegistry(FacesContext.getCurrentInstance());
    MimetypeService mimetypeService = registry.getMimetypeService();
    // get the mime type display name
    Map<String, String> mimeTypes = mimetypeService.getDisplaysByMimetype();
    return mimeTypes.get(mimeType);
}

4. UploadContentServlet#doPut()

Project: community-edition
File: UploadContentServlet.java
/**
     * @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");
    }
}

5. VirtualFileFolderServiceExtensionTest#addWildCardInName()

Project: community-edition
File: VirtualFileFolderServiceExtensionTest.java
private String addWildCardInName(String name, String mimetype) {
    MimetypeService mimetypeService = ctx.getBean("mimetypeService", MimetypeService.class);
    String extension = mimetypeService.getExtension(mimetype);
    return name.substring(0, name.length() - (extension.length() + 1)).concat("*." + extension);
}

6. AbstractContentTransformerLimitsTest#setUp()

Project: community-edition
File: AbstractContentTransformerLimitsTest.java
@Before
public void setUp() throws Exception {
    ApplicationContext ctx = ContentMinimalContextTestSuite.getContext();
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    MimetypeService mimetypeService = serviceRegistry.getMimetypeService();
    TransformerDebug transformerDebug = (TransformerDebug) ctx.getBean("transformerDebug");
    TransformerConfig transformerConfig = (TransformerConfig) ctx.getBean("transformerConfig");
    transformer = new AbstractContentTransformer2() {

        @Override
        public boolean isTransformableMimetype(String sourceMimetype, String targetMimetype, TransformationOptions options) {
            return false;
        }

        @Override
        protected void transformInternal(ContentReader reader, ContentWriter writer, TransformationOptions options) throws Exception {
        }
    };
    transformer.setMimetypeService(mimetypeService);
    transformer.setTransformerDebug(transformerDebug);
    transformer.setTransformerConfig(transformerConfig);
    transformer.setBeanName("transformer.test" + System.currentTimeMillis() % 100000);
    limits = new TransformationOptionLimits();
    options = new TransformationOptions();
}

7. TransformActionExecuterTest#transformName()

Project: community-edition
File: TransformActionExecuterTest.java
@Test
public void transformName() throws Exception {
    MimetypeService dummyMimetypeService = new DummyMimetypeService("txt");
    // Case 1. A simple name with a reasonable extension.
    String original = "Letter to Bank Manager.doc";
    final String newMimetype = MimetypeMap.MIMETYPE_TEXT_PLAIN;
    String newName = TransformActionExecuter.transformName(dummyMimetypeService, original, newMimetype, true);
    assertEquals("Letter to Bank Manager.txt", newName);
    // Case 2. String after '.' is clearly not an extension
    original = "No.1 - First Document Title";
    newName = TransformActionExecuter.transformName(dummyMimetypeService, original, newMimetype, true);
    assertEquals(original + ".txt", newName);
    // Case 2b. String after '.' is clearly not an extension. Don't always add
    original = "No.1 - First Document Title";
    newName = TransformActionExecuter.transformName(dummyMimetypeService, original, newMimetype, false);
    assertEquals(original, newName);
    // Case 3. A name with no extension
    original = "Letter to Bank Manager";
    newName = TransformActionExecuter.transformName(dummyMimetypeService, original, newMimetype, true);
    assertEquals(original + ".txt", newName);
    // Case 3b. A name with no extension. Don't always add
    original = "Letter to Bank Manager";
    newName = TransformActionExecuter.transformName(dummyMimetypeService, original, newMimetype, false);
    assertEquals(original, newName);
    // Case 4. A name ending in a dot
    original = "Letter to Bank Manager.";
    newName = TransformActionExecuter.transformName(dummyMimetypeService, original, newMimetype, true);
    assertEquals(original + "txt", newName);
    // Case 4b. A name ending in a dot. Don't always add
    original = "Letter to Bank Manager.";
    newName = TransformActionExecuter.transformName(dummyMimetypeService, original, newMimetype, false);
    assertEquals(original, newName);
    // Case 5. Unknown mime type
    original = "Letter to Bank Manager.txt";
    final String unknownMimetype = "Marcel/Marceau";
    // The real MimetypeService returns a 'bin' extension for unknown mime types.
    dummyMimetypeService = new DummyMimetypeService("bin");
    newName = TransformActionExecuter.transformName(dummyMimetypeService, original, unknownMimetype, true);
    assertEquals("Letter to Bank Manager.bin", newName);
}

8. Export#execute()

Project: community-edition
File: Export.java
/* (non-Javadoc)
     * @see org.alfresco.tools.Tool#execute()
     */
@Override
protected /*package*/
int execute() throws ToolException {
    ExporterService exporter = getServiceRegistry().getExporterService();
    MimetypeService mimetypeService = getServiceRegistry().getMimetypeService();
    // create export package handler
    ExportPackageHandler exportHandler = null;
    if (context.zipped) {
        exportHandler = new ZipHandler(context.getDestDir(), context.getZipFile(), context.getPackageFile(), context.getPackageDir(), context.overwrite, mimetypeService);
    } else {
        exportHandler = new FileHandler(context.getDestDir(), context.getPackageFile(), context.getPackageDir(), context.overwrite, mimetypeService);
    }
    // export Repository content to export package
    ExporterCrawlerParameters parameters = new ExporterCrawlerParameters();
    parameters.setExportFrom(context.getLocation());
    parameters.setCrawlSelf(context.self);
    parameters.setCrawlChildNodes(context.children);
    try {
        exporter.exportView(exportHandler, parameters, new ExportProgress());
    } catch (ExporterException e) {
        throw new ToolException("Failed to export", e);
    }
    return 0;
}

9. OOoContentTransformerHelper#transform()

Project: community-edition
File: OOoContentTransformerHelper.java
public void transform(ContentReader reader, ContentWriter writer, TransformationOptions options) throws Exception {
    if (isAvailable() == false) {
        throw new ContentIOException("Content conversion failed (unavailable): \n" + "   reader: " + reader + "\n" + "   writer: " + writer);
    }
    if (getLogger().isDebugEnabled()) {
        StringBuilder msg = new StringBuilder();
        msg.append("transforming content from ").append(reader.getMimetype()).append(" to ").append(writer.getMimetype());
        getLogger().debug(msg.toString());
    }
    String sourceMimetype = getMimetype(reader);
    String targetMimetype = getMimetype(writer);
    MimetypeService mimetypeService = getMimetypeService();
    String sourceExtension = mimetypeService.getExtension(sourceMimetype);
    String targetExtension = mimetypeService.getExtension(targetMimetype);
    // query the registry for the source format
    DocumentFormat sourceFormat = formatRegistry.getFormatByFileExtension(sourceExtension);
    if (sourceFormat == null) {
        // source format is not recognised
        throw new ContentIOException("No OpenOffice document format for source extension: " + sourceExtension);
    }
    // query the registry for the target format
    DocumentFormat targetFormat = formatRegistry.getFormatByFileExtension(targetExtension);
    if (targetFormat == null) {
        // target format is not recognised
        throw new ContentIOException("No OpenOffice document format for target extension: " + targetExtension);
    }
    // get the family of the target document
    DocumentFamily sourceFamily = sourceFormat.getFamily();
    // does the format support the conversion
    if (!targetFormat.isExportableFrom(sourceFamily)) {
        throw new ContentIOException("OpenOffice conversion not supported: \n" + "   reader: " + reader + "\n" + "   writer: " + writer);
    }
    // MNT-11279 fix. Because of the creating temp files for transformations the document's header with file name field
    // could be changed to temporary file's name.
    // Get the original file name which was on upload.
    String origFileName = getOriginalFileName(options);
    if (origFileName == null) {
        origFileName = "TemporaryFile-" + GUID.generate();
    }
    // Create a temp folder and put source and target files into it. (i.e. tempFromFile and tempToFile will be placed
    // into such folder)
    File tempSubfolder = new File(TempFileProvider.getTempDir() + File.separator + origFileName + "-" + getTempFilePrefix() + "-" + getTempFilePrefix() + "-" + new Date().getTime());
    tempSubfolder.mkdir();
    // create temporary files to convert from and to
    // The source file should have the name which was on upload
    File tempFromFile = new File(tempSubfolder, origFileName);
    File tempToFile = TempFileProvider.createTempFile(origFileName + "-" + getTempFilePrefix() + "-target-", "." + targetExtension, tempSubfolder);
    // There is a bug (reported in ALF-219) whereby JooConverter (the Alfresco Community Edition's 3rd party
    // OpenOffice connector library) struggles to handle zero-size files being transformed to pdf.
    // For zero-length .html files, it throws NullPointerExceptions.
    // For zero-length .txt files, it produces a pdf transformation, but it is not a conformant
    // pdf file and cannot be viewed (contains no pages).
    //
    // For these reasons, if the file is of zero length, we will not use JooConverter & OpenOffice
    // and will instead ask Apache PDFBox to produce an empty pdf file for us.
    final long documentSize = reader.getSize();
    if (documentSize == 0L || temporaryMsFile(options)) {
        produceEmptyPdfFile(tempToFile);
    } else {
        // download the content from the source reader
        saveContentInFile(sourceMimetype, reader, tempFromFile);
        // it is preferred over PDFBox.
        try {
            convert(tempFromFile, sourceFormat, tempToFile, targetFormat);
        } catch (OpenOfficeException e) {
            throw new ContentIOException("OpenOffice server conversion failed: \n" + "   reader: " + reader + "\n" + "   writer: " + writer + "\n" + "   from file: " + tempFromFile + "\n" + "   to file: " + tempToFile, e);
        } catch (Throwable throwable) {
            if (throwable.getCause() instanceof ErrorCodeIOException && ((ErrorCodeIOException) throwable.getCause()).ErrCode == JODCONVERTER_TRANSFORMATION_ERROR_CODE) {
                getLogger().warn("Transformation failed: \n" + "from file: " + tempFromFile + "\n" + "to file: " + tempToFile + "Source file " + tempFromFile + " has no content");
                produceEmptyPdfFile(tempToFile);
            } else {
                throw throwable;
            }
        }
    }
    if (getLogger().isDebugEnabled()) {
        StringBuilder msg = new StringBuilder();
        msg.append("transforming ").append(tempFromFile.getName()).append(" to ").append(tempToFile.getName());
        getLogger().debug(msg.toString());
    }
    // upload the temp output to the writer given us
    writer.putContent(tempToFile);
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("transformation successful");
    }
}

10. OOoContentTransformerHelper#isTransformable()

Project: community-edition
File: OOoContentTransformerHelper.java
/**
     * @see DocumentFormatRegistry
     */
public boolean isTransformable(String sourceMimetype, String targetMimetype, TransformationOptions options) {
    // Use BinaryPassThroughContentTransformer if mimetypes are the same.
    if (sourceMimetype.equals(targetMimetype)) {
        return false;
    }
    if (!isAvailable()) {
        // The connection management is must take care of this
        return false;
    }
    if (isTransformationBlocked(sourceMimetype, targetMimetype)) {
        if (getLogger().isDebugEnabled()) {
            StringBuilder msg = new StringBuilder();
            msg.append("Transformation from ").append(sourceMimetype).append(" to ").append(targetMimetype).append(" is blocked and therefore unavailable.");
            getLogger().debug(msg.toString());
        }
        return false;
    }
    MimetypeService mimetypeService = getMimetypeService();
    String sourceExtension = mimetypeService.getExtension(sourceMimetype);
    String targetExtension = mimetypeService.getExtension(targetMimetype);
    // query the registry for the source format
    DocumentFormat sourceFormat = formatRegistry.getFormatByFileExtension(sourceExtension);
    if (sourceFormat == null) {
        // no document format
        return false;
    }
    // query the registry for the target format
    DocumentFormat targetFormat = formatRegistry.getFormatByFileExtension(targetExtension);
    if (targetFormat == null) {
        // no document format
        return false;
    }
    // get the family of the target document
    DocumentFamily sourceFamily = sourceFormat.getFamily();
    // does the format support the conversion
    if (!targetFormat.isExportableFrom(sourceFamily)) {
        // unable to export from source family of documents to the target format
        return false;
    } else {
        return true;
    }
}

11. AbstractImageMagickContentTransformerWorker#transform()

Project: community-edition
File: AbstractImageMagickContentTransformerWorker.java
/**
     * @see #transformInternal(File, String, File, String, TransformationOptions)
     */
public final void transform(ContentReader reader, ContentWriter writer, TransformationOptions options) throws Exception {
    // get mimetypes
    String sourceMimetype = getMimetype(reader);
    String targetMimetype = getMimetype(writer);
    // get the extensions to use
    MimetypeService mimetypeService = getMimetypeService();
    String sourceExtension = mimetypeService.getExtension(sourceMimetype);
    String targetExtension = mimetypeService.getExtension(targetMimetype);
    if (sourceExtension == null || targetExtension == null) {
        throw new AlfrescoRuntimeException("Unknown extensions for mimetypes: \n" + "   source mimetype: " + sourceMimetype + "\n" + "   source extension: " + sourceExtension + "\n" + "   target mimetype: " + targetMimetype + "\n" + "   target extension: " + targetExtension);
    }
    // create required temp files
    File sourceFile = TempFileProvider.createTempFile(getClass().getSimpleName() + "_source_", "." + sourceExtension);
    File targetFile = TempFileProvider.createTempFile(getClass().getSimpleName() + "_target_", "." + targetExtension);
    // pull reader file into source temp file
    reader.getContent(sourceFile);
    // For most target mimetypes, it only makes sense to read the first page of the
    // source, as the target is a single page, so set the pageLimit automatically.
    // However for others, such as PDF (see ALF-7278) all pages should be read.
    // transform the source temp file to the target temp file
    transformInternal(sourceFile, sourceMimetype, targetFile, targetMimetype, options);
    // check that the file was created
    if (!targetFile.exists() || targetFile.length() == 0) {
        throw new ContentIOException("JMagick transformation failed to write output file");
    }
    // upload the output image
    writer.putContent(targetFile);
    // done
    if (logger.isDebugEnabled()) {
        logger.debug("Transformation completed: \n" + "   source: " + reader + "\n" + "   target: " + writer + "\n" + "   options: " + options);
    }
}