Example usage for javax.activation MimetypesFileTypeMap MimetypesFileTypeMap

List of usage examples for javax.activation MimetypesFileTypeMap MimetypesFileTypeMap

Introduction

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

Prototype

public MimetypesFileTypeMap() 

Source Link

Document

The default constructor.

Usage

From source file:com.qcadoo.model.internal.file.FileServiceImpl.java

@Override
public String getContentType(final String path) {
    return new MimetypesFileTypeMap().getContentType(new File(path));
}

From source file:eu.openanalytics.rsb.component.DirectoryDepositHandler.java

public void handleJob(final Message<File> message) throws IOException {
    final DepositDirectoryConfiguration depositDirectoryConfiguration = message.getHeaders()
            .get(DIRECTORY_CONFIG_HEADER_NAME, DepositDirectoryConfiguration.class);

    final String applicationName = depositDirectoryConfiguration.getApplicationName();
    final File dataFile = message.getPayload();

    final File depositRootDirectory = dataFile.getParentFile().getParentFile();
    final File acceptedDirectory = new File(depositRootDirectory, Configuration.DEPOSIT_ACCEPTED_SUBDIR);

    final File acceptedFile = new File(acceptedDirectory, dataFile.getName());
    FileUtils.deleteQuietly(acceptedFile); // in case a similar job already
                                           // exists
    FileUtils.moveFile(dataFile, acceptedFile);

    final Map<String, Serializable> meta = new HashMap<String, Serializable>();
    meta.put(DEPOSIT_ROOT_DIRECTORY_META_NAME, depositRootDirectory);
    meta.put(ORIGINAL_FILENAME_META_NAME, dataFile.getName());
    meta.put(INBOX_DIRECTORY_META_NAME, dataFile.getParent());

    final MultiFilesJob job = new MultiFilesJob(Source.DIRECTORY, applicationName, getUserName(),
            UUID.randomUUID(), (GregorianCalendar) GregorianCalendar.getInstance(), meta);

    try {/*  w w w . j a v a 2  s . c om*/
        if (FilenameUtils.isExtension(acceptedFile.getName().toLowerCase(), "zip")) {
            MultiFilesJob.addZipFilesToJob(new FileInputStream(acceptedFile), job);
        } else {
            MultiFilesJob.addDataToJob(new MimetypesFileTypeMap().getContentType(acceptedFile),
                    acceptedFile.getName(), new FileInputStream(acceptedFile), job);
        }

        final String jobConfigurationFileName = depositDirectoryConfiguration.getJobConfigurationFileName();

        if (StringUtils.isNotBlank(jobConfigurationFileName)) {
            final File jobConfigurationFile = getJobConfigurationFile(applicationName,
                    jobConfigurationFileName);

            job.addFile(Constants.MULTIPLE_FILES_JOB_CONFIGURATION, new FileInputStream(jobConfigurationFile));
        }

        getMessageDispatcher().dispatch(job);
    } catch (final Exception e) {
        final MultiFilesResult errorResult = job.buildErrorResult(e, getMessages());
        handleResult(errorResult);
    }
}

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

/**
 * *****************************************************************************
 * NAME: listFiles/* www  .j  a va2  s . co  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/*www.ja v a  2 s.  co  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;
}

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));
    }/*from w  w w .j a v  a 2s.  c om*/

    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:org.apache.stratos.manager.services.mgt.util.Util.java

/**
 * Currently this is not used, as the icons are loaded from the webapps
 * /*w w  w  .ja v a  2s  . c  o m*/
 * @throws Exception
 */
public static void loadServiceIcons() throws Exception {
    String serviceIconDirLocation = CarbonUtils.getCarbonHome() + "/resources/cloud-service-icons";
    File serviceIconDirDir = new File(serviceIconDirLocation);
    UserRegistry registry = getTenantZeroSystemGovernanceRegistry();
    try {
        // adding the common media types
        Map<String, String> extensionToMediaTypeMap = new HashMap<String, String>();
        extensionToMediaTypeMap.put("gif", "img/gif");
        extensionToMediaTypeMap.put("jpg", "img/gif");
        extensionToMediaTypeMap.put("png", "img/png");

        File[] filesAndDirs = serviceIconDirDir.listFiles();
        if (filesAndDirs == null) {
            return;
        }
        List<File> filesDirs = Arrays.asList(filesAndDirs);

        for (File file : filesDirs) {
            String filename = file.getName();
            String fileRegistryPath = Constants.CLOUD_SERVICE_ICONS_STORE_PATH
                    + RegistryConstants.PATH_SEPARATOR + filename;

            // Add the file to registry
            Resource newResource = registry.newResource();
            String mediaType = null;
            if (filename.contains(".")) {
                String fileExt = filename.substring(filename.lastIndexOf(".") + 1);
                mediaType = extensionToMediaTypeMap.get(fileExt.toLowerCase());
            }
            if (mediaType == null) {
                mediaType = new MimetypesFileTypeMap().getContentType(file);
            }
            newResource.setMediaType(mediaType);
            newResource.setContentStream(new FileInputStream(file));
            registry.put(fileRegistryPath, newResource);
        }
    } catch (Exception e) {
        String msg = "Error loading icons to the system registry for registry path: "
                + Constants.CLOUD_SERVICE_ICONS_STORE_PATH;
        log.error(msg, e);
        throw new Exception(msg, e);
    }

    try {
        CommonUtil.setAnonAuthorization(
                RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + Constants.CLOUD_SERVICE_ICONS_STORE_PATH,
                registry.getUserRealm());
    } catch (RegistryException e) {
        String msg = "Setting the annon access enabled for the services icons paths.";
        log.error(msg, e);
        throw new Exception(msg, e);
    }

}

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 w  w  . j  ava2 s .  c  om
        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:com.devbliss.doctest.LogicDocTest.java

protected ApiResponse makePostUploadRequest(URI uri, File fileToUpload, String paramName,
        Map<String, String> additionalHeaders) throws Exception {
    FileBody fileBodyToUpload = new FileBody(fileToUpload);
    String mimeType = new MimetypesFileTypeMap().getContentType(fileToUpload);

    Context context = apiTest.post(uri, null, new PostUploadWithoutRedirectImpl(paramName, fileBodyToUpload),
            additionalHeaders);/*from  w ww.j a  va  2s .  c  om*/

    docTestMachine.sayUploadRequest(context.apiRequest, fileBodyToUpload.getFilename(),
            fileHelper.readFile(fileToUpload), fileToUpload.length(), mimeType, headersToShow, cookiesToShow);

    docTestMachine.sayResponse(context.apiResponse, headersToShow);

    return context.apiResponse;
}

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

private String determineContentType(StaplerRequest req) {
    String contentType = null;//from www .  ja  v a 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:de.mprengemann.intellij.plugin.androidicons.forms.AndroidBatchScaleImporter.java

private void addImageFiles(File file) {
    if (file == null) {
        return;/*w  ww .ja  v a 2  s .c o m*/
    }

    if (!file.isDirectory()) {
        ImageInformation item = parseImageInformation(file);
        if (item != null) {
            tableModel.addItem(item);
        }
    } else {
        File[] files = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                if (file.isDirectory()) {
                    return true;
                }
                String mimetype = new MimetypesFileTypeMap().getContentType(file);
                String type = mimetype.split("/")[0];
                return type.equals("image");
            }
        });

        for (File foundFile : files) {
            addImageFiles(foundFile);
        }
    }
}