1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.xml.validation;
18
19 import java.io.IOException;
20 import javax.xml.transform.Source;
21 import javax.xml.validation.Schema;
22 import javax.xml.validation.SchemaFactory;
23
24 import org.springframework.core.io.Resource;
25 import org.springframework.util.Assert;
26 import org.springframework.xml.transform.ResourceSource;
27 import org.xml.sax.SAXException;
28 import org.xml.sax.XMLReader;
29 import org.xml.sax.helpers.XMLReaderFactory;
30
31
32
33
34
35
36
37 public abstract class SchemaLoaderUtils {
38
39
40
41
42
43
44
45
46
47
48
49
50 public static Schema loadSchema(Resource resource, String schemaLanguage) throws IOException, SAXException {
51 return loadSchema(new Resource[]{resource}, schemaLanguage);
52 }
53
54
55
56
57
58
59
60
61
62
63
64
65 public static Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
66 Assert.notEmpty(resources, "No resources given");
67 Assert.hasLength(schemaLanguage, "No schema language provided");
68 Source[] schemaSources = new Source[resources.length];
69 XMLReader xmlReader = XMLReaderFactory.createXMLReader();
70 xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
71 for (int i = 0; i < resources.length; i++) {
72 Assert.notNull(resources[i], "Resource is null");
73 Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist");
74 schemaSources[i] = new ResourceSource(xmlReader, resources[i]);
75 }
76 SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
77 return schemaFactory.newSchema(schemaSources);
78 }
79
80
81 public static String getSystemId(Resource resource) {
82 try {
83 return resource.getURL().toString();
84 }
85 catch (IOException e) {
86 return null;
87 }
88 }
89 }