Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,22 @@ public void testVerifyMagic() {
assertFalse(verifyMagic(BinaryResources.create().withContent(HexUtility.decode("ffaaaa")).withFilename("invalid.jpg").build()));
}

@Test
public void findByMagicBytes() {
// jpg
assertTrue(MimeTypes.findByMagicBytes(HexUtility.decode("ffd8ff")).contains(MimeType.JPG));

// unknown mime-type
assertTrue(MimeTypes.findByMagicBytes(new byte[0]).isEmpty());
assertTrue(MimeTypes.findByMagicBytes(null).isEmpty());

// wav
assertTrue(MimeTypes.findByMagicBytes(HexUtility.decode("5249 4646 2e2e 2e2e 5741 5645")).contains(MimeType.WAV));

// pdf
assertTrue(MimeTypes.findByMagicBytes(HexUtility.decode("2550 4446")).contains(MimeType.PDF));
}

@Test
public void testMatches() throws IOException {
assertFalse(MimeType.JAR.matches((Path) null));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2010, 2025 BSI Business Systems Integration AG
* Copyright (c) 2010, 2026 BSI Business Systems Integration AG
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
Expand Down Expand Up @@ -83,10 +83,17 @@ public static Collection<IMimeType> findByContentMagic(BinaryResource res) {
if (res == null) {
return Collections.emptyList();
}
return findByMagicBytes(res.getContent());
}

public static Collection<IMimeType> findByMagicBytes(byte[] bytes) {
if (bytes == null) {
return Collections.emptyList();
}
return EXT_TO_MIMETYPE
.values()
.stream()
.filter(t -> t.getMagic() != null && t.getMagic().matches(res))
.filter(t -> t.getMagic() != null && t.getMagic().matches(bytes))
.collect(Collectors.toList());
}

Expand Down Expand Up @@ -115,9 +122,6 @@ public static boolean verifyMagic(BinaryResource res) {
Set<String> detectedMajorParts = findByContentMagic(res).stream()
.map(IMimeType::getMajorPart)
.collect(Collectors.toSet());
if (detectedMajorParts.isEmpty() || detectedMajorParts.contains(ext)) {
return true;
}
return false;
return (detectedMajorParts.isEmpty() || detectedMajorParts.contains(ext));
}
}
Loading