Java Code Examples for org.codehaus.stax2.XMLStreamReader2#next()

The following examples show how to use org.codehaus.stax2.XMLStreamReader2#next() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestCopyEventFromReader97.java    From woodstox with Apache License 2.0 6 votes vote down vote up
public void testUTF8MsLinefeedCopyEvent() throws Exception
{
    final XMLInputFactory2 xmlIn = getInputFactory();
    final XMLOutputFactory2 xmlOut = getOutputFactory();
    InputStream in = getClass().getResource("issue97.xml").openStream();

    ByteArrayOutputStream bogus = new ByteArrayOutputStream();
    XMLStreamReader2 reader = (XMLStreamReader2) xmlIn.createXMLStreamReader(in);
    XMLStreamWriter2 writer = (XMLStreamWriter2) xmlOut.createXMLStreamWriter(bogus, "UTF-8");
    while (reader.hasNext()) {
       reader.next();
       writer.copyEventFromReader(reader, false);
    }

    in.close();
}
 
Example 2
Source File: BaseStax2ValidationTest.java    From woodstox with Apache License 2.0 5 votes vote down vote up
protected void verifyFailure(String xml, XMLValidationSchema schema, String failMsg,
                             String failPhrase, boolean strict) throws XMLStreamException
{
    XMLStreamReader2 sr = constructStreamReader(getInputFactory(), xml);
    sr.validateAgainst(schema);
    try {
        while (sr.hasNext()) {
            /* int type = */sr.next();
        }
        fail("Expected validity exception for " + failMsg);
    } catch (XMLValidationException vex) {
        String origMsg = vex.getMessage();
        String msg = (origMsg == null) ? "" : origMsg.toLowerCase();
        if (msg.indexOf(failPhrase.toLowerCase()) < 0) {
            String actualMsg = "Expected validation exception for "
                + failMsg + ", containing phrase '" + failPhrase
                + "': got '" + origMsg + "'";
            if (strict) {
                fail(actualMsg);
            }
            warn("suppressing failure due to MSV bug, failure: '"
                 + actualMsg + "'");
        }
        // should get this specific type; not basic stream exception
    } catch (XMLStreamException sex) {
        fail("Expected XMLValidationException for " + failMsg
             + "; instead got " + sex.getMessage());
    }
}
 
Example 3
Source File: W3CSchemaWrite23Test.java    From woodstox with Apache License 2.0 5 votes vote down vote up
public void testSchemaValidatingCopy23() throws Exception
{
    final String SCHEMA = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<xs:schema elementFormDefault=\"unqualified\"\n" +
            "           xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
            "    <xs:element name=\"Document\">\n" +
            "        <xs:complexType>\n" +
            "            <xs:sequence>\n" +
            "                <xs:element name=\"Paragraph\" type=\"xs:string\"/>\n" +
            "            </xs:sequence>\n" +
            "        </xs:complexType>\n" +
            "    </xs:element>\n" +
            "</xs:schema>";
    final String CONTENT = "<Document>\n" +
            "    <Paragraph>Hello world!</Paragraph>\n" +
            "</Document>";
    final String DOC = "<?xml version='1.0' encoding='UTF-8'?>\n"+CONTENT;
            

    StringWriter strw = new StringWriter();
    XMLStreamWriter2 xmlWriter = getSchemaValidatingWriter(strw, SCHEMA, false);
    XMLStreamReader2 xmlReader = constructNsStreamReader(DOC, false);

    // For this test we need validation, otherwise the reader returns characters events instead of white-space events.
    xmlReader.validateAgainst(parseW3CSchema(SCHEMA));

    while (xmlReader.hasNext()) {
        /*int type =*/ xmlReader.next();
        xmlWriter.copyEventFromReader(xmlReader, true);
    }
 
    xmlWriter.close();
    xmlReader.close();

    String xml = strw.toString();
    if (!xml.contains(CONTENT)) {
        fail("Should contain ["+CONTENT+"], does not: ["+xml+"]");
    }
}
 
Example 4
Source File: BaseValidationTest.java    From woodstox with Apache License 2.0 5 votes vote down vote up
protected void verifyFailure(String xml, XMLValidationSchema schema, String failMsg,
                             String failPhrase, boolean strict) throws XMLStreamException
{
    XMLStreamReader2 sr = constructStreamReader(getInputFactory(), xml);
    sr.validateAgainst(schema);
    try {
        while (sr.hasNext()) {
            /* int type = */sr.next();
        }
        fail("Expected validity exception for " + failMsg);
    } catch (XMLValidationException vex) {
        String origMsg = vex.getMessage();
        String msg = (origMsg == null) ? "" : origMsg.toLowerCase();
        if (msg.indexOf(failPhrase.toLowerCase()) < 0) {
            String actualMsg = "Expected validation exception for "
                + failMsg + ", containing phrase '" + failPhrase
                + "': got '" + origMsg + "'";
            if (strict) {
                fail(actualMsg);
            }
            warn("suppressing failure due to MSV bug, failure: '"
                 + actualMsg + "'");
        }
        // should get this specific type; not basic stream exception
    } catch (XMLStreamException sex) {
        fail("Expected XMLValidationException for " + failMsg
             + "; instead got " + sex.getMessage());
    }
}
 
