1 /***
2 * Copyright 2003-2010 Terracotta, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package net.sf.ehcache.config;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.InputStream;
22
23 import javax.xml.XMLConstants;
24 import javax.xml.parsers.DocumentBuilder;
25 import javax.xml.parsers.DocumentBuilderFactory;
26 import javax.xml.transform.Source;
27 import javax.xml.transform.dom.DOMSource;
28 import javax.xml.transform.stream.StreamSource;
29 import javax.xml.validation.Schema;
30 import javax.xml.validation.SchemaFactory;
31 import javax.xml.validation.Validator;
32
33 import org.junit.Test;
34 import org.w3c.dom.Document;
35
36 /***
37 * Tests that the Ehcache schema passes validation
38 *
39 * @author Alex Miller
40 */
41 public class SchemaValidationTest {
42
43 private static final String SRC_CONFIG_DIR = "src/main/config/";
44
45 /***
46 * Test that schema validates
47 */
48 @Test
49 public void testSchemaValidates() throws Exception {
50 InputStream docStream = new FileInputStream(new File(SRC_CONFIG_DIR + "ehcache.xml").getAbsolutePath());
51 InputStream xsdStream = new FileInputStream(new File(SRC_CONFIG_DIR + "ehcache.xsd").getAbsolutePath());
52
53 try {
54
55 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
56 docFactory.setNamespaceAware(true);
57 DocumentBuilder parser = docFactory.newDocumentBuilder();
58 Document document = parser.parse(docStream);
59
60
61 SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
62
63
64 Source schemaFile = new StreamSource(xsdStream);
65 Schema schema = factory.newSchema(schemaFile);
66
67
68 Validator validator = schema.newValidator();
69
70
71 validator.validate(new DOMSource(document));
72
73 } finally {
74 docStream.close();
75 xsdStream.close();
76 }
77 }
78 }