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
28 import org.xml.sax.SAXException;
29 import org.xml.sax.XMLReader;
30 import org.xml.sax.helpers.XMLReaderFactory;
31
32
33
34
35
36
37
38 public abstract class SchemaLoaderUtils {
39
40
41
42
43
44
45
46
47
48
49
50
51 public static Schema loadSchema(Resource resource, String schemaLanguage) throws IOException, SAXException {
52 return loadSchema(new Resource[]{resource}, schemaLanguage);
53 }
54
55
56
57
58
59
60
61
62
63
64
65
66 public static Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
67 Assert.notEmpty(resources, "No resources given");
68 Assert.hasLength(schemaLanguage, "No schema language provided");
69 Source[] schemaSources = new Source[resources.length];
70 XMLReader xmlReader = XMLReaderFactory.createXMLReader();
71 xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
72 for (int i = 0; i < resources.length; i++) {
73 Assert.notNull(resources[i], "Resource is null");
74 Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist");
75 schemaSources[i] = new ResourceSource(xmlReader, resources[i]);
76 }
77 SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
78 return schemaFactory.newSchema(schemaSources);
79 }
80
81
82 public static String getSystemId(Resource resource) {
83 try {
84 return resource.getURL().toString();
85 }
86 catch (IOException e) {
87 return null;
88 }
89 }
90 }