1 package org.apache.maven.plugin.changes.schema;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.File;
23 import java.io.FileReader;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.Map;
27
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.codehaus.plexus.util.FastMap;
34 import org.xml.sax.SAXException;
35
36
37
38
39
40
41
42
43
44 public class DefaultChangesSchemaValidator
45 implements ChangesSchemaValidator
46 {
47
48
49 public static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
50
51 public static final String CHANGES_SCHEMA_PATH = "META-INF/changes/xsd/";
52
53 private Map compiledSchemas = new FastMap();
54
55 public XmlValidationHandler validateXmlWithSchema( File file, String schemaVersion, boolean failOnValidationError )
56 throws SchemaValidatorException
57 {
58 try
59 {
60 String schemaPath = CHANGES_SCHEMA_PATH + "changes-" + schemaVersion + ".xsd";
61
62 Schema schema = getSchema( schemaPath );
63
64 Validator validator = schema.newValidator();
65
66 XmlValidationHandler baseHandler = new XmlValidationHandler( failOnValidationError );
67
68 validator.setErrorHandler( baseHandler );
69
70 validator.validate( new StreamSource( new FileReader( file ) ) );
71
72 return baseHandler;
73 }
74 catch ( IOException e )
75 {
76 throw new SchemaValidatorException( "IOException : " + e.getMessage(), e );
77 }
78 catch ( SAXException e )
79 {
80 throw new SchemaValidatorException( "SAXException : " + e.getMessage(), e );
81 }
82 catch ( Exception e )
83 {
84 throw new SchemaValidatorException( "Exception : " + e.getMessage(), e );
85 }
86 }
87
88 public Schema getSchema( String schemaPath )
89 throws SAXException
90 {
91 if ( this.compiledSchemas.containsKey( schemaPath ) )
92 {
93 return (Schema) this.compiledSchemas.get( schemaPath );
94 }
95 Schema schema = this.compileJAXPSchema( schemaPath );
96
97 this.compiledSchemas.put( schemaPath, schema );
98
99 return schema;
100 }
101
102
103
104
105
106
107 private Schema compileJAXPSchema( String uriSchema )
108 throws SAXException, NullPointerException
109 {
110
111 InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( uriSchema );
112
113 if ( is == null )
114 {
115 throw new NullPointerException( " impossible to load schema with path " + uriSchema );
116 }
117
118
119 return SchemaFactory.newInstance( W3C_XML_SCHEMA ).newSchema( new StreamSource( is ) );
120
121 }
122
123
124
125
126 public void loadSchema( String uriSchema )
127 throws SchemaValidatorException
128 {
129 try
130 {
131 this.getSchema( uriSchema );
132 }
133 catch ( SAXException e )
134 {
135 throw new SchemaValidatorException( "SAXException : " + e.getMessage(), e );
136 }
137
138 }
139
140
141 }