Create a gist now

Instantly share code, notes, and snippets.

Test program for nio probeContentType and FileTypeDetector implementation
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.spi.FileTypeDetector;
import java.util.HashMap;
import java.util.Map;
import sun.nio.fs.DefaultFileTypeDetector;
import sun.nio.fs.GnomeFileTypeDetector;
public class ContentTypeTest {
public static void main(String[] argv) {
Map<String,String> checks = new HashMap<>();
checks.put("index.html", "text/html");
checks.put("index.java", "text/x-java-source");
Path path = Paths.get(".");
System.out.println("current working directory: "+path.toAbsolutePath());
int failCount = 0;
try {
FileTypeDetector fileTypeDetector = DefaultFileTypeDetector.create();
System.out.println("DefaultFileTypeDetector class : " + fileTypeDetector.getClass().getCanonicalName());
isGioAvailable(fileTypeDetector);
for (Map.Entry<String,String> check : checks.entrySet()) {
String expectedContentType = check.getValue();
if(!checkContentType(check.getKey(), expectedContentType)){
failCount++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (failCount > 0) {
System.out.println("TEST FAIL!");
} else {
System.out.println("TEST PASS!");
}
}
private static boolean checkContentType(String s, String expectedContentType) throws IOException {
Path path = Paths.get(s);
String filetype = Files.probeContentType(path);
if (filetype == null || !filetype.equals(expectedContentType)) {
System.out.println(path.toString() + " - file type is not "+expectedContentType+"; file type is - " + filetype);
return false;
} else {
System.out.println(path.toString() + " - file type is "+expectedContentType);
return true;
}
}
private static void isGioAvailable(FileTypeDetector fileTypeDetector) throws NoSuchFieldException, IllegalAccessException {
if (fileTypeDetector instanceof GnomeFileTypeDetector) {
Field f = fileTypeDetector.getClass().getDeclaredField("gioAvailable"); //NoSuchFieldException
f.setAccessible(true);
Object gioAvailable = f.get(fileTypeDetector); //IllegalAccessException
GnomeFileTypeDetector gnomeFileTypeDetector = (GnomeFileTypeDetector) fileTypeDetector;
System.out.println("isGioAvailable: " + gioAvailable.toString());
}
}
}
<html></html>
class Index{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment