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

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