From 94453bbd031d04a3c8777dfc6dcbbeafd84bfe48 Mon Sep 17 00:00:00 2001 From: Stefan Schmiedl Date: Mon, 8 Jul 2019 22:25:48 +0200 Subject: [PATCH] skip over BOM in XML input --- .../ZUGFeRD/ZUGFeRDImporter.java | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/mustangproject/ZUGFeRD/ZUGFeRDImporter.java b/src/main/java/org/mustangproject/ZUGFeRD/ZUGFeRDImporter.java index a33ea2e3..be95f293 100644 --- a/src/main/java/org/mustangproject/ZUGFeRD/ZUGFeRDImporter.java +++ b/src/main/java/org/mustangproject/ZUGFeRD/ZUGFeRDImporter.java @@ -180,11 +180,40 @@ public class ZUGFeRDImporter { DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance(); xmlFact.setNamespaceAware(false); DocumentBuilder builder = xmlFact.newDocumentBuilder(); - Document doc = builder.parse(new ByteArrayInputStream(rawXML)); + ByteArrayInputStream is = new ByteArrayInputStream(rawXML); + is.skip(guessBOMSize(is)); + Document doc = builder.parse(is); //prettyPrint(doc); return doc; } + /** + * Skips over a BOM at the beginning of the given ByteArrayInputStream, if one exists. + * @param is the ByteArrayInputStream used + * @throws IOException + * @see Autodetection of Character Encodings + */ + private int guessBOMSize(ByteArrayInputStream is) throws IOException { + byte[] pad = new byte[4]; + is.read(pad); + is.reset(); + int test2 = ((pad[0] & 0xFF) << 8) | (pad[1] & 0xFF); + int test3 = ((test2 & 0xFFFF) << 8) | (pad[2] & 0xFF); + int test4 = ((test3 & 0xFFFFFF) << 8) | (pad[3] & 0xFF); + // + if (test4 == 0x0000FEFF || test4 == 0xFFFE0000 || test4 == 0x0000FFFE || test4 == 0xFEFF0000) { + // UCS-4: BOM takes 4 bytes + return 4; + } else if (test3 == 0xEFBBFF) { + // UTF-8: BOM takes 3 bytes + return 3; + } else if (test2 == 0xFEFF || test2 == 0xFFFE) { + // UTF-16: BOM takes 2 bytes + return 2; + } + return 0; + } + private String extractString(String xpathStr) { if (!containsMeta) { throw new ZUGFeRDExportException("No suitable data/ZUGFeRD file could be found.");