Java Code Examples for java.nio.file.Files#probeContentType()

The following examples show how to use java.nio.file.Files#probeContentType() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * 获取文件内容类型
 * @param file
 * @return
 */
public static String getContentType(File file){
    if (file == null){
        return null;
    }
    Path path = Paths.get(file.toURI());
    if (path == null){
        return null;
    }
    String contentType = null;
    try {
        contentType = Files.probeContentType(path);
    } catch (IOException e) {
        log.error("获取文件ContentType异常",e);
    }
    if (contentType == null){
        // 读取拓展的自定义配置
        contentType = getContentTypeByExtension(file);
    }
    // 设置默认的内容类型
    if (contentType == null){
        contentType = DEFAULT_MIME_TYPE;
    }
    return contentType;
}
 
Example 2
private Attachment mapDataToAttachment(File resultDirectory, StepResult stepResult, FormData formData) {
    String extension = FilenameUtils.getExtension(formData.getFilePath());
    String relativePath = getAttachRelativePath(formData.getFieldName(), extension);
    Path sourcePath = Paths.get(projectRepositoryPath, stepResult.getProjectCode(), formData.getFilePath());
    Path attachPath = resultDirectory.toPath().resolve(relativePath);
    String contentType;
    try {
        contentType = Files.probeContentType(sourcePath);
    } catch (IOException ignored) {
        contentType = TEXT_PLAIN;
    }
    try {
        Files.copy(sourcePath, attachPath);
    } catch (IOException e) {
        log.warn("Exception while copying form data file: {}", formData.getFilePath(), e);
    }
    return new Attachment().withTitle(formData.getFieldName()).withSource(relativePath).withType(contentType);
}
 
