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

The following are Jave code examples for showing how to use probeContentType() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: joanne   File: ImageManager.java   Source Code and License Vote up 7 votes
public Metadata readMetdataFor(File f) throws JpegProcessingException {
  Metadata m = null;
  try {
      String mime = Files.probeContentType(f.toPath());
      System.out.println(mime);
      switch(mime){
          case "image/jpeg":
              m = JpegMetadataReader.readMetadata(f,readers);
              break;
          case "image/png":
              m = PngMetadataReader.readMetadata(f);
              break;
          case "image/gif":
              m = GifMetadataReader.readMetadata(f);
              break;
          case "image/bmp":
              m = BmpMetadataReader.readMetadata(f);
              break;
      }
  } catch (IOException | PngProcessingException ex) {
      Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
  }
  return m;
}
 
Example 2
Project: VISNode   File: InputReader.java   Source Code and License Vote up 6 votes
/**
 * Reads the file
 * 
 * @param file The file
 * @return Image
 * @throws IOException Impossible read the file 
 */
public Image read(File file) throws IOException {
    String fileType = Files.probeContentType(file.toPath());
    if (isDicom(fileType) || file.getName().endsWith(".dcm")) {
        return readDicom(file);
    }
    return readImage(file);
}
 
Example 3
Project: minijax   File: MinijaxStaticResource.java   Source Code and License Vote up 6 votes
@Override
Object invoke(final MinijaxRequestContext ctx) throws Exception {
    final String resourceName;

    if (directory) {
        resourceName = baseResourceName + "/" + ctx.getUriInfo().getPathParameters().getFirst("file");
    } else {
        resourceName = baseResourceName;
    }

    final URL resourceUrl = MinijaxStaticResource.class.getClassLoader().getResource(resourceName);
    if (resourceUrl == null) {
        return Response.status(Status.NOT_FOUND).build();
    }

    final File resourceFile = new File(resourceUrl.getFile());
    if (resourceFile.isDirectory()) {
        return Response.status(Status.NOT_FOUND).build();
    }

    final String contentType = Files.probeContentType(resourceFile.toPath());
    final MediaType mediaType = contentType == null ? MediaType.APPLICATION_OCTET_STREAM_TYPE : MediaType.valueOf(contentType);
    return Response.ok(resourceUrl.openStream(), mediaType).cacheControl(PUBLIC).build();
}
 
Example 4
Project: REST-Web-Services   File: ImageValidator.java   Source Code and License Vote up 5 votes
@Override
public boolean isValid(File file, ConstraintValidatorContext context) {
    if(Optional.ofNullable(file).isPresent()) {
        String contentType;
        try {
            contentType = Files.probeContentType(file.toPath());
        } catch (IOException e) {
            throw new ResourcePreconditionException("An I/O error occurs");
        }
        return contentType.equals("image/png")
                || contentType.equals("image/jpeg");
    }

    return true;
}
 
Example 5
Project: REST-Web-Services   File: FileUtils.java   Source Code and License Vote up 5 votes
/**
 * Convenience method of validation of an image file.
 *
 * @param file The file for validation
 * @throws ResourcePreconditionException if an I/O error occurs or incorrect content type
 */
public static void validImage(final File file) throws ResourcePreconditionException {
    String contentType;
    try {
        contentType = Files.probeContentType(file.toPath());
    } catch (IOException e) {
        throw new ResourcePreconditionException("An I/O error occurs");
    }
    if(!contentType.equals(PNG_MIME_TYPE)
            && !contentType.equals(JPEG_MIME_TYPE)) {
        throw new ResourcePreconditionException("Incorrect content type");
    }
}
 
Example 6
Project: REST-Web-Services   File: FileUtils.java   Source Code and License Vote up 5 votes
/**
 * Convenience method of validation of an image files.
 *
 * @param files Files for validation
 * @throws ResourcePreconditionException if an I/O error occurs or incorrect content type
 */
public static void validImage(final List<File> files) throws ResourcePreconditionException {
    for(final File file : files) {
        String contentType;
        try {
            contentType = Files.probeContentType(file.toPath());
        } catch (IOException e) {
            throw new ResourcePreconditionException("An I/O error occurs");
        }
        if(!contentType.equals(PNG_MIME_TYPE)
                && !contentType.equals(JPEG_MIME_TYPE)) {
            throw new ResourcePreconditionException("Incorrect content type");
        }
    }
}
 
