1
2
3
4
5
6
7
8
9
10
11 package org.mule.config.spring;
12
13 import org.mule.tck.junit4.AbstractMuleTestCase;
14 import org.mule.util.IOUtils;
15
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.text.MessageFormat;
19 import java.util.Iterator;
20 import java.util.Map;
21
22 import javax.xml.XMLConstants;
23 import javax.xml.transform.Source;
24 import javax.xml.transform.stream.StreamSource;
25 import javax.xml.validation.Schema;
26 import javax.xml.validation.SchemaFactory;
27
28 import org.apache.commons.collections.map.HashedMap;
29 import org.junit.Before;
30 import org.junit.Test;
31 import org.xml.sax.SAXException;
32 import org.xml.sax.SAXParseException;
33
34 import static org.junit.Assert.assertNotNull;
35
36 public abstract class AbstractSchemaValidationTestCase extends AbstractMuleTestCase
37 {
38
39 public static final String SEPARATOR = " ";
40 protected Map schemas = new HashedMap();
41
42
43 @Before
44 public void setUpSchemas()
45 {
46 addSchema("http://www.mulesoft.org/schema/mule/core", "META-INF/mule.xsd");
47 }
48
49 protected void addSchema(String name, String location)
50 {
51 schemas.put(name, location);
52 }
53
54 protected Source[] getSchemasAsSources() throws IOException
55 {
56 Source[] sources = new Source[schemas.size()];
57 int index = 0;
58 for (Iterator keys = schemas.keySet().iterator(); keys.hasNext();)
59 {
60 String name = (String) keys.next();
61 String location = (String) schemas.get(name);
62 sources[index++] = load(location);
63 }
64 return sources;
65 }
66
67 protected void doTest(String config) throws SAXException, IOException
68 {
69 try
70 {
71 SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
72 schemaFactory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
73 Schema schema = schemaFactory.newSchema(getSchemasAsSources());
74 schema.newValidator().validate(load(config));
75 }
76 catch (SAXParseException ex)
77 {
78 System.err.println(MessageFormat.format("SAX parsing exception occurs at line {0}, column {1}",
79 ex.getLineNumber(), ex.getColumnNumber()));
80 throw ex;
81 }
82 }
83
84 protected Source load(String name) throws IOException
85 {
86 InputStream stream = IOUtils.getResourceAsStream(name, getClass());
87 assertNotNull("Cannot load " + name, stream);
88 return new StreamSource(stream);
89 }
90
91 @Test
92 public void testSchemaLocations() throws IOException
93 {
94 for (Iterator keys = schemas.keySet().iterator(); keys.hasNext();)
95 {
96 String name = (String) keys.next();
97 String location = (String) schemas.get(name);
98 logger.debug("checking " + location + " for " + name);
99 InputStream stream = IOUtils.getResourceAsStream(location, getClass());
100 assertNotNull("Cannot load " + location + " for " + name, stream);
101 stream.close();
102 }
103 }
104
105 }