Example 3
Source Project: webdsl   File: File.java    License: Apache License 2.0 6 votes vote down vote up
public static File createFromFilePath(String fullPath) {
  File file = null;
  try {
      java.io.File fileOnDisk = new java.io.File(fullPath);
      if(!fileOnDisk.exists()) {
        return null;
      } else {
        file = new utils.File();
        file.setContentStream(new FileInputStream(fileOnDisk));
        String contentType = Files.probeContentType( fileOnDisk.toPath() );
        file.setContentType(contentType);
        file.setFileName( fileOnDisk.getName() );
      }  
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  return file;
}
 
Example 4
Source Project: elepy   File: FrontendLoader.java    License: Apache License 2.0 6 votes vote down vote up
private void setupLogo(ElepyPostConfiguration elepy, HttpService http) throws IOException {
    final var logo = Optional.ofNullable(elepy.getPropertyConfig().getString("cms.logo")).orElse("/banner.jpg");

    final var logoURI = Optional.ofNullable(getClass().getResource(logo)).orElseThrow(() -> new ElepyConfigException(logo + " can't be found"));
    final var logoContentType = Files.probeContentType(Paths.get(logoURI.getPath()));
    final var input = Objects.requireNonNull(getClass().getResourceAsStream(logo));
    final var logoBytes = IOUtils.toByteArray(input);
    http.get("/elepy/logo", ctx -> {
        if (logo.startsWith("http://") || logo.startsWith("https://")) {
            ctx.redirect(logo);
        } else {
            ctx.type(logoContentType);
            ctx.response().result(logoBytes);
        }
    });
}
 
Example 5
@Nullable
private String tryGetAttachment(CommandContext ctx) {
    final Attachment attachment = ctx.getMessage().getAttachments().get(0);

    final File file = new File(attachment.getFileName());

    String mimetype = null;
    try {
        mimetype = Files.probeContentType(file.toPath());
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    //mimetype should be something like "image/png"
    if (mimetype == null || !mimetype.split("/")[0].equals("image")) {
        sendMsg(ctx, "That file does not look like an image");
        return null;
    }

    return attachment.getUrl();
}
 
Example 6
Source Project: darklaf   File: DarkFileChooserUI.java    License: MIT License 5 votes vote down vote up
public Icon getIcon(final File f) {
    Icon icon = getCachedIcon(f);
    if (icon != null) {
        return icon;
    }
    icon = fileIcon;
    if (f != null) {
        FileSystemView fsv = getFileChooser().getFileSystemView();

        if (fsv.isFloppyDrive(f)) {
            icon = floppyDriveIcon;
        } else if (fsv.isDrive(f)) {
            icon = hardDriveIcon;
        } else if (fsv.isComputerNode(f)) {
            icon = computerIcon;
        } else if (f.isDirectory()) {
            icon = directoryIcon;
        } else {
            try {
                String mimeType = Files.probeContentType(f.toPath());
                if (mimeType == null) mimeType = "";
                if (mimeType.startsWith(MIME_IMAGE)) {
                    icon = imageFileIcon;
                } else if (mimeType.startsWith(MIME_TEXT)) {
                    icon = textFileIcon;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    cacheIcon(f, icon);
    return icon;
}
 
Example 7
@GET
@Path("/files")
public String getFiles(@QueryParam("path") String path, @QueryParam("type") String type) throws IOException {
    File dir = new File(MCRWebPagesSynchronizer.getWCMSDataDir().getPath() + path);
    JsonObject jsonObj = new JsonObject();
    JsonArray jsonArray = new JsonArray();
    File[] fileArray = dir.listFiles();
    if (fileArray != null) {
        for (File file : fileArray) {
            String mimetype = Files.probeContentType(file.toPath());
            if (mimetype != null && (type.equals("images") ? mimetype.split("/")[0].equals("image")
                : !mimetype.split("/")[1].contains("xml"))) {
                JsonObject fileJsonObj = new JsonObject();
                fileJsonObj.addProperty("name", file.getName());
                fileJsonObj.addProperty("path", context.getContextPath() + path + "/" + file.getName());
                if (file.isDirectory()) {
                    fileJsonObj.addProperty("type", "folder");
                } else {
                    fileJsonObj.addProperty("type", mimetype.split("/")[0]);
                }
                jsonArray.add(fileJsonObj);
            }
        }
        jsonObj.add("files", jsonArray);
        return jsonObj.toString();
    }
    return "";
}
 
Example 8
@Override
public String probeContentType(Path path) throws IOException {
    LOGGER.debug(() -> "Probing content type of: " + path);
    if (!(path.getFileSystem() instanceof MCRIFSFileSystem)) {
        return null;
    }
    MCRStoredNode resolvePath = MCRFileSystemUtils.resolvePath(MCRPath.toMCRPath(path));
    if (resolvePath instanceof MCRDirectory) {
        throw new NoSuchFileException(path.toString());
    }
    MCRFile file = (MCRFile) resolvePath;
    String mimeType = Files.probeContentType(file.getLocalPath());
    LOGGER.debug(() -> "IFS mime-type: " + mimeType);
    return mimeType;
}
 
Example 9
Source Project: tutorials   File: MimeTypeUnitTest.java    License: MIT License 5 votes vote down vote up
/**
 * Test method, demonstrating usage in Java 7.
 * 
 * @throws IOException
 */
@Test
public void whenUsingJava7_thenSuccess() throws IOException {
    final Path path = new File(FILE_LOC).toPath();
    final String mimeType = Files.probeContentType(path);
    assertEquals(mimeType, PNG_EXT);
}
 
Example 10
/**
 * Open anything that looks a bit like a file name
 */
@Override
public TypedInputStream open(LookUpRequest request) {
    String filenameIRI = request.getFilenameOrURI();
    if(filenameIRI.startsWith("http") || filenameIRI.startsWith("coap")) {
        return null;
    }
    String fn = toFileName(filenameIRI);
    if (fn == null) {
        log.debug("Cannot find a proper filename: " + filenameIRI);
        return null;
    }

    try {
        if (!exists$(fn)) {
            return null;
        }
    } catch (AccessControlException e) {
        log.debug("Security problem testing for file", e);
        return null;
    }

    try {
        InputStream in = IO.openFileEx(fn);
        try {
            String ct = Files.probeContentType(Paths.get(new File(filenameIRI).getName()));
            return new TypedInputStream(in, ContentType.create(ct), filenameIRI);
        } catch (Exception ex) {
            return new TypedInputStream(in, (ContentType) null, filenameIRI);
        } 
    } catch (IOException ioEx) {
        // Includes FileNotFoundException
        // We already tested whether the file exists or not.
        log.debug("File unreadable (but exists): " + fn + " Exception: " + ioEx.getMessage());
        return null;
    }
}
 
Example 11
Source Project: HtmlUnit-Android   File: FileReader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reads the contents of the specified {@link Blob} or {@link File}.
 * @param object the {@link Blob} or {@link File} from which to read
 * @throws IOException if an error occurs
 */
@JsxFunction
public void readAsDataURL(final Object object) throws IOException {
    readyState_ = LOADING;
    final java.io.File file = ((File) object).getFile();
    String contentType = Files.probeContentType(file.toPath());
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        FileUtils.copyFile(file, bos);

        final byte[] bytes = bos.toByteArray();
        final String value = new String(new Base64().encode(bytes));
        final BrowserVersion browserVersion = getBrowserVersion();

        result_ = "data:";
        final boolean includeConentType = browserVersion.hasFeature(JS_FILEREADER_CONTENT_TYPE);
        if (!value.isEmpty() || includeConentType) {
            if (contentType == null) {
                if (includeConentType) {
                    contentType = "application/octet-stream";
                }
                else {
                    contentType = "";
                }
            }
            result_ += contentType + ";base64," + value;
        }
        if (value.isEmpty() && getBrowserVersion().hasFeature(JS_FILEREADER_EMPTY_NULL)) {
            result_ = "null";
        }
    }
    readyState_ = DONE;

    final Event event = new Event(this, Event.TYPE_LOAD);
    fireEvent(event);
}
 
Example 12
Source Project: bamboobsc   File: FSUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * get MIME-TYPE 
 * 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());
}
 
Example 13
Source Project: signal-cli   File: Utils.java    License: GNU General Public License v3.0 5 votes vote down vote up
static StreamDetails createStreamDetailsFromFile(File file) throws IOException {
    InputStream stream = new FileInputStream(file);
    final long size = file.length();
    String mime = Files.probeContentType(file.toPath());
    if (mime == null) {
        mime = "application/octet-stream";
    }
    return new StreamDetails(stream, mime, size);
}
 
Example 14
Source Project: SB_Elsinore_Server   File: UrlEndpoints.java    License: MIT License 5 votes vote down vote up
/**
 * Read the incoming parameters and update the name as appropriate.
 * @return True if success, false if failure
 */
@SuppressWarnings("unchecked")
@UrlEndpoint(url = "/uploadimage", help = "Upload an image for the brewery logo",
parameters = {@Parameter(name = "file", value = "Push a file to this EndPoint to upload")})
public Response updateBreweryImage() {

    final Map<String, String> files = this.files;

    if (files.size() == 1) {
        for (Map.Entry<String, String> entry : files.entrySet()) {

            try {
                File uploadedFile = new File(entry.getValue());
                String fileType = Files.probeContentType(
                        uploadedFile.toPath());

                if (fileType.equalsIgnoreCase(MIME_TYPES.get("gif"))
                    || fileType.equalsIgnoreCase(MIME_TYPES.get("jpg"))
                    || fileType.equalsIgnoreCase(MIME_TYPES.get("jpeg"))
                    || fileType.equalsIgnoreCase(MIME_TYPES.get("png")))
                {
                    File targetFile = new File(rootDir, "brewerImage.gif");
                    if (targetFile.exists() && !targetFile.delete()) {
                        BrewServer.LOG.warning("Failed to delete " + targetFile.getCanonicalPath());
                    }
                    LaunchControl.copyFile(uploadedFile, targetFile);

                    if (!targetFile.setReadable(true, false) || targetFile.setWritable(true, false)) {
                        BrewServer.LOG.warning("Failed to set read write permissions on " + targetFile.getCanonicalPath());
                    }

                    LaunchControl.setFileOwner(targetFile);
                    return new Response(Response.Status.OK, MIME_TYPES.get("text"), "Updated brewery logo");
                }
            } catch (IOException e) {}
        }
    }
    return null;

}
 
Example 15
@Override
public String probeContentType(Path path) throws IOException {
    LOGGER.debug(() -> "Probing content type of: " + path);
    if (!(path.getFileSystem() instanceof MCRIFSFileSystem)) {
        return null;
    }
    MCRFilesystemNode resolvePath = MCRFileSystemProvider.resolvePath(MCRPath.toMCRPath(path));
    if (resolvePath == null) {
        throw new NoSuchFileException(path.toString());
    }
    if (resolvePath instanceof MCRDirectory) {
        throw new NoSuchFileException(path.toString());
    }
    MCRFile file = (MCRFile) resolvePath;
    String mimeType = file.getContentType().getMimeType();
    LOGGER.debug(() -> "IFS mime-type: " + mimeType);
    if (defaultMimeType.equals(mimeType)) {
        Path dummy = Paths.get(path.getFileName().toString());
        String dummyType = Files.probeContentType(dummy);
        if (dummyType != null) {
            LOGGER.debug(() -> "System mime-type #1: " + dummyType);
            return dummyType;

        }
        String systemMimeType = Files.probeContentType(file.getLocalFile().toPath());
        if (systemMimeType != null) {
            LOGGER.debug(() -> "System mime-type #2: " + systemMimeType);
            return systemMimeType;
        }
    }
    return mimeType;
}
 
Example 16
@Override
public String getContentType() {
    String contentType;
    try {
        contentType = Files.probeContentType(file);
        if(contentType == null) {
            contentType = DEFAULT_CONTENT_TYPE;
        }
    } catch (IOException ex) {
        DeploymentRepositoryLogger.ROOT_LOGGER.debugf(ex, "Error obtaining content-type for %s", file.toString());
        contentType = DEFAULT_CONTENT_TYPE;
    }
    return contentType;
}
 
Example 17
Source Project: signal-cli   File: Utils.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static String getFileMimeType(File file) throws IOException {
    String mime = Files.probeContentType(file.toPath());
    if (mime == null) {
        try (InputStream bufferedStream = new BufferedInputStream(new FileInputStream(file))) {
            mime = URLConnection.guessContentTypeFromStream(bufferedStream);
        }
    }
    if (mime == null) {
        mime = "application/octet-stream";
    }
    return mime;
}
 
Example 18
@Override
public String getMimeType() throws IOException {
    return mimeType == null ? Files.probeContentType(path) : mimeType;
}
 
Example 19
Source Project: jsr203-hadoop   File: TestFiles.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void probeContentType() throws IOException {
  Path rootPath = Paths.get(clusterUri);
  Path path = Files.createTempFile(rootPath, "test", "tmp");
  Files.probeContentType(path);
}
 
Example 20
public static boolean isVideoFile(Path path) throws IOException {
    String mimeType = Files.probeContentType(path);
    return mimeType != null && mimeType.startsWith("video");
}