Example usage for javax.xml.stream XMLStreamReader getEncoding

List of usage examples for javax.xml.stream XMLStreamReader getEncoding

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamReader getEncoding.

Prototype

public String getEncoding();

Source Link

Document

Return input encoding if known or null if unknown.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    File file = new File("yourXML.xml");
    FileInputStream inputStream = new FileInputStream(file);
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader reader = inputFactory.createXMLStreamReader(inputStream);

    System.out.println(reader.getVersion());
    System.out.println(reader.isStandalone());
    System.out.println(reader.standaloneSet());
    System.out.println(reader.getEncoding());
    System.out.println(reader.getCharacterEncodingScheme());

    parseRestOfDocument(reader);/*from w ww. j  av a 2  s  . co  m*/
}

From source file:Main.java

public static boolean hasValidXmlDeclaration(byte[] doc) throws Exception {
    try {//ww w.ja  v  a 2  s .com
        XMLStreamReader r = xif.createXMLStreamReader(new ByteArrayInputStream(doc), null);
        if (!"UTF-8".equalsIgnoreCase(r.getEncoding()))
            return false;
        if (!"1.0".equals(r.getVersion()))
            return false;

        r.close();
        return true;
    } catch (XMLStreamException e) {
        throw new Exception("Unable to parse xml", e);
    }
}

From source file:com.gtdfree.test.XMLTest.java

public void testParserEncoding() {

    try {/*from w  w  w  . j  a  va2  s .  co m*/

        File file = new File("./src/test/resources/gtd-free-data_2.1.xml");
        InputStream is = new FileInputStream(file);
        XMLStreamReader r = XMLInputFactory.newInstance().createXMLStreamReader(is);
        System.out.println(r.getEncoding());
        assertEquals("UTF-8", r.getEncoding());
        while (r.hasNext()) {
            r.next();
        }
        r.close();
        is.close();

        file = new File("./src/test/resources/gtd-free-data_WIN1250_2.1.xml");
        is = new FileInputStream(file);
        r = XMLInputFactory.newInstance().createXMLStreamReader(is);
        System.out.println(r.getEncoding());
        assertEquals("UTF-8", r.getEncoding());
        try {
            while (r.hasNext()) {
                r.next();
            }
            fail("This should not happend.");
        } catch (Exception e) {
            //e.printStackTrace();
        }
        r.close();
        is.close();

        file = new File("./src/test/resources/gtd-free-data_2.1_enc.xml");
        is = new FileInputStream(file);
        r = XMLInputFactory.newInstance().createXMLStreamReader(is);
        System.out.println(r.getEncoding());
        assertEquals("UTF-8", r.getEncoding());
        while (r.hasNext()) {
            r.next();
        }
        r.close();
        is.close();

        file = new File("./src/test/resources/gtd-free-data_WIN1250_2.1_enc.xml");
        is = new FileInputStream(file);
        r = XMLInputFactory.newInstance().createXMLStreamReader(is);
        System.out.println(r.getEncoding());
        assertEquals("WINDOWS-1250", r.getEncoding());
        while (r.hasNext()) {
            r.next();
        }
        r.close();
        is.close();

    } catch (Exception e) {

        e.printStackTrace();
        fail(e.getMessage());

    }

}

From source file:StAXStreamTreeViewer.java

private void addStartDocumentNodes(XMLStreamReader reader, DefaultMutableTreeNode current) {
    DefaultMutableTreeNode version = new DefaultMutableTreeNode(reader.getVersion());
    current.add(version);//from  www.jav a 2  s .  c o m

    DefaultMutableTreeNode standalone = new DefaultMutableTreeNode(reader.isStandalone());
    current.add(standalone);

    DefaultMutableTreeNode standaloneSet = new DefaultMutableTreeNode(reader.standaloneSet());
    current.add(standaloneSet);

    DefaultMutableTreeNode encoding = new DefaultMutableTreeNode(reader.getEncoding());
    current.add(encoding);

    DefaultMutableTreeNode declaredEncoding = new DefaultMutableTreeNode(reader.getCharacterEncodingScheme());
    current.add(declaredEncoding);
}

From source file:org.apache.axiom.om.impl.builder.StAXBuilder.java

/**
 * Constructor StAXBuilder./*ww w .jav  a2  s. c  om*/
 * This constructor is used if the parser is at the beginning (START_DOCUMENT).
 *
 * @param ombuilderFactory
 * @param parser
 */
protected StAXBuilder(OMFactory ombuilderFactory, XMLStreamReader parser) {
    omfactory = ombuilderFactory;

    // The getEncoding information is only available at the START_DOCUMENT event.
    charEncoding = parser.getEncoding();

    initParser(parser);
}