Example 5
Source File: TestDTD.java    From woodstox with Apache License 2.0 5 votes vote down vote up
public void testFullValidationOk() throws XMLStreamException
{
    String XML = "<root attr='123'><leaf /></root>";
    XMLValidationSchema schema = parseDTDSchema(SIMPLE_DTD);
    XMLStreamReader2 sr = getReader(XML);
    sr.validateAgainst(schema);
    while (sr.next() != END_DOCUMENT) { }
    sr.close();
}
 
Example 6
Source File: TestDTD.java    From woodstox with Apache License 2.0 5 votes vote down vote up
public void testFullValidationIssue23() throws XMLStreamException
{
    final String INPUT_DTD = "<!ELEMENT FreeFormText (#PCDATA) >\n"
            +"<!ATTLIST FreeFormText  xml:lang CDATA #IMPLIED >\n"
            ;
    String XML = "<FreeFormText xml:lang='en-US'>foobar</FreeFormText>";
    XMLInputFactory f = getInputFactory();

    /*
    Resolver resolver = new XMLResolver() {
        @Override
        public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) {
            return new StringReader(DTD);
        }
    };
    f.setXMLResolver(resolver);
    */

    XMLValidationSchemaFactory schemaFactory =
            XMLValidationSchemaFactory.newInstance(XMLValidationSchema.SCHEMA_ID_DTD);
    XMLValidationSchema schema = schemaFactory.createSchema(new StringReader(INPUT_DTD));
    XMLStreamReader2 sr = (XMLStreamReader2)f.createXMLStreamReader(
            new StringReader(XML));

    sr.validateAgainst(schema);
    while (sr.next() != END_DOCUMENT) {
        /*
        System.err.println("Curr == "+sr.getEventType());
        if (sr.getEventType() == CHARACTERS) {
            System.err.println(" text: "+sr.getText());
        }
        */
    }
    sr.close();
}
 
Example 7
Source File: TestDTD.java    From woodstox with Apache License 2.0 5 votes vote down vote up
/**
 * And then a test for validating starting when stream points
 * to START_ELEMENT
 */
public void testPartialValidationOk()
    throws XMLStreamException
{
    String XML = "<root attr='123'><leaf /></root>";
    XMLValidationSchema schema = parseDTDSchema(SIMPLE_DTD);
    XMLStreamReader2 sr = getReader(XML);
    assertTokenType(START_ELEMENT, sr.next());
    sr.validateAgainst(schema);
    while (sr.next() != END_DOCUMENT) { }
    sr.close();
}
 
Example 8
Source File: XmlDumpParser.java    From wikiforia with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parse a MediaWiki header
 * @param xmlReader stream
 * @return header
 */
