Example usage for javax.activation MimetypesFileTypeMap getContentType

List of usage examples for javax.activation MimetypesFileTypeMap getContentType

Introduction

In this page you can find the example usage for javax.activation MimetypesFileTypeMap getContentType.

Prototype

public synchronized String getContentType(String filename) 

Source Link

Document

Return the MIME type based on the specified file name.

Usage

From source file:org.craftercms.search.service.impl.SolrSearchService.java

@Override
public String updateDocument(String site, String id, File document, Map<String, String> additionalFields)
        throws SearchException {
    String finalId = site + ":" + id;
    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    String contentType = mimeTypesMap.getContentType(document.getName());

    ContentStreamUpdateRequest request = new ContentStreamUpdateRequest(SOLR_CONTENT_STREAM_UPDATE_URL);
    try {/*from  w ww. ja v a2 s  . co  m*/
        request.addFile(document, contentType);
        request.setParam(ExtractingParams.LITERALS_PREFIX + "id", finalId);
        request.setParam(ExtractingParams.LITERALS_PREFIX + solrDocumentBuilder.siteFieldName, site);
        request.setParam(ExtractingParams.LITERALS_PREFIX + "file-name", new File(finalId).getName());
        request.setParam(ExtractingParams.LITERALS_PREFIX + solrDocumentBuilder.localIdFieldName, id);

        if (MapUtils.isNotEmpty(additionalFields)) {
            request = solrDocumentBuilder.buildPartialUpdateDocument(request, additionalFields);
        }

        request.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);

        solrServer.request(request);
    } catch (SolrServerException e) {
        logger.warn("Error while communicating with Solr server to commit document: " + e.getMessage());
        try {

            SolrInputDocument inputDocument = new SolrInputDocument();
            inputDocument = solrDocumentBuilder.buildPartialUpdateDocument(inputDocument, additionalFields);
            // Add id and file name related metadata
            inputDocument.setField("id", finalId);
            inputDocument.setField(solrDocumentBuilder.siteFieldName, site);
            inputDocument.setField("file-name", new File(finalId).getName());
            inputDocument.setField(solrDocumentBuilder.localIdFieldName, id);
            UpdateResponse response = solrServer.add(inputDocument);
        } catch (IOException e1) {
            throw new SearchException("I/O error while committing document to Solr server " + e.getMessage(),
                    e1);
        } catch (SolrServerException e1) {
            throw new SearchException(
                    "Error while communicating with Solr server to commit document" + e1.getMessage(), e1);
        }

    } catch (IOException e) {
        throw new SearchException("I/O error while committing document to Solr server " + e.getMessage(), e);
    }

    return "Successfully updated '" + id + "'";

}

From source file:org.craftercms.studio.impl.repository.mongodb.services.impl.ContentServiceImpl.java

private Item nodeToItem(final Node newNode, String ticket, String site, final InputStream inputStream)
        throws RepositoryException {
    CoreMetadata core = newNode.getCore();
    Item item = new Item();
    item.setPath(pathService.getPathByItemId(ticket, site, newNode.getId()));
    item.setId(new ItemId(newNode.getId()));
    item.setLastModifiedDate(core.getLastModifiedDate());
    item.setModifiedBy(core.getCreator());
    item.setCreatedBy(core.getCreator());
    item.setCreationDate(core.getCreateDate());
    item.setFolder(nodeService.isNodeFolder(newNode));
    item.setModifiedBy(core.getModifier());
    item.setRepoId(newNode.getId());/*from   w  w  w.  j av  a2s.c o m*/
    item.setLabel(core.getLabel());
    item.setFileName(core.getNodeName());
    if (nodeService.isNodeFile(newNode)) {
        MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
        item.setMimeType(mimeTypesMap.getContentType(item.getFileName()));
    }
    item.setInputStream(inputStream);
    return item;
}

From source file:com.square.document.core.service.implementations.GedServiceImpl.java

