Java Code Examples for javax.xml.validation.ValidatorHandler#setContentHandler()

The following examples show how to use javax.xml.validation.ValidatorHandler#setContentHandler() . 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: AbstractXmlValidator.java    From iaf with Apache License 2.0 6 votes vote down vote up
public String validate(Object input, IPipeLineSession session, String logPrefix, ValidatorHandler validatorHandler, XMLFilterImpl filter, ValidationContext context) throws XmlValidatorException, PipeRunException, ConfigurationException {

		if (filter != null) {
			// If a filter is present, connect its output to the context.contentHandler.
			// It is assumed that the filter input is already properly connected.
			filter.setContentHandler(context.getContentHandler());
			filter.setErrorHandler(context.getErrorHandler());
		} else {
			validatorHandler.setContentHandler(context.getContentHandler());
		}
		validatorHandler.setErrorHandler(context.getErrorHandler());

		InputSource is = getInputSource(Message.asMessage(input));

		return validate(is, validatorHandler, session, context);
	}
 
Example 2
Source File: EdfiRecordParserImpl2.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
private void parseAndValidate(InputStream input, Schema schema) throws XmlParseException, IOException {
    ValidatorHandler vHandler = schema.newValidatorHandler();
    vHandler.setContentHandler(this);
    vHandler.setErrorHandler(this);

    InputSource is = new InputSource(new InputStreamReader(input, "UTF-8"));
    is.setEncoding("UTF-8");

    try {
        XMLReader parser = XMLReaderFactory.createXMLReader();
        parser.setContentHandler(vHandler);
        parser.setErrorHandler(this);

        vHandler.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false);

        parser.setFeature("http://apache.org/xml/features/validation/id-idref-checking", false);
        parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false);
        parser.setFeature("http://xml.org/sax/features/external-general-entities", false);
        parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

        parser.parse(is);
    } catch (SAXException e) {
        throw new XmlParseException(e.getMessage(), e);
    }
}
 
Example 3
Source File: Bug4970951.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    XMLReader xmlReader = createXMLReader();
    final ValidatorHandler validatorHandler = createValidatorHandler(XSD);
    xmlReader.setContentHandler(validatorHandler);

    DefaultHandler handler = new DefaultHandler() {
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if (!"ns:test".equals(qName)) {
                return;
            }

            TypeInfoProvider infoProvider = validatorHandler.getTypeInfoProvider();
            if (infoProvider == null) {
                throw new SAXException("Can't obtain TypeInfoProvider object.");
            }

            int index = attributes.getIndex("id");
            if (index == -1) {
                throw new SAXException("The attribute 'id' is not in the list.");
            }

            Assert.assertTrue(infoProvider.isSpecified(index));

            index = attributes.getIndex("date");
            if (index == -1) {
                throw new SAXException("The attribute 'date' is not in the list.");
            }

            Assert.assertFalse(infoProvider.isSpecified(index));

            System.out.println("OK");
        }
    };
    validatorHandler.setContentHandler(handler);

    parse(xmlReader, XML);
}
 
Example 4
Source File: Bug4969732.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test1() throws Exception {
    XMLReader xmlReader = createXMLReader();
    final ValidatorHandler validatorHandler = createValidatorHandler(XSD);
    xmlReader.setContentHandler(validatorHandler);

    DefaultHandler handler = new DefaultHandler() {
        public void characters(char[] ch, int start, int length) throws SAXException {
            TypeInfoProvider infoProvider = null;
            synchronized (validatorHandler) {
                infoProvider = validatorHandler.getTypeInfoProvider();
            }
            if (infoProvider == null) {
                Assert.fail("Can't obtain TypeInfo object.");
            }

            try {
                infoProvider.getElementTypeInfo();
                Assert.fail("IllegalStateException was not thrown.");
            } catch (IllegalStateException e) {
                // as expected
                System.out.println("OK");
            }
        }
    };
    validatorHandler.setContentHandler(handler);

    parse(xmlReader, XML);
}
 
Example 5
Source File: ValidatorHandlerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testContentHandler() {
    ValidatorHandler validatorHandler = getValidatorHandler();
    assertNull(validatorHandler.getContentHandler(), "When ValidatorHandler is created, initially ContentHandler should not be set.");

    ContentHandler handler = new DefaultHandler();
    validatorHandler.setContentHandler(handler);
    assertSame(validatorHandler.getContentHandler(), handler);

    validatorHandler.setContentHandler(null);
    assertNull(validatorHandler.getContentHandler());

}
 
Example 6
Source File: XmlValidator.java    From iaf with Apache License 2.0 5 votes vote down vote up
protected PipeForward validate(String messageToValidate, IPipeLineSession session, boolean responseMode) throws XmlValidatorException, PipeRunException, ConfigurationException {
	ValidationContext context = validator.createValidationContext(session, getRootValidations(responseMode), getInvalidRootNamespaces());
	ValidatorHandler validatorHandler = validator.getValidatorHandler(session, context);
	XMLFilterImpl storeRootFilter = StringUtils.isNotEmpty(getRootElementSessionKey()) ? new RootElementToSessionKeyFilter(session, getRootElementSessionKey(), getRootNamespaceSessionKey(), null) : null;
	if (storeRootFilter!=null) {
		validatorHandler.setContentHandler(storeRootFilter);
	}
	String resultEvent = validator.validate(messageToValidate, session, getLogPrefix(session), validatorHandler, storeRootFilter, context);
	return determineForward(resultEvent, session, responseMode);
}
 