public static Header readHeader(XMLStreamReader2 xmlReader) {
    try {
        String lang = null;
        String version = null;
        String sitename = null;
        String dbname = null;
        String base = null;
        String generator = null;
        TreeMap<Integer,String> namespaces = new TreeMap<Integer,String>();

        int type;

        while (xmlReader.hasNext()) {
            type = xmlReader.next();

            if (type == XMLEvent.START_ELEMENT)
            {
                String localname = xmlReader.getLocalName();
                if(localname.equals("mediawiki")) {

                    int attributeCount = xmlReader.getAttributeCount();

                    for (int i = 0; i < attributeCount; i++)
                    {
                        String attr = xmlReader.getAttributeLocalName(i);
                        if(attr.equals("lang")) {
                            lang = xmlReader.getAttributeValue(i);
                        }
                        else if(attr.equals("version")) {
                            version = xmlReader.getAttributeValue(i);
                        }
                    }

                    if(lang == null || version == null)
                    {
                        throw new IOError(new IllegalArgumentException("Did not find language and version in supplied header!"));
                    }
                }
                else if(localname.equals("siteinfo")) {
                    while(xmlReader.hasNext()) {
                        type = xmlReader.next();
                        if(type == XMLEvent.START_ELEMENT) {
                            localname = xmlReader.getLocalName();
                            if(localname.equals("sitename"))
                                sitename = xmlReader.getElementText();
                            else if(localname.equals("dbname"))
                                dbname = xmlReader.getElementText();
                            else if(localname.equals("base"))
                                base = xmlReader.getElementText();
                            else if(localname.equals("generator"))
                                generator = xmlReader.getElementText();
                            else if(localname.equals("namespaces")) {
                                while(xmlReader.hasNext()) {
                                    type = xmlReader.nextTag();
                                    if(type == XMLEvent.START_ELEMENT && xmlReader.getLocalName().equals("namespace")) {
                                        int ns_key = Integer.parseInt(xmlReader.getAttributeValue(null, "key"));
                                        String ns_name = xmlReader.getElementText();
                                        namespaces.put(ns_key, ns_name);
                                    }
                                    else if(type == XMLEvent.END_ELEMENT && xmlReader.getLocalName().equals("namespaces")) {
                                        break;
                                    }
                                }
                            }
                        }
                        else if(type == XMLEvent.END_ELEMENT && xmlReader.getLocalName().equals("siteinfo")) {
                            break;
                        }
                    }
                    break;
                }
                else if(localname.equals("page")) {
                    throw new RuntimeException("BUG: Incorrect behaviour, got unexpected page element.");
                }
            }
        }

        if(lang == null)
            throw new IOError(new IllegalArgumentException("Did not find language and version in the header."));
        else
            return new Header(lang, version, new Siteinfo(sitename, dbname, base, generator, namespaces));
    } catch (XMLStreamException e) {
        throw new IOError(e);
    }
}
 
Example 9
Source File: TestDTDErrorCollection104Test.java    From woodstox with Apache License 2.0 4 votes vote down vote up
public void testValidationBeyondUnknownElement() throws Exception
    {
        final String DOC =
                "<map>\n" + 
                "  <val>\n" + 
                "    <prop att=\"product\" val=\"win\" action=\"flag\" color=\"black\"/>\n" +
                "  </val>\n" + 
                "</map>\n";

        final String INPUT_DTD =
"<!ELEMENT map (notval+)>\n"
+"<!ELEMENT notval EMPTY>\n"
;

        XMLInputFactory f = getInputFactory();
        setCoalescing(f, true);

        XMLValidationSchemaFactory schemaFactory =
                XMLValidationSchemaFactory.newInstance(XMLValidationSchema.SCHEMA_ID_DTD);
        XMLValidationSchema schema = schemaFactory.createSchema(new StringReader(INPUT_DTD));
        XMLStreamReader2 sr = (XMLStreamReader2)f.createXMLStreamReader(
                new StringReader(DOC));

        final List<XMLValidationProblem> probs = new ArrayList<XMLValidationProblem>();
        
        sr.validateAgainst(schema);
        sr.setValidationProblemHandler(new ValidationProblemHandler() {
            @Override
            public void reportProblem(XMLValidationProblem problem)
                    throws XMLValidationException {
                probs.add(problem);
            }
        });

        assertTokenType(START_ELEMENT, sr.next());
        assertEquals("map", sr.getLocalName());

        sr.next(); // SPACE or CHARACTERS
        assertTokenType(START_ELEMENT, sr.next());
        assertEquals("val", sr.getLocalName());
        assertEquals(1, probs.size());
        assertEquals("Undefined element <val> encountered", 
                probs.get(0).getMessage());

        sr.next(); // SPACE or CHARACTERS
        assertEquals(1, probs.size());

        // From this point on, however, behavior bit unclear except
        // that for DTD I guess we can at least check for undefined
        // cases....
        
        assertTokenType(START_ELEMENT, sr.next());
        assertEquals("prop", sr.getLocalName());
        // <prop> not defined either so:
        assertEquals(2, probs.size());
        assertEquals("Undefined element <prop> encountered", 
                probs.get(1).getMessage());

        assertTokenType(END_ELEMENT, sr.next());
        assertEquals("prop", sr.getLocalName());
        assertEquals(2, probs.size());

        sr.next(); // SPACE or CHARACTERS
        assertEquals(2, probs.size());
        assertTokenType(END_ELEMENT, sr.next());
        assertEquals("val", sr.getLocalName());
        assertEquals(2, probs.size());
        
        sr.next(); // SPACE or CHARACTERS
        assertTokenType(END_ELEMENT, sr.next());
        assertEquals("map", sr.getLocalName());
        assertEquals(3, probs.size());
        assertEquals("Validation error, element </map>: Expected at least one element <notval>", 
                probs.get(2).getMessage());

        // Plus content model now missing <notval>(s)
        assertTokenType(END_DOCUMENT, sr.next());
        assertEquals(3, probs.size());

        sr.close();
    }