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

The following examples show how to use org.codehaus.stax2.XMLStreamReader2#validateAgainst() . 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: TestWsdlValidation.java    From woodstox with Apache License 2.0 6 votes vote down vote up
public void testWsdlValidation() throws Exception {
	String runMe = System.getProperty("testWsdlValidation");
	if (runMe == null || "".equals(runMe)) {
		return;
	}
	XMLInputFactory2 factory = getInputFactory();
	XMLStreamReader2 reader = (XMLStreamReader2) factory.createXMLStreamReader(getClass().getResourceAsStream("test-message.xml"), "utf-8");
	QName msgQName = new QName("http://server.hw.demo/", "sayHi");
	while (true) {
		int what = reader.nextTag();
		if (what == XMLStreamConstants.START_ELEMENT) {
			if (reader.getName().equals(msgQName)) {
				reader.validateAgainst(schema);
			}
		} else if (what == XMLStreamConstants.END_ELEMENT) {
			if (reader.getName().equals(msgQName)) {
				reader.stopValidatingAgainst(schema);
			}
		} else if (what == XMLStreamConstants.END_DOCUMENT) {
			break;
		}
	}
}
 
Example 2
Source File: Stax2ValidationUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws XMLStreamException
 */
public boolean setupValidation(XMLStreamReader reader, Endpoint endpoint, ServiceInfo serviceInfo)
        throws XMLStreamException {

    // Gosh, this is bad, but I don't know a better solution, unless we're willing
    // to require the stax2 API no matter what.
    XMLStreamReader effectiveReader = reader;
    if (effectiveReader instanceof DepthXMLStreamReader) {
        effectiveReader = ((DepthXMLStreamReader) reader).getReader();
    }
    final XMLStreamReader2 reader2 = (XMLStreamReader2) effectiveReader;
    XMLValidationSchema vs = getValidator(endpoint, serviceInfo);
    if (vs == null) {
        return false;
    }
    reader2.setValidationProblemHandler(new ValidationProblemHandler() {

        public void reportProblem(XMLValidationProblem problem) throws XMLValidationException {
            throw new Fault(new Message("READ_VALIDATION_ERROR", LOG, problem.getMessage()),
                    Fault.FAULT_CODE_CLIENT);
        }
    });
    reader2.validateAgainst(vs);
    return true;
}
 
Example 3
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 4
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 5
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 6
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 7
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 8
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 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();
    }
 
Example 10
Source File: TestW3CSchemaComplexTypes.java    From woodstox with Apache License 2.0 4 votes vote down vote up
/**
	 * For problem with MSV: https://github.com/kohsuke/msv/issues/2
	 *
	 * 29-Mar-2018, tatu: Oddly enough, problem itself allegedly resolved...
	 */
    public void testMSVGithubIssue2() throws Exception
    {
        XMLValidationSchema schema = parseW3CSchema(
"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:tns='http://MySchema' elementFormDefault='qualified' targetNamespace='http://MySchema' version='1.0'>"
+"<xs:element name='Root' type='tns:Root'/>"
+"<xs:complexType name='Root'>"
+"    <xs:sequence>"
+"      <xs:element minOccurs='0' name='Child' type='xs:anyType'/>"
+"    </xs:sequence>"
+"</xs:complexType>"
+"<xs:complexType abstract='true' name='Child'>"
+"<xs:complexContent>"
+"  <xs:extension base='tns:Base'>"
+"    <xs:sequence/>"
+"  </xs:extension>"
+"</xs:complexContent>"
+"</xs:complexType>"
+"<xs:complexType abstract='true' name='Base'>"
+"<xs:sequence/>"
+"</xs:complexType>"
+"<xs:complexType name='ChildInst'>"
+"<xs:complexContent>"
+"  <xs:extension base='tns:Child'>"
+"    <xs:sequence>"
+"    </xs:sequence>"
+"  </xs:extension>"
+"</xs:complexContent>"
+"</xs:complexType>"
+"</xs:schema>");
        XMLStreamReader2 sr = getReader("<ns11:Root xmlns:ns11='http://MySchema'>"
            +"<ns11:Child xsi:type='ns11:ChildInst' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>"
            +"</ns11:Child>"
            +"</ns11:Root>");
        sr.validateAgainst(schema);
        
        try {
            assertTokenType(START_ELEMENT, sr.next());
            assertEquals("Root", sr.getLocalName());
            assertTokenType(START_ELEMENT, sr.next());
            assertEquals("Child", sr.getLocalName());
            assertTokenType(END_ELEMENT, sr.next());
            assertTokenType(END_ELEMENT, sr.next());
            assertTokenType(END_DOCUMENT, sr.next());
        } catch (XMLValidationException vex) {
            fail("Did not expect validation exception, got: " + vex);
        }
        assertTokenType(END_DOCUMENT, sr.getEventType());        
    }