NameDetector implements Detector { public MediaType detect(InputStream input, Metadata metadata) { String name = metadata.get(TikaCoreProperties.RESOURCE_NAME_KEY); if (name != null) { int question = name.indexOf('?'); if (question != -1) { name = name.substring(0, question); } int slash = name.lastIndexOf('/'); if (slash != -1) { name = name.substring(slash + 1); } int backslash = name.lastIndexOf('\\'); if (backslash != -1) { name = name.substring(backslash + 1); } int hash = name.lastIndexOf('#'); int dot = name.indexOf('.'); if (hash != -1) { if (dot == -1 || hash > dot) { name = name.substring(0, hash); } } int percent = name.indexOf('%'); if (percent != -1) { try { name = URLDecoder.decode(name, UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 not supported", e); } } name = name.trim(); if (name.length() > 0) { for (Pattern pattern : patterns.keySet()) { if (pattern.matcher(name).matches()) { return patterns.get(pattern); } } } } return MediaType.OCTET_STREAM; } NameDetector(Map<Pattern, MediaType> patterns); MediaType detect(InputStream input, Metadata metadata);  }
@Test public void testDetect() { assertDetect(MediaType.TEXT_PLAIN, "text.txt"); assertDetect(MediaType.TEXT_PLAIN, "text.txt "); assertDetect(MediaType.TEXT_PLAIN, "text.txt\n"); assertDetect(MediaType.TEXT_PLAIN, "text.txt?a=b"); assertDetect(MediaType.TEXT_PLAIN, "text.txt#abc"); assertDetect(MediaType.TEXT_PLAIN, "text%2Etxt"); assertDetect(MediaType.TEXT_PLAIN, "text.TXT"); assertDetect(MediaType.OCTET_STREAM, "text.txt.gz"); assertDetect(MediaType.TEXT_PLAIN, "README"); assertDetect(MediaType.TEXT_PLAIN, " README "); assertDetect(MediaType.TEXT_PLAIN, "\tREADME\n"); assertDetect(MediaType.TEXT_PLAIN, "/a/README"); assertDetect(MediaType.TEXT_PLAIN, "\\b\\README"); assertDetect(MediaType.OCTET_STREAM, "ReadMe"); assertDetect(MediaType.OCTET_STREAM, "README.NOW"); assertDetect(MediaType.TEXT_PLAIN, "text.txt"); assertDetect(MediaType.TEXT_PLAIN, "text#.txt"); assertDetect(MediaType.TEXT_PLAIN, "text#123.txt"); assertDetect(MediaType.TEXT_PLAIN, "text.txt#pdf"); assertDetect(MediaType.TEXT_PLAIN, "http: assertDetect(MediaType.TEXT_PLAIN, "http: assertDetect( MediaType.TEXT_PLAIN, " See http: assertDetect(MediaType.TEXT_PLAIN, "See README.txt"); assertDetect(MediaType.OCTET_STREAM, "See README"); assertDetect(MediaType.application("envi.hdr"), "ang20150420t182050_corr_v1e_img.hdr"); assertDetect(MediaType.OCTET_STREAM, ""); assertDetect(MediaType.OCTET_STREAM, null); try { assertEquals( MediaType.OCTET_STREAM, detector.detect(null, new Metadata())); } catch (IOException e) { fail("NameDetector should never throw an IOException"); } }