mirror of https://github.com/jacekkow/keycloak-protocol-cas

Jacek Kowalski
2023-11-24 eda11afe10b463af8fc93991f8eb2dd77fbc2c21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package org.keycloak.protocol.cas;
 
import org.glassfish.jaxb.runtime.v2.util.FatalAdapter;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.StringReader;
 
public abstract class XMLValidator {
    private XMLValidator(){}
 
    public static Schema schemaFromClassPath(String path) throws SAXException {
        return SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(XMLValidator.class.getResource(path));
    }
 
    /**
     * Parse XML document and validate against CAS schema
     */
    public static Document parseAndValidate(String xml, Schema schema) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setSchema(schema);
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler(new FatalAdapter(new DefaultHandler()));
        return builder.parse(new InputSource(new StringReader(xml)));
    }
}