@Override
public DocumentDto getDocumentByCriteres(CriteresRechercheDocumentDto criteres, String utilisateur) {
    if (criteres.getNumeroClient() == null || criteres.getNumeroClient().trim().isEmpty()) {
        throw new BusinessException(messageSourceUtil.get(GedKeyUtil.MESSAGE_ERROR_FILE_NUMBER_USER_REQUIRED));
    }/*w  w w .j  a  v a  2 s.com*/

    if (criteres.getIds() == null) {
        throw new BusinessException(messageSourceUtil.get(GedKeyUtil.MESSAGE_ERROR_FILE_NUMBER_USER_REQUIRED));
    } else {
        if (criteres.getIds().get(0) == null) {
            throw new BusinessException(
                    messageSourceUtil.get(GedKeyUtil.MESSAGE_ERROR_FILE_NUMBER_USER_REQUIRED));
        }
    }

    final Document document = documentDao.rechercherDocumentUniqueParCritere(criteres);
    final DocumentDto documentDto = mapperDozerBean.map(document, DocumentDto.class);
    final MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();

    documentDto.setTypeMime(mimeTypesMap.getContentType(documentDto.getNom()));

    final String cheminFichier = gedMappingService.getCheminRepertoire() + "/" + document.getNumClient() + "/"
            + document.getNom();
    try {
        final byte[] contenuPieceJointe = IOUtils.toByteArray(new FileInputStream(cheminFichier));
        documentDto.setContenu(contenuPieceJointe);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return documentDto;
}

From source file:com.cwctravel.jenkinsci.plugins.htmlresource.HTMLResourceManagement.java

private String determineContentType(StaplerRequest req) {
    String contentType = null;//from   www  . java 2  s. c  o m
    String resourcePath = req.getPathInfo();
    int lastIndexOfDot = resourcePath.lastIndexOf('.');
    String extension = resourcePath.substring(lastIndexOfDot);
    if (".css".equals(extension)) {
        contentType = "text/css";
    } else if (".js".equals(extension)) {
        contentType = "application/x-javascript";
    } else if (".png".equals(extension)) {
        contentType = "image/png";
    } else if (".gif".equals(extension)) {
        contentType = "image/gif";
    } else {
        MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
        contentType = mimeTypesMap.getContentType(resourcePath);
    }

    return contentType;
}

From source file:edu.ku.brc.util.thumbnails.Thumbnailer.java

/**
  * Generates a thumbnail for the given original.
  * /*from  w  w w . j  av  a 2s.c  o m*/
 * @param originalFile the original
 * @param outputFile the output file for the generated thumbnail
 * @throws IOException an exception occured while generating the thumbnail or no generator was registered for the given MIME type
 */
public void generateThumbnail(final String originalFile, final String outputFile, final boolean doHighQuality)
        throws IOException {
    // get the system MIME type mapper
    MimetypesFileTypeMap mimeMap = AttachmentUtils.getMimeMap();

    // get the MIME type of the given original file
    String mimeType = mimeMap.getContentType(originalFile);

    String iconName = null;

    String ext = FilenameUtils.getExtension(originalFile);
    if (!mimeType.startsWith("image/") && StringUtils.isNotEmpty(ext)) {
        iconName = availableIcons.get(ext);
    }

    if (iconName == null) {
        // find the appropriate thumbnail generator, if any
        ThumbnailGeneratorIFace generator = mimeTypeToGeneratorMap.get(mimeType);
        if (generator != null) {
            if (generator.generateThumbnail(originalFile, outputFile, doHighQuality)) {
                return;
            }
            UIRegistry.getStatusBar().setLocalizedText("Thumbnailer.THMB_NO_CREATE", originalFile);
            iconName = fallbackIcons.get(ext);
        }
    }

    if (StringUtils.isEmpty(iconName)) {
        iconName = "unknown";
    }

    IconEntry entry = IconManager.getIconEntryByName(iconName);
    if (entry != null) {
        BufferedImage bi = ImageIO.read(entry.getUrl());
        ImageIO.write(bi, "PNG", new FileOutputStream(outputFile));
    }
}

From source file:org.chililog.server.workbench.StaticFileRequestHandler.java

/**
 * Sets the content type header for the HTTP Response
 * //from  w  w  w . j a v a2 s .  co  m
 * @param response
 *            HTTP response
 * @param file
 *            file to extract content type
 */
private void setContentTypeHeader(HttpResponse response, File file) {
    String mimeType = null;
    String filePath = file.getPath();

    int idx = filePath.lastIndexOf('.');
    if (idx == -1) {
        mimeType = "application/octet-stream";
    } else {
        String fileExtension = filePath.substring(idx).toLowerCase();

        // Try common types first
        if (fileExtension.equals(".html")) {
            mimeType = "text/html";
        } else if (fileExtension.equals(".css")) {
            mimeType = "text/css";
        } else if (fileExtension.equals(".js")) {
            mimeType = "application/javascript";
        } else if (fileExtension.equals(".gif")) {
            mimeType = "image/gif";
        } else if (fileExtension.equals(".png")) {
            mimeType = "image/png";
        } else if (fileExtension.equals(".txt")) {
            mimeType = "text/plain";
        } else if (fileExtension.equals(".xml")) {
            mimeType = "application/xml";
        } else if (fileExtension.equals(".json")) {
            mimeType = "application/json";
        } else {
            MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
            mimeType = mimeTypesMap.getContentType(file.getPath());
        }
    }

    response.setHeader(HttpHeaders.Names.CONTENT_TYPE, mimeType);
}

From source file:com.liferay.sync.engine.lan.server.file.LanFileServerHandler.java

protected void sendFile(final ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest,
        SyncFile syncFile) throws Exception {

    Path path = Paths.get(syncFile.getFilePathName());

    if (Files.notExists(path)) {
        _syncTrafficShapingHandler.decrementConnectionsCount();

        if (_logger.isTraceEnabled()) {
            Channel channel = channelHandlerContext.channel();

            _logger.trace("Client {}: file not found {}", channel.remoteAddress(), path);
        }//  w ww .  java  2s.  com

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    if (_logger.isDebugEnabled()) {
        Channel channel = channelHandlerContext.channel();

        _logger.debug("Client {}: sending file {}", channel.remoteAddress(), path);
    }

    long modifiedTime = syncFile.getModifiedTime();
    long previousModifiedTime = syncFile.getPreviousModifiedTime();

    if (OSDetector.isApple()) {
        modifiedTime = modifiedTime / 1000 * 1000;
        previousModifiedTime = previousModifiedTime / 1000 * 1000;
    }

    FileTime currentFileTime = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);

    long currentTime = currentFileTime.toMillis();

    if ((currentTime != modifiedTime) && (currentTime != previousModifiedTime)) {

        _syncTrafficShapingHandler.decrementConnectionsCount();

        Channel channel = channelHandlerContext.channel();

        _logger.error(
                "Client {}: file modified {}, currentTime {}, modifiedTime " + "{}, previousModifiedTime {}",
                channel.remoteAddress(), path, currentTime, modifiedTime, previousModifiedTime);

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK);

    long size = Files.size(path);

    HttpUtil.setContentLength(httpResponse, size);

    HttpHeaders httpHeaders = httpResponse.headers();

    MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();

    httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType(syncFile.getName()));

    if (HttpUtil.isKeepAlive(fullHttpRequest)) {
        httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    channelHandlerContext.write(httpResponse);

    SyncChunkedFile syncChunkedFile = new SyncChunkedFile(path, size, 4 * 1024 * 1024, currentTime);

    ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(new HttpChunkedInput(syncChunkedFile),
            channelHandlerContext.newProgressivePromise());

    channelFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {

            _syncTrafficShapingHandler.decrementConnectionsCount();

            if (channelFuture.isSuccess()) {
                return;
            }

            Throwable exception = channelFuture.cause();

            Channel channel = channelHandlerContext.channel();

            _logger.error("Client {}: {}", channel.remoteAddress(), exception.getMessage(), exception);

            channelHandlerContext.close();
        }

    });

    if (!HttpUtil.isKeepAlive(fullHttpRequest)) {
        channelFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:eu.planets_project.tb.gui.backing.data.DigitalObjectTreeNode.java

/**
 * @return//  w w  w  .jav a2 s .  c om
 */
public String getMimeType() {
    String mimetype = null;

    // Lookup in this:
    MimetypesFileTypeMap mimeMap = new MimetypesFileTypeMap();
    // Ensure the image/png mapping is present, as it appears to be broken in Java 6
    // See http://furiouspurpose.blogspot.com/2009/01/what-does-java-6-have-against-imagepng.html
    mimeMap.addMimeTypes("image/png png");

    // Based only on URI:
    if (getUri() != null)
        mimetype = mimeMap.getContentType(getUri().getPath());

    // Return this if it worked.
    if (mimetype != null)
        return mimetype;

    // Otherwise, inspect content of the Digital Object: Title:
    if (getDob() != null && getDob().getTitle() != null)
        mimetype = mimeMap.getContentType(getDob().getTitle());

    return mimetype;
}

From source file:com.hr_scaffold.fileservice.FileService.java

/**
 * *****************************************************************************
 * NAME: listFiles//from  w ww. j  av  a2 s  .c o  m
 * DESCRIPTION:
 * Returns a description of every file in the uploadDir.
 * RETURNS array of inner class WMFile (defined above)
 * ******************************************************************************
 */
public WMFile[] listFiles(HttpServletRequest httpServletRequest) throws IOException {
    MimetypesFileTypeMap m = new MimetypesFileTypeMap();
    File[] files = fileServiceManager.listFiles(uploadDirectory);

    /* Iterate over every file, creating a WMFile object to be returned */
    WMFile[] result = new WMFile[files.length];
    for (int i = 0; i < files.length; i++) {
        String filteredPath = WMRuntimeUtils.getContextRelativePath(files[i], httpServletRequest);
        result[i] = new WMFile(filteredPath, files[i].getName(), files[i].length(), m.getContentType(files[i]));
    }
    return result;
}

From source file:com.all_widgets.fileservice.FileService.java

/**
 * *****************************************************************************
 * NAME: listFiles//from   w w  w  .ja  v a2  s.c  o  m
 * DESCRIPTION:
 * Returns a description of every file in the uploadDir.
 * RETURNS array of inner class WMFile (defined above)
 * ******************************************************************************
 */
public WMFile[] listFiles(HttpServletRequest httpServletRequest, String relativePath) throws IOException {
    MimetypesFileTypeMap m = new MimetypesFileTypeMap();
    File[] files = fileServiceManager
            .listFiles(relativePath == null ? uploadDirectory : new File(uploadDirectory, relativePath));

    /* Iterate over every file, creating a WMFile object to be returned */
    WMFile[] result = new WMFile[files.length];
    for (int i = 0; i < files.length; i++) {
        String filteredPath = WMRuntimeUtils.getContextRelativePath(files[i], httpServletRequest, relativePath);
        result[i] = new WMFile(filteredPath, files[i].getName(), files[i].length(), m.getContentType(files[i]));
    }
    return result;
}