Example 7
Project: Anyfast-Java   File: FileAPI.java   Source Code and License Vote up 5 votes
public static final String contentType(String filename){
	String type = null;
	Path path = Paths.get(filename);
	try {
		type = Files.probeContentType(path);
	} catch (IOException e) {
		e.printStackTrace();
	}
	return type;
}
 
Example 8
Project: openjdk-systemtest   File: ProbeContentTypeTest.java   Source Code and License Vote up 5 votes
private static void probeFileTypes() throws Exception {		
	List<String> missmatches = new LinkedList<String>();		
	for (Path path: fileToMimeMap.keySet()) {
		System.out.print("Checking " + path + " ...\t");
		Path filename = rootDirectory.resolve(path);
		if (Files.notExists(filename)) {
			System.err.println(filename + " doesn't exist, unable to probe file type");
		} else {
			String fileType = Files.probeContentType(filename);
			String expectedFileType = fileToMimeMap.get(path);
			
			// The return value can be legitimately null if it doesn't know what it is
			// So skip the checking if it is, and carry on
			if (fileType != null) {
				if (!expectedFileType.equalsIgnoreCase(fileType)) {
					missmatches.add(path +"'s filetype was '" + fileType +  "' but we expected '" + expectedFileType + "'");
					System.out.println("Fail");
				} else {
					System.out.println("OK");
				}
			} else {
				System.out.println("Unknown");
			}
		}
	}
	
	if (missmatches.size() > 0) {
		for (String message: missmatches) {
			System.out.println(message);
		}
		// Wait until here to fail so that we can list all the failures, 
		//  rather than just the first one.
		fail(Arrays.toString(missmatches.toArray()));
	}		
}
 
Example 9
Project: amanda   File: FileSystemStorageService.java   Source Code and License Vote up 5 votes
private FileInfo getFileInfo(File file) {
    String fileType = "";
    try {
        fileType =  Files.probeContentType(file.toPath());
    } catch (IOException e) {
        LOGGER.info("Can't get file type for file: " + file);
    }

    String url = this.getPathUrlFunction.apply(file.toPath());

    return new FileInfo(file.getName(), fileType, file.length(), Instant.ofEpochMilli(file.lastModified()), url);
}
 
Example 10
Project: WechatBot   File: NetUtils.java   Source Code and License Vote up 4 votes
public static String postImage(String id, String url, File file,
                               String mediatype, Map<String, Object> uploadMediaRequest,
                               String passTicket) throws IOException {

    log.debug("local cookies: " + localCookie.toString());
    String webwxDataTicket = StringUtils.substringBetween(localCookie.toString(), "webwx_data_ticket=", "; expires");
    if (StringUtils.isBlank(webwxDataTicket)) {
        log.error("No webwx_data_ticket in cookies");
        return null;
    }

    String type = Files.probeContentType(file.toPath());

    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("id", id)
            .addFormDataPart("name", file.getName())
            .addFormDataPart("type", type)
            .addFormDataPart("lastModifiedDate", LocalDate.now().getMonthValue()
                    + "/" + LocalDate.now().getDayOfMonth()
                    + "/" + LocalDate.now().getYear()
                    + ", " + LocalTime.now().withNano(0)
                    + " GMT+0800 (CST)")
            .addFormDataPart("size", String.valueOf(Files.size(file.toPath())))
            .addFormDataPart("mediatype", mediatype)
            .addFormDataPart("uploadmediarequest", mapper.writeValueAsString(uploadMediaRequest))
            .addFormDataPart("webwx_data_ticket", webwxDataTicket)
            .addFormDataPart("pass_ticket", passTicket)
            .addFormDataPart("filename", file.getName(), RequestBody.create(MediaType.parse(type), file))
            .build();

    Request request = new Request.Builder()
            .addHeader(USER_AGENT, USER_AGENT_CONTENT)
            .url(url)
            .post(requestBody)
            .build();

    try (ResponseBody responseBody = client.newCall(request).execute().body()) {
        return responseBody.string();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}