public String detectEncoding()

in axiom-api/src/main/java/org/apache/axiom/util/stax/dialect/EncodingDetectionHelper.java [48:97]


    public String detectEncoding() throws XMLStreamException {
        byte[] startBytes = new byte[4];
        try {
            if (useMark) {
                stream.mark(4);
            }
            int read = 0;
            do {
                int c = stream.read(startBytes, read, 4-read);
                if (c == -1) {
                    throw new XMLStreamException("Unexpected end of stream");
                }
                read += c;
            } while (read < 4);
            if (useMark) {
                stream.reset();
            } else {
                ((PushbackInputStream)stream).unread(startBytes);
            }
        } catch (IOException ex) {
            throw new XMLStreamException("Unable to read start bytes", ex);
        }
        int marker = ((startBytes[0] & 0xFF) << 24) + ((startBytes[1] & 0xFF) << 16)
                + ((startBytes[2] & 0xFF) << 8) + (startBytes[3] & 0xFF);
        switch (marker) {
            case 0x0000FEFF:
            case 0xFFFE0000:
            case 0x0000FFFE:
            case 0xFEFF0000:
            case 0x0000003C:
            case 0x3C000000:
            case 0x00003C00:
            case 0x003C0000:
                return "UCS-4";
            case 0x003C003F:
                return "UTF-16BE";
            case 0x3C003F00:
                return "UTF-16LE";
            case 0x3C3F786D:
                return "UTF-8";
            default:
                if ((marker & 0xFFFF0000) == 0xFEFF0000) {
                    return "UTF-16BE";
                } else if ((marker & 0xFFFF0000) == 0xFFFE0000) {
                    return "UTF-16LE";
                } else {
                    return "UTF-8";
                }
        }
    }