Example usage for java.nio.file Files probeContentType

List of usage examples for java.nio.file Files probeContentType

Introduction

In this page you can find the example usage for java.nio.file Files probeContentType.

Prototype

public static String probeContentType(Path path) throws IOException 

Source Link

Document

Probes the content type of a file.

Usage

From source file:org.opencb.opencga.catalog.utils.BioformatDetector.java

public static File.Bioformat detect(URI uri, File.Format format, File.Compression compression) {
    String path = uri.getPath();/*from  www  .  jav a2s  . c o  m*/
    Path source = Paths.get(uri);
    String mimeType;

    try {
        switch (format) {
        case VCF:
        case GVCF:
        case BCF:
            return File.Bioformat.VARIANT;
        case TBI:
            break;
        case SAM:
        case BAM:
        case CRAM:
            return File.Bioformat.ALIGNMENT;
        case BAI:
            return File.Bioformat.NONE; //TODO: Alignment?
        case FASTQ:
            return File.Bioformat.SEQUENCE;
        case PED:
            return File.Bioformat.PEDIGREE;
        case TAB_SEPARATED_VALUES:
            break;
        case COMMA_SEPARATED_VALUES:
            break;
        case PROTOCOL_BUFFER:
            break;
        case PLAIN:
            break;
        case JSON:
        case AVRO:
            String file;
            if (compression != File.Compression.NONE) {
                file = com.google.common.io.Files.getNameWithoutExtension(uri.getPath()); //Remove compression extension
                file = com.google.common.io.Files.getNameWithoutExtension(file); //Remove format extension
            } else {
                file = com.google.common.io.Files.getNameWithoutExtension(uri.getPath()); //Remove format extension
            }

            if (file.endsWith("variants")) {
                return File.Bioformat.VARIANT;
            } else if (file.endsWith("alignments")) {
                return File.Bioformat.ALIGNMENT;
            }
            break;
        case PARQUET:
            break;
        case IMAGE:
        case BINARY:
        case EXECUTABLE:
        case UNKNOWN:
        case XML:
            return File.Bioformat.NONE;
        default:
            break;
        }

        //            for (Map.Entry<File.Bioformat, Pattern> entry : bioformatMap.entrySet()) {
        //                if (entry.getValue().matcher(path).matches()) {
        //                    return entry.getKey();
        //                }
        //            }

        mimeType = Files.probeContentType(source);

        if (path.endsWith(".nw")) {
            return File.Bioformat.OTHER_NEWICK;
        }

        if (mimeType == null || !mimeType.equalsIgnoreCase("text/plain") || path.endsWith(".redirection")
                || path.endsWith(".Rout") || path.endsWith("cel_files.txt") || !path.endsWith(".txt")) {
            return File.Bioformat.NONE;
        }

        FileInputStream fstream = new FileInputStream(path);
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        String strLine;
        int numberOfLines = 20;

        int i = 0;
        boolean names = false;
        while ((strLine = br.readLine()) != null) {
            if (strLine.equalsIgnoreCase("")) {
                continue;
            }
            if (i == numberOfLines) {
                break;
            }
            if (strLine.startsWith("#")) {
                if (strLine.startsWith("#NAMES")) {
                    names = true;
                } else {
                    continue;
                }
            } else {
                String[] fields = strLine.split("\t");
                if (fields.length > 2) {
                    if (names && NumberUtils.isNumber(fields[1])) {
                        return File.Bioformat.DATAMATRIX_EXPRESSION;
                    }
                } else if (fields.length == 1) {
                    if (fields[0].split(" ").length == 1 && !NumberUtils.isNumber(fields[0])) {
                        return File.Bioformat.IDLIST;
                    }
                } else if (fields.length == 2) {
                    if (!fields[0].contains(" ") && NumberUtils.isNumber(fields[1])) {
                        return File.Bioformat.IDLIST_RANKED;
                    }
                }
            }
            i++;
        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return File.Bioformat.NONE;
}

From source file:de.inren.service.picture.PictureModificationServiceImpl.java

public void initPictureModificationService() {
    Application.get().getSharedResources().add(PictureResource.PICTURE_RESOURCE, new PictureResource());
    final File file = storehouseService.getDataFile(PictureModificationService.FILE_NOT_FOUND_DIGEST);
    if (!file.exists()) {
        InputStream is = PictureModificationServiceImpl.class
                .getResourceAsStream(PictureModificationService.FILE_NOT_FOUND_NAME);
        final Hex hex = new Hex();
        byte[] md5sum;
        md5sum = (byte[]) hex.decode(PictureModificationService.FILE_NOT_FOUND_DIGEST);
        // prescale to thumbnail, also test for converter
        storehouseService.doImport(is, md5sum);
        File thumbFile = getThumbnailImage(PictureModificationService.FILE_NOT_FOUND_DIGEST);
        log.info("picture modification service \"File not found\" image imported");
        try {/*from  ww  w. j  a  v a  2  s.co m*/
            log.info("Mimetype of " + thumbFile.getName() + " is " + Files.probeContentType(file.toPath()));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

    } else {
        try {
            log.info("Mimetype of " + PictureModificationService.FILE_NOT_FOUND_NAME + " is "
                    + Files.probeContentType(file.toPath()));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}

From source file:edu.si.services.sidora.rest.batch.MimeTypeTest.java

@Test
public void mimeTypeDetectionComparison() throws IOException {
    File path = new File("src/test/resources/test-data/mimetype-test-files");

    String[] row = new String[] { "File Name", "ProbeContentType", "MimetypesFileTypeMap", "MimeUtil",
            "SimpleMagic", "Tika" };
    printRow(row);/*from  w w  w .ja  va 2  s.  c o  m*/
    String line = "------------------------------";
    row = new String[] { "--------------------", line, line, line, line, line };
    printRow(row);

    File[] files = path.listFiles();

    for (int i = 0; i < files.length; i++) {
        if (files[i].isFile()) { //this line weeds out other directories/folders
            row[0] = files[i].getName().toString();
            row[1] = Files.probeContentType(files[i].toPath());
            row[2] = String.valueOf(new MimetypesFileTypeMap().getContentType(files[i]));
            row[3] = String.valueOf(MimeUtil.getMimeTypes(files[i]));
            if (!files[i].getName().contains("mkv") && !files[i].getName().contains("csv")) {
                ContentInfoUtil util = new ContentInfoUtil();
                row[4] = util.findMatch(files[i]).getMimeType();
            }
            row[5] = new Tika().detect(files[i]);

            printRow(row);
        }
    }
}

From source file:de.ks.file.FileStore.java

private String getMimeType(File file) {
    Path path = file.toPath();//  w  w w.  j  ava 2  s. c o  m
    try {
        return Files.probeContentType(path);
    } catch (IOException e) {
        log.error("Could not get mime type from ", file, e);
        return null;
    }
}

From source file:nl.opengeogroep.safetymaps.server.admin.stripes.FotoActionBean.java

@DontValidate
public Resolution downloadFoto() throws Exception {
    String filename = context.getRequest().getParameter("filename");
    String location = Cfg.getSetting("fotofunctie");
    String path = location + filename;
    log.info("downloading: " + path);
    File file = new File(path);
    Image image = ImageIO.read(file);
    if (image != null && file.exists()) {
        Path source = Paths.get(path);
        context.getResponse().setBufferSize(DEFAULT_BUFFER_SIZE);
        context.getResponse().setContentType(Files.probeContentType(source));
        context.getResponse().setHeader("Content-Length", String.valueOf(file.length()));
        context.getResponse().addHeader("content-disposition", "attachment; filename=" + filename);

        FileInputStream fis = null;

        try {//from   ww  w.j  a  v a  2  s  . c  o  m
            fis = new FileInputStream(file);

            IOUtils.copy(fis, context.getResponse().getOutputStream());
        } catch (Exception e) {
            log.error(e);
            return new ErrorResolution(500);
        }
        return null;
    } else {
        log.debug("The requested file" + path + "could not be opened , it is not an image or does not exists");
        return new ErrorResolution(404);
    }
}

From source file:org.geoserver.taskmanager.tasks.FileRemotePublicationTaskTypeImpl.java

@Override
protected boolean createStore(ExternalGS extGS, GeoServerRESTManager restManager, StoreInfo store,
        TaskContext ctx, String name) throws IOException, TaskException {
    final StoreType storeType = store instanceof CoverageStoreInfo ? StoreType.COVERAGESTORES
            : StoreType.DATASTORES;//from  w  w  w .j  a va 2 s  . co m

    boolean upload = false;

    FileReference fileRef = (FileReference) ctx.getBatchContext().get(ctx.getParameterValues().get(PARAM_FILE),
            new BatchContext.Dependency() {
                @Override
                public void revert() throws TaskException {
                    FileReference fileRef = (FileReference) ctx.getBatchContext()
                            .get(ctx.getParameterValues().get(PARAM_FILE));
                    URI uri = fileRef.getService().getURI(fileRef.getLatestVersion());
                    restManager.getStoreManager().update(store.getWorkspace().getName(),
                            new GSGenericStoreEncoder(storeType, store.getWorkspace().getName(),
                                    store.getType(), store.getName(), uri.toString(), true));
                }
            });
    URI uri = fileRef == null ? null : fileRef.getService().getURI(fileRef.getLatestVersion());
    if (uri == null) {
        try {
            uri = new URI(getLocation(store));
            upload = uri.getScheme() == null || uri.getScheme().toLowerCase().equals("file");
        } catch (URISyntaxException e) {
            throw new IOException(e);
        }
    }
    if (upload) {
        final File file = Resources.fromURL(uri.toString()).file();
        return restManager.getPublisher().createStore(store.getWorkspace().getName(), storeType, name,
                UploadMethod.FILE, store.getType().toLowerCase(), Files.probeContentType(file.toPath()),
                file.toURI(), null);
    } else {
        return restManager.getStoreManager().create(store.getWorkspace().getName(), new GSGenericStoreEncoder(
                storeType, store.getWorkspace().getName(), store.getType(), name, uri.toString(), true));
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.file.File.java

/**
 * Returns the {@code type} property.//from   w  w w  . j a va  2 s  .  co m
 * @return the {@code type} property
 */
@JsxGetter
public String getType() {
    try {
        return Files.probeContentType(file_.toPath());
    } catch (final IOException e) {
        return "";
    }
}

From source file:org.mitre.mpf.mvc.model.FileTreeNode.java

public FileTreeNode(File f) {
    this.text = f.getName();
    this.fullPath = f.getAbsolutePath();
    if (f.isFile()) {
        this.file = true;
        //this will prevent the node from having the ability to expand
        this.nodes = null;

        //TODO: move this checking to a method!
        String name = f.getName();

        String extension = "";
        int i = name.lastIndexOf('.');
        if (i > 0) {
            extension = name.toLowerCase().substring(i + 1);
        }//from   w  ww  .  j a va  2  s  . c  om

        //TODO: would save processing if not going from Java 6 to Java 7/8
        Path p = Paths.get(this.fullPath, name);
        String contentType = "";
        try {
            contentType = Files.probeContentType(p);
        } catch (Exception ex) {
            //TODO: a logger in here would probably break serialization - should move the content retrieval to another method
            //log.error("An exception occurred when trying to determine the content type of the file '{}': {}", f.getAbsolutePath(), ex);
        }

        //photo ?
        // glyphicon glyphicon-picture
        //audio ?
        // glyphicon glyphicon-music   
        //video ?
        // glyphicon glyphicon-film

        if (StringUtils.startsWithIgnoreCase(contentType, "AUDIO")) {
            this.icon = "glyphicon glyphicon-music";
        } else if (StringUtils.startsWithIgnoreCase(contentType, "IMAGE")) {
            this.icon = "glyphicon glyphicon-picture";
        } else if (StringUtils.startsWithIgnoreCase(contentType, "VIDEO")) {
            this.icon = "glyphicon glyphicon-film";
        } else {
            //TODO: doesn't display an mkv, capital JPG            
            //TODO: should not be included!!
            //TOOD: could use the extension as a backup if the content-type is ignored
            this.icon = "glyphicon glyphicon-file";
        }
    } else {
        //directory
        if (f.list().length <= 0) {
            //icon should be a closed folder by default
            this.nodes = null;
        }

        //set the expansion to false because the node will automatically expand if/when nodes are added
        //the expanded state will stay with the node
        this.state.expanded = false;
    }
}

From source file:net.urosk.mifss.core.workers.FileHandlerImpl.java

@Override
public String getMimeType(File file) {

    Path path = Paths.get(file.getPath());
    try {//from w  w w .  ja va2  s  . c  om
        String mt = Files.probeContentType(path);
        logger.debug("probe content " + mt);
        if (!StringUtils.isEmpty(mt))
            return mt;
    } catch (IOException e1) {
        logger.error(e1);
    }

    String mime = null;

    try {
        mime = tika.detect(file);
    } catch (IOException e) {
        logger.error(e);
    }

    return mime;
}

From source file:de.dennishoersch.web.css.images.ImagesInliner.java

private String inlineUrl(String url) throws IOException {
    Path path = _pathResolver.resolve(url);

    if (path == null) {
        logger.log(Level.WARNING, "Could not inline URL '" + url + "'!");
        return null;
    }//from w ww.  j  a  va2  s. c  om

    String contentType = Files.probeContentType(path);
    if (!contentType.contains("image")) {
        return null;
    }

    byte[] bytes = Files.readAllBytes(path);

    return contentType + ";base64," + org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);
}