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:uk.org.openeyes.diagnostics.FhirUtils.java

/**
 *
 * @param reference//from  w  w w  . j a va2  s. c o m
 * @param attachments
 * @return
 * @throws IOException
 */
public DiagnosticReport createDiagnosticReport(int patientRef, String reference, File[] attachments)
        throws IOException {
    DiagnosticReport report = DiagnosticReport.Factory.newInstance();

    ResourceReference subject = report.addNewSubject();
    subject.addNewReference().setValue("patient/pat-" + patientRef);
    DiagnosticReportImage image = report.addNewImage();
    ResourceReference imageRef = image.addNewLink();
    org.hl7.fhir.String ref = imageRef.addNewReference();
    ref.setValue(reference);
    for (int i = 0; i < attachments.length; i++) {
        ResourceReference resref = report.addNewResult();
        resref.addNewReference().setValue("#r" + (i + 1)); // TODO
        ResourceInline inline = report.addNewContained();
        Observation o = inline.addNewObservation();
        o.setId("r" + (i + 1));

        Attachment att = o.addNewValueAttachment();
        Base64Binary binary = att.addNewData();
        Path path = FileSystems.getDefault().getPath(attachments[i].getParentFile().getAbsolutePath(),
                attachments[i].getName());
        att.addNewContentType().setValue(Files.probeContentType(path));
        att.addNewTitle().setValue(attachments[i].getName());
        binary.setValue(this.base64encode(attachments[i]));
        att.setData(binary);

    }
    DiagnosticReportDocument doc = DiagnosticReportDocument.Factory.newInstance();
    doc.setDiagnosticReport(report);
    return report;
}

From source file:com.netsteadfast.greenstep.util.FSUtils.java

/**
 * get MIME-TYPE //from w w w. j  av  a  2s.co  m
 * Using javax.activation.MimetypesFileTypeMap
 * 
 * @param file
 * @return
 * @throws Exception
 */
public static String getMimeType(File file) throws Exception {
    String mimeType = "";
    if (file == null || !file.exists() || file.isDirectory()) {
        return mimeType;
    }
    /*
    mimeType=new MimetypesFileTypeMap().getContentType(file);
    return mimeType;
    */
    return Files.probeContentType(file.toPath());
}

From source file:com.github.rwhogg.git_vcr.review.ReviewResults.java

/**
 * review runs the code review on each file
 * @throws ClassNotFoundException If we cannot find a review tool class
 * @throws ReviewFailedException If code review failed for some reason
 * @throws IllegalAccessException If we cannot access a review tool class
 * @throws InstantiationException if we cannot instantiate a review tool class
 *//*from  w ww .j a v  a 2 s .c o m*/
@SuppressWarnings("rawtypes")
public void review()
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, ReviewFailedException {
    Map<String, List<ReviewTool>> tests = getTests();
    results = new HashMap<>();
    for (ImmutablePair<String, String> changePair : Util.getFilesChanged(patch)) {
        String oldFileName = changePair.left;
        String newFileName = changePair.right;

        // FIXME: what to do if one or more is null?

        // FIXME: not sure what to do about this case. For now, just assert.
        assert FilenameUtils.getExtension(oldFileName).equals(FilenameUtils.getExtension(newFileName));

        File file = new File(isNew ? newFileName : oldFileName);

        String mimeType = null;
        try {
            mimeType = Files.probeContentType(file.toPath());
        } catch (IOException e) {
            // FIXME Auto-generated catch block
            e.printStackTrace();
        }

        // run the tests
        List<ReviewTool> tools = tests.get(mimeType);
        Map<Class, List<String>> resultsForThisFile = new HashMap<>();
        if (tools != null) {
            for (ReviewTool tool : tools) {
                List<String> resultsFromTool;
                resultsFromTool = tool.getResults(file);
                resultsForThisFile.put(tool.getClass(), resultsFromTool);
            }
        }
        results.put(oldFileName, resultsForThisFile);
    }
}

From source file:com.osbitools.ws.shared.prj.web.EntityUtilsMgrWsSrvServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from  ww w.  j  av a 2s  .c  o  m
        super.doGet(req, resp);
    } catch (ServletException e) {
        if (e.getCause().getClass().equals(WsSrvException.class)) {
            // Authentication failed
            checkSendError(req, resp, (WsSrvException) e.getCause());
            return;
        } else {
            throw e;
        }
    }

    // Check if only info requires
    boolean fcheck = req.getParameter("check") != null;
    String name = req.getParameter(PrjMgrConstants.REQ_NAME_PARAM);

    if (fcheck) {
        try {
            // Get info about single file
            printJson(resp, GenericUtils.getInfo(getPrjRootDir(req), name, getBaseExt(req),
                    getReqParamValues(req), isMinfied(req)));
        } catch (WsSrvException e) {
            return;
        }
    } else {
        try {
            // Download file
            File f = GenericUtils.checkFile(getPrjRootDir(req), name, getBaseExt(req));
            printMimeFile(resp, Files.probeContentType(f.toPath()), name, GenericUtils.readFile(f), "utf-8");
        } catch (WsSrvException e) {
            checkSendError(req, resp, e);
        }
    }
}

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