Example 7
Source File: XmlAligner.java    From iaf with Apache License 2.0 4 votes vote down vote up
public XmlAligner(ValidatorHandler psviProvidingValidatorHandler) {
	this((PSVIProvider)psviProvidingValidatorHandler);
	psviProvidingValidatorHandler.setContentHandler(this);
}
 
Example 8
Source File: TestDomTreeAligner.java    From iaf with Apache License 2.0 4 votes vote down vote up
@Override
	public void testFiles(String schemaFile, String namespace, String rootElement, String inputFile, boolean potentialCompactionProblems, String expectedFailureReason) throws Exception {
		URL schemaUrl=getSchemaURL(schemaFile);
    	String xsdUri=schemaUrl.toExternalForm();
    	Schema schema = Utils.getSchemaFromResource(schemaUrl);

    	XMLSchemaLoader xsLoader = new XMLSchemaLoader();
		XSModel xsModel = xsLoader.loadURI(xsdUri);
		List<XSModel> schemaInformation= new LinkedList<XSModel>();
		schemaInformation.add(xsModel);
   	
    	String xmlString=getTestFile(inputFile+".xml");
    	
    	boolean expectValid=expectedFailureReason==null;
    	
    	assertEquals("valid XML", expectValid, Utils.validate(schemaUrl, xmlString));
 	

    	ValidatorHandler validator = schema.newValidatorHandler();
    	DomTreeAligner aligner = new DomTreeAligner(validator, schemaInformation);
 //   	Xml2Json xml2json = new Xml2Json(aligner, false);
    	
    	validator.setContentHandler(aligner);
//    	aligner.setContentHandler(xml2json);
 
    	Document domIn = Utils.string2Dom(xmlString);
    	System.out.println("input DOM ["+Utils.dom2String1(domIn)+"]");
//    	System.out.println("xmlString "+xmlString);
//    	System.out.println("dom in "+ToStringBuilder.reflectionToString(domIn.getDocumentElement()));
    	Source source=aligner.asSource(domIn);
    	System.out.println();
    	System.out.println("start aligning "+inputFile);
   	
		
    	String xmlAct = Utils.source2String(source);
    	System.out.println("xml aligned via source="+xmlAct);
    	assertNotNull("xmlAct is null",xmlAct);
    	assertTrue("XML is not aligned",  Utils.validate(schemaUrl, xmlAct));

//    	InputSource is = new InputSource(new StringReader(xmlString));
//    	try {
// //       	String jsonOut=xml2json.toString();
//        	System.out.println("jsonOut="+jsonOut);
//        	if (!expectValid) {
//    			fail("expected to fail");
//    		}
//    	} catch (Exception e) {
//    		if (expectValid) {
//    			e.printStackTrace();
//    			fail(e.getMessage());
//    		}
//    	}
//    	String xmlString=getTestXml(xml);
//    	String xsdUri=Utils.class.getResource(xsd).toExternalForm();
//    	
//    	assertEquals("valid XML", expectValid, Utils.validate(namespace, xsdUri, xmlString));
//    	
//    	Document dom = Utils.string2Dom(xmlString);
//    	Utils.clean(dom);
//    	
//    	XMLReader parser = new SAXParser();
//    	Schema schema=Utils.getSchemaFromResource(namespace, xsdUri);
//    	ValidatorHandler validator = schema.newValidatorHandler();
//    	XmlAligner instance = implementation.newInstance();
//    	instance.setPsviProvider((PSVIProvider)validator);
//    	
//    	parser.setContentHandler(validator);
//    	validator.setContentHandler(instance);
//    	
//    	System.out.println();
//    	System.out.println("start aligning "+xml);

//    	instance.parse(dom.getDocumentElement());
//    	System.out.println("alignedXml="+Utils.dom2String1(dom));
//    	assertTrue("valid aligned XML", Utils.validate(namespace, xsdUri, dom)); // only if dom  itself is modified...

//    	testXmlAligner(instance, dom.getDocumentElement(), namespace, xsdUri);

//    	JSONObject json=Utils.xml2Json(xmlString);
//    	System.out.println("JSON:"+json);
//    	String jsonString = json.toString();
//    	
//    	jsonString=jsonString.replaceAll(",\"xmlns\":\"[^\"]*\"", "");
//    	System.out.println("JSON with fixed xmlns:"+jsonString);
//    	
//    	String xmlFromJson = Utils.json2Xml(Utils.string2Json(jsonString));
//    	if (StringUtils.isNotEmpty(namespace)) {
//    		xmlFromJson=xmlFromJson.replaceFirst(">", " xmlns=\""+namespace+"\">");
//    	}
//    	System.out.println("start aligning xml from json "+xmlFromJson);
//    	Document domFromJson = Utils.string2Dom(xmlFromJson);
//    	instance.startParse(domFromJson.getDocumentElement());
    	
    }
 
Example 9
Source File: EdfiRecordUnmarshaller.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
@Override
protected void parseAndValidate(InputStream input, ValidatorHandler vHandler) throws XmlParseException, IOException {
    vHandler.setContentHandler(this);

    super.parseAndValidate(input, vHandler);
}