From source file:org.gtdfree.model.GTDDataXMLTools.java

static public DataHeader load(GTDModel model, InputStream in) throws XMLStreamException, IOException {

    model.setSuspendedForMultipleChanges(true);
    model.getDataRepository().suspend(true);

    XMLStreamReader r;
    try {//from   www .j  av  a  2 s. co  m

        // buffer size is same as default in 1.6, we explicitly request it so, not to brake if defaut changes.
        BufferedInputStream bin = new BufferedInputStream(in, 8192);
        bin.mark(8191);

        Reader rr = new InputStreamReader(bin);
        CharBuffer b = CharBuffer.allocate(96);
        rr.read(b);
        b.position(0);
        //System.out.println(b);
        Pattern pattern = Pattern.compile("<\\?.*?encoding\\s*?=.*?\\?>", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
        Matcher matcher = pattern.matcher(b);

        // reset back to start of file
        bin.reset();

        // we check if encoding is defined in xml, by the book encoding on r should be null if not defined in xml,
        // but in reality it can be arbitrary if not defined in xml. So we have to check ourselves.
        if (matcher.find()) {
            //System.out.println(matcher);
            // if defined, then XML parser will pick it up and use it
            r = XMLInputFactory.newInstance().createXMLStreamReader(bin);
            Logger.getLogger(GTDDataXMLTools.class).info("XML declared encoding: " + r.getEncoding() //$NON-NLS-1$
                    + ", system default encoding: " + Charset.defaultCharset()); //$NON-NLS-1$
        } else {
            //System.out.println(matcher);
            // if not defined, then we assume it is generated by gtd-free version 0.4 or some local editor,
            // so we assume system default encoding.
            r = XMLInputFactory.newInstance().createXMLStreamReader(new InputStreamReader(bin));
            Logger.getLogger(GTDDataXMLTools.class)
                    .info("XML assumed system default encoding: " + Charset.defaultCharset()); //$NON-NLS-1$
        }

        r.nextTag();
        if ("gtd-data".equals(r.getLocalName())) { //$NON-NLS-1$
            DataHeader dh = new DataHeader(null, r.getAttributeValue(null, "version"), //$NON-NLS-1$
                    r.getAttributeValue(null, "modified")); //$NON-NLS-1$
            if (dh.version != null) {
                if (dh.version.equals("2.0")) { //$NON-NLS-1$
                    r.nextTag();
                    _load_2_0(model, r);
                    return dh;
                }
            }
            String s = r.getAttributeValue(null, "lastActionID"); //$NON-NLS-1$
            if (s != null) {
                try {
                    model.setLastActionID(Integer.parseInt(s));
                } catch (Exception e) {
                    Logger.getLogger(GTDDataXMLTools.class).debug("Internal error.", e); //$NON-NLS-1$
                }
            }
            if (dh.version != null) {
                if (dh.version.equals("2.1")) { //$NON-NLS-1$
                    r.nextTag();
                    _load_2_1(model, r);
                    return dh;

                }
                if (dh.version.startsWith("2.2")) { //$NON-NLS-1$
                    r.nextTag();
                    _load_2_2(model, r);
                    return dh;
                }
            }
            throw new IOException("XML gtd-free data with version number " + dh.version //$NON-NLS-1$
                    + " can not be imported. Data version is newer then supported versions. Update your GTD-Free application to latest version."); //$NON-NLS-1$
        }

        _load_1_0(model, r);

        return null;

    } catch (XMLStreamException e) {
        if (e.getNestedException() != null) {
            Logger.getLogger(GTDDataXMLTools.class).debug("Parse error.", e.getNestedException()); //$NON-NLS-1$
        } else {
            Logger.getLogger(GTDDataXMLTools.class).debug("Parse error.", e); //$NON-NLS-1$
        }
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        model.setSuspendedForMultipleChanges(false);
        model.getDataRepository().suspend(false);
    }

}

From source file:org.rhq.plugins.hadoop.HadoopServerConfigurationDelegate.java

private static void updateFile(File configFile, Map<String, PropertySimple> allProps)
        throws IOException, InterruptedException, XMLStreamException {
    InputStream in = null;/* ww w .  j ava  2  s  . co  m*/
    XMLStreamReader rdr = null;

    OutputStream out = null;
    XMLStreamWriter outWrt = null;

    try {
        Set<String> processedPropertyNames = new HashSet<String>();

        in = new BufferedInputStream(new FileInputStream(configFile));
        rdr = XML_INPUT_FACTORY.createXMLStreamReader(in);

        File tmpFile = File.createTempFile("hadoop-plugin", null);
        out = new FileOutputStream(tmpFile);
        outWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);

        ByteArrayOutputStream stash = new ByteArrayOutputStream();
        XMLStreamWriter stashWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(stash);
        boolean outputActive = true;

        outWrt.writeStartDocument();

        while (rdr.hasNext()) {
            int event = rdr.next();

            XMLStreamWriter wrt = outputActive ? outWrt : stashWrt;

            switch (event) {
            case XMLStreamConstants.ATTRIBUTE:
                break;
            case XMLStreamConstants.CDATA:
                wrt.writeCData(rdr.getText());
                break;
            case XMLStreamConstants.CHARACTERS:
                wrt.writeCharacters(rdr.getText());
                break;
            case XMLStreamConstants.COMMENT:
                wrt.writeComment(rdr.getText());
                break;
            case XMLStreamConstants.DTD:
                wrt.writeDTD(rdr.getText());
                break;
            case XMLStreamConstants.END_DOCUMENT:
                wrt.writeEndDocument();
                break;
            case XMLStreamConstants.END_ELEMENT:
                if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    String encoding = rdr.getEncoding();
                    if (encoding == null) {
                        encoding = "UTF-8";
                    }

                    String propertyTagSoFar = Charset.forName(encoding)
                            .decode(ByteBuffer.wrap(stash.toByteArray())).toString();
                    DetectedPropertyNameAndUpdatedTag propAndTag = updateProperty(propertyTagSoFar, allProps);

                    //yes, we're intentionally circumventing the xml stream writer, because we already have the XML data we want to write.
                    outWrt.flush();
                    out.write(propAndTag.updatedTag.getBytes("UTF-8"));

                    processedPropertyNames.add(propAndTag.propertyName);

                    //reset stuff
                    stash.reset();
                    wrt = outWrt;
                    outputActive = true;
                } else if (CONFIGURATION_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    //now add the new props
                    for (String prop : processedPropertyNames) {
                        allProps.remove(prop);
                    }

                    for (Map.Entry<String, PropertySimple> e : allProps.entrySet()) {
                        outWrt.writeStartElement(PROPERTY_TAG_NAME);

                        outWrt.writeStartElement(NAME_TAG_NAME);
                        outWrt.writeCharacters(e.getKey());
                        outWrt.writeEndElement();

                        outWrt.writeStartElement(VALUE_TAG_NAME);
                        outWrt.writeCharacters(e.getValue().getStringValue());
                        outWrt.writeEndElement();

                        outWrt.writeEndElement();
                    }
                }
                wrt.writeEndElement();
                break;
            case XMLStreamConstants.ENTITY_DECLARATION:
                //XXX could not find what to do with this
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                wrt.writeEntityRef(rdr.getText());
                break;
            case XMLStreamConstants.NAMESPACE:
                for (int i = 0; i < rdr.getNamespaceCount(); ++i) {
                    wrt.writeNamespace(rdr.getNamespacePrefix(i), rdr.getNamespaceURI(i));
                }
                break;
            case XMLStreamConstants.NOTATION_DECLARATION:
                //XXX could not find what to do with this
                break;
            case XMLStreamConstants.PROCESSING_INSTRUCTION:
                wrt.writeProcessingInstruction(rdr.getPITarget(), rdr.getPIData());
                break;
            case XMLStreamConstants.SPACE:
                wrt.writeCharacters(rdr.getText());
                break;
            case XMLStreamConstants.START_DOCUMENT:
                //this seems to be never called for some strange reason
                //wrt.writeStartDocument();
                break;
            case XMLStreamConstants.START_ELEMENT:
                wrt.writeStartElement(rdr.getName().getPrefix(), rdr.getName().getLocalPart(),
                        rdr.getName().getNamespaceURI());

                for (int i = 0; i < rdr.getAttributeCount(); ++i) {
                    wrt.writeAttribute(rdr.getAttributePrefix(i), rdr.getAttributeNamespace(i),
                            rdr.getAttributeLocalName(i), rdr.getAttributeValue(i));
                }

                if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    wrt.writeCharacters("");
                    outputActive = false;
                }
                break;
            }
        }

        outWrt.flush();
        out.flush();
        out.close();

        in.close();

        //now copy the temp file in the place of the original one
        FileUtil.copyFile(tmpFile, configFile);
    } finally {
        rdr.close();

        outWrt.flush();
        outWrt.close();

        try {
            in.close();
        } finally {
            out.flush();
            out.close();
        }
    }
}