protected void addPossibleImage(File file) {
    if (file == null) {
        return;/*from  www  .  j  a  v a 2s  .c o m*/
    }
    try {
        String contentType = Files.probeContentType(file.toPath());
        if (contentType != null && contentType.contains("image")) {
            imageProvider.addImage(new ImageData(file.getName(), file.getPath()));
        }
    } catch (IOException e) {
        //
    }
}

From source file:com.cami.web.controller.FileController.java

/**
 * *************************************************
 * URL: /appel-offre/file/get/{value} get(): get file as an attachment
 *
 * @param response : passed by the server
 * @param value : value from the URL//from   w w  w  . j a v a  2s .co  m
 * @return void **************************************************
 */
@RequestMapping(value = "/get/{value}", method = RequestMethod.GET)
public void get(HttpServletResponse response, @PathVariable String value) {
    System.out.println(value);
    String savedFileName = getSavedFileName(SAVE_DIRECTORY, value);
    File file = new File(savedFileName);
    Path source = Paths.get(savedFileName);
    FileMeta getFile = new FileMeta();

    try {

        getFile.setFileName(file.getName());
        getFile.setFileSize(Files.size(source) / 1024 + " Kb");
        getFile.setFileType(Files.probeContentType(source));

        response.setContentType(getFile.getFileType());
        response.setHeader("Content-disposition", "attachment; filename=\"" + getFile.getFileName() + "\"");
        FileCopyUtils.copy(Files.readAllBytes(source), response.getOutputStream());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.egov.infra.utils.FileStoreUtils.java

public ResponseEntity<InputStreamResource> fileAsResponseEntity(String fileStoreId, String moduleName,
        boolean toSave) {
    try {//w w  w  . j a v  a 2s . co m
        Optional<FileStoreMapper> fileStoreMapper = getFileStoreMapper(fileStoreId);
        if (fileStoreMapper.isPresent()) {
            Path file = getFileAsPath(fileStoreId, moduleName);
            byte[] fileBytes = Files.readAllBytes(file);
            String contentType = isBlank(fileStoreMapper.get().getContentType()) ? Files.probeContentType(file)
                    : fileStoreMapper.get().getContentType();
            return ResponseEntity.ok().contentType(parseMediaType(defaultIfBlank(contentType, JPG_MIME_TYPE)))
                    .cacheControl(CacheControl.noCache()).contentLength(fileBytes.length)
                    .header(CONTENT_DISPOSITION,
                            format(toSave ? CONTENT_DISPOSITION_ATTACH : CONTENT_DISPOSITION_INLINE,
                                    fileStoreMapper.get().getFileName()))
                    .body(new InputStreamResource(new ByteArrayInputStream(fileBytes)));
        }
        return ResponseEntity.notFound().build();
    } catch (IOException e) {
        LOGGER.error("Error occurred while creating response entity from file mapper", e);
        return ResponseEntity.badRequest().build();
    }
}

From source file:uk.org.openeyes.diagnostics.FhirUtils.java

/**
 * @param type//ww  w . j a  v  a  2 s.co m
 * @param media
 * @param attachments
 */
public Media createMedia(File media) throws IOException {
    Media m = Media.Factory.newInstance();
    Attachment att = m.addNewContent();
    Base64Binary data = att.addNewData();

    Path path = FileSystems.getDefault().getPath(media.getParentFile().getAbsolutePath(), media.getName());
    att.addNewContentType().setValue(Files.probeContentType(path));
    att.addNewTitle().setValue(media.getName());
    data.setValue(this.base64encode(media));
    att.setData(data);
    m.addNewSubject().addNewReference().setValue("media/med-1");
    MediaDocument doc = MediaDocument.Factory.newInstance();
    doc.setMedia(m);
    return m;
}

From source file:com.braffdev.server.core.container.resourceloader.ResourceLoader.java

/**
 * Determines the content type of the file denoted by the given path.<br />
 * This method asks the file system to determine the content type.
 *
 * @param path the path.//from   ww  w.  ja  v  a  2  s  .c  o m
 * @return the content type
 * @throws Exception if something bad happens.
 */
public String lookupContentType(String path) throws Exception {
    return Files.probeContentType(Paths.get(new File(this.root, path).toURI()));
}

From source file:httpUtils.HttpUtils.java

/**
 * Get the file as an HttpServletResponse
 * @param request//from w w  w .  j  a  v  a 2s.  c  o  m
 * @param response
 * @param file
 * @return
 */
public static HttpServletResponse getAssetAsStream(HttpServletRequest request, HttpServletResponse response,
        File file) {
    InputStream dataStream = null;
    try {
        dataStream = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        log.warn("file not found", e);
    }
    long fileLength = file.length();
    String fileName = file.getName();
    long fileLastModified = file.lastModified();
    String contentType = null;

    Path path = FileSystems.getDefault().getPath("", file.getPath());
    try {
        contentType = Files.probeContentType(path);
    } catch (IOException e) {
        log.warn("content type determination failed", e);
    }

    //TODO make this better
    if (fileName.endsWith("js") && contentType == null) {
        contentType = "application/javascript";
    } else if (fileName.endsWith("css") && contentType == null) {
        contentType = "text/css";
    }

    return getFileAsStream(request, response, dataStream, fileLength, fileName, fileLastModified, contentType);
}