Debian Codegraph @

src/main/java/com/ctc/wstx/msv/GenericMsvValidator.java

raw
1 /* Woodstox XML processor
2 *
3 * Copyright (c) 2004- Tatu Saloranta, [email protected]
4 *
5 * Licensed under the License specified in the file LICENSE which is
6 * included with the source code.
7 * You may not use this file except in compliance with the License.
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package com.ctc.wstx.msv;
17
18 import java.util.*;
19
20 import javax.xml.namespace.QName;
21 import javax.xml.stream.Location;
22 import javax.xml.stream.XMLStreamConstants;
23 import javax.xml.stream.XMLStreamException;
24
25 import org.codehaus.stax2.validation.*;
26 import org.relaxng.datatype.Datatype;
27
28 import com.sun.msv.grammar.IDContextProvider2;
29 import com.sun.msv.util.DatatypeRef;
30 import com.sun.msv.util.StartTagInfo;
31 import com.sun.msv.util.StringRef;
32 import com.sun.msv.verifier.Acceptor;
33 import com.sun.msv.verifier.DocumentDeclaration;
34 import com.sun.msv.verifier.regexp.StringToken;
35 import com.ctc.wstx.util.ElementId;
36 import com.ctc.wstx.util.ElementIdMap;
37 import com.ctc.wstx.util.PrefixedName;
38 import com.ctc.wstx.util.TextAccumulator;
39
40 /**
41 * Generic validator instance to be used for all Multi-Schema Validator
42 * backed implementations. A common class can be used since functionality
43 * is almost identical between variants (RNG, W3C SChema); minor
44 * differences that exist can be configured by settings provided.
45 *<p>
46 * Note about id context provider interface: while it'd be nice to
47 * separate that part out, it is unfortunately closely tied to the
48 * validation process. Hence it's directly implemented by this class.
49 */
50 public final class GenericMsvValidator
51 extends XMLValidator
52 implements com.sun.msv.grammar.IDContextProvider2,
53 XMLStreamConstants
54 {
55 /*
56 ///////////////////////////////////////////////////////////
57 // Configuration
58 ///////////////////////////////////////////////////////////
59 */
60
61 final XMLValidationSchema mParentSchema;
62
63 final ValidationContext mContext;
64
65 final DocumentDeclaration mVGM;
66
67 /*
68 ///////////////////////////////////////////////////////////
69 // State, helper objects
70 ///////////////////////////////////////////////////////////
71 */
72
73 final ArrayList<Object> mAcceptors = new ArrayList<Object>();
74
75 Acceptor mCurrAcceptor = null;
76
77 final TextAccumulator mTextAccumulator = new TextAccumulator();
78
79 /**
80 * Map that contains information about element id (values of attributes
81 * or textual content with type ID) declarations and references
82 */
83 ElementIdMap mIdDefs;
84
85 /*
86 ///////////////////////////////////////////////////////////
87 // State, positions
88 ///////////////////////////////////////////////////////////
89 */
90
91 String mCurrAttrPrefix;
92
93 String mCurrAttrLocalName;
94
95 /**
96 * Sometimes a problem object has to be temporarily
97 * stored, and only reported later on. This happens
98 * when exceptions can not be thrown via code outside
99 * of Woodstox (like validation methods in MSV that do
100 * callbacks).
101 */
102 XMLValidationProblem mProblem;
103
104 /*
105 ///////////////////////////////////////////////////////////
106 // Helper objects
107 ///////////////////////////////////////////////////////////
108 */
109
110 final StringRef mErrorRef = new StringRef();
111
112 /**
113 * StartTagInfo instance need not be thread-safe, and it is not immutable
114 * so let's reuse one instance during a single validation.
115 */
116 final StartTagInfo mStartTag = new StartTagInfo("", "", "", null, (IDContextProvider2) null);
117
118 /**
119 * Since `StartTagInfo` has no place for prefix, hold reference to one here
120 */
121 protected String mStartTagPrefix = "";
122
123 /**
124 * This object provides limited access to attribute values of the
125 * currently validated element.
126 */
127 final AttributeProxy mAttributeProxy;
128
129 /*
130 ///////////////////////////////////////////////////////////
131 // Construction, configuration
132 ///////////////////////////////////////////////////////////
133 */
134
135 public GenericMsvValidator(XMLValidationSchema parent, ValidationContext ctxt,
136 DocumentDeclaration vgm)
137 {
138 mParentSchema = parent;
139 mContext = ctxt;
140 mVGM = vgm;
141
142 mCurrAcceptor = mVGM.createAcceptor();
143 mAttributeProxy = new AttributeProxy(ctxt);
144 }
145
146 /*
147 ///////////////////////////////////////////////////////////
148 // IDContextProvider2 implementation:
149 //
150 // Core RelaxNG ValidationContext implementation
151 // (org.relaxng.datatype.ValidationContext, base interface
152 // of the id provider context)
153 ///////////////////////////////////////////////////////////
154 */
155
156 @Override
157 public String getBaseUri() {
158 return mContext.getBaseUri();
159 }
160
161 @Override
162 public boolean isNotation(String notationName) {
163 return mContext.isNotationDeclared(notationName);
164 }
165
166 @Override
167 public boolean isUnparsedEntity(String entityName) {
168 return mContext.isUnparsedEntityDeclared(entityName);
169 }
170
171 @Override
172 public String resolveNamespacePrefix(String prefix) {
173 return mContext.getNamespaceURI(prefix);
174 }
175
176 /*
177 ///////////////////////////////////////////////////////////
178 // IDContextProvider2 implementation, extensions over
179 // core ValidationContext
180 ///////////////////////////////////////////////////////////
181 */
182
183 /**
184 *<p>
185 * Note: we have to throw a dummy marker exception, which merely
186 * signals that a validation problem is to be reported.
187 * This is obviously messy, but has to do for now.
188 */
189 @Override
190 public void onID(Datatype datatype, StringToken idToken)
191 throws IllegalArgumentException
192 {
193 if (mIdDefs == null) {
194 mIdDefs = new ElementIdMap();
195 }
196
197 int idType = datatype.getIdType();
198 Location loc = mContext.getValidationLocation();
199 PrefixedName elemPName = getElementPName();
200 PrefixedName attrPName = getAttrPName();
201
202 if (idType == Datatype.ID_TYPE_ID) {
203 String idStr = idToken.literal.trim();
204 ElementId eid = mIdDefs.addDefined(idStr, loc, elemPName, attrPName);
205 // We can detect dups by checking if Location is the one we passed:
206 if (eid.getLocation() != loc) {
207 mProblem = new XMLValidationProblem(loc, "Duplicate id '"+idStr+"', first declared at "+eid.getLocation());
208 mProblem.setReporter(this);
209 }
210 } else if (idType == Datatype.ID_TYPE_IDREF) {
211 String idStr = idToken.literal.trim();
212 mIdDefs.addReferenced(idStr, loc, elemPName, attrPName);
213 } else if (idType == Datatype.ID_TYPE_IDREFS) {
214 StringTokenizer tokens = new StringTokenizer(idToken.literal);
215 while (tokens.hasMoreTokens()) {
216 mIdDefs.addReferenced(tokens.nextToken(), loc, elemPName, attrPName);
217 }
218 } else { // sanity check
219 throw new IllegalStateException("Internal error: unexpected ID datatype: "+datatype);
220 }
221 }
222
223 /*
224 ///////////////////////////////////////////////////////////
225 // XMLValidator implementation
226 ///////////////////////////////////////////////////////////
227 */
228
229 @Override
230 public XMLValidationSchema getSchema() {
231 return mParentSchema;
232 }
233
234 /**
235 * Method called to update information about the newly encountered (start)
236 * element. At this point namespace information has been resolved, but
237 * no DTD validation has been done. Validator is to do these validations,
238 * including checking for attribute value (and existence) compatibility.
239 */
240 @Override
241 public void validateElementStart(String localName, String uri, String prefix)
242 throws XMLStreamException
243 {
244 /* [WSTX-200]: If sub-tree we were to validate has ended, we
245 * have no current acceptor, and must quite. Ideally we would
246 * really handle this more cleanly but...
247 */
248 if (mCurrAcceptor == null) {
249 return;
250 }
251
252 // Very first thing: do we have text collected?
253 if (mTextAccumulator.hasText()) {
254 doValidateText(mTextAccumulator);
255 }
256
257 /* 31-Mar-2006, TSa: MSV seems to require empty String for empty/no
258 * namespace, not null.
259 */
260 if (uri == null) {
261 uri = "";
262 }
263
264 /* Do we need to properly fill it? Or could we just put local name?
265 * Looking at code, I do believe it's only used for error reporting
266 * purposes...
267 */
268 //String qname = (prefix == null || prefix.length() == 0) ? localName : (prefix + ":" +localName);
269 String qname = localName;
270 mStartTag.reinit(uri, localName, qname, mAttributeProxy, this);
271 mStartTagPrefix = prefix;
272
273 mCurrAcceptor = mCurrAcceptor.createChildAcceptor(mStartTag, mErrorRef);
274 /* As per documentation, the side-effect of getting the error message
275 * is that we also get a recoverable non-null acceptor... thus, should
276 * never (?) see null acceptor being returned
277 */
278 if (mErrorRef.str != null) {
279 reportError(mErrorRef, START_ELEMENT, _qname(uri, localName, prefix));
280 }
281 if (mProblem != null) { // pending problems (to throw exception on)?
282 XMLValidationProblem p = mProblem;
283 mProblem = null;
284 mContext.reportProblem(p);
285 }
286 mAcceptors.add(mCurrAcceptor);
287 }
288
289 @Override
290 public String validateAttribute(String localName, String uri,
291 String prefix, String value)
292 throws XMLStreamException
293 {
294 mCurrAttrLocalName = localName;
295 mCurrAttrPrefix = prefix;
296 if (mCurrAcceptor != null) {
297
298 String qname = localName; // for now, let's assume we don't need prefixed version
299 DatatypeRef typeRef = null; // for now, let's not care
300
301 /* 31-Mar-2006, TSa: MSV seems to require empty String for empty/no
302 * namespace, not null.
303 */
304 if (uri == null) {
305 uri = "";
306 }
307
308 if (!mCurrAcceptor.onAttribute2(uri, localName, qname, value, this, mErrorRef, typeRef)
309 || mErrorRef.str != null) {
310 reportError(mErrorRef, ATTRIBUTE, _qname(uri, localName, prefix));
311 }
312 if (mProblem != null) { // pending problems (to throw exception on)?
313 XMLValidationProblem p = mProblem;
314 mProblem = null;
315 mContext.reportProblem(p);
316 }
317 }
318 // No normalization done by RelaxNG, is there? (at least nothing
319 // visible to callers that is)
320 return null;
321 }
322
323 @Override
324 public String validateAttribute(String localName, String uri, String prefix,
325 char[] valueChars, int valueStart, int valueEnd)
326 throws XMLStreamException
327 {
328 int len = valueEnd - valueStart;
329 // This is very sub-optimal... but MSV doesn't deal with char arrays.
330 return validateAttribute(localName, uri, prefix,
331 new String(valueChars, valueStart, len));
332 }
333
334 @Override
335 public int validateElementAndAttributes()
336 throws XMLStreamException
337 {
338 // Not handling any attributes
339 mCurrAttrLocalName = mCurrAttrPrefix = "";
340 if (mCurrAcceptor != null) {
341 /* start tag info is still intact here (only attributes sent
342 * since child acceptor was created)
343 */
344 if (!mCurrAcceptor.onEndAttributes(mStartTag, mErrorRef)
345 || mErrorRef.str != null) {
346 reportError(mErrorRef, XMLStreamConstants.END_ELEMENT, _startTagAsQName());
347 }
348
349 int stringChecks = mCurrAcceptor.getStringCareLevel();
350 switch (stringChecks) {
351 case Acceptor.STRING_PROHIBITED: // only WS
352 return XMLValidator.CONTENT_ALLOW_WS;
353 case Acceptor.STRING_IGNORE: // anything (mixed content models)
354 return XMLValidator.CONTENT_ALLOW_ANY_TEXT;
355 case Acceptor.STRING_STRICT: // validatable (data-oriented)
356 return XMLValidator.CONTENT_ALLOW_VALIDATABLE_TEXT;
357 default:
358 throw new IllegalArgumentException("Internal error: unexpected string care level value return by MSV: "+stringChecks);
359 }
360 }
361
362 // If no acceptor, we are recovering, no need or use to validate text
363 return CONTENT_ALLOW_ANY_TEXT;
364 }
365
366 /**
367 * @return Validation state that should be effective for the parent
368 * element state
369 */
370 @Override
371 public int validateElementEnd(String localName, String uri, String prefix)
372 throws XMLStreamException
373 {
374 // Very first thing: do we have text collected?
375 /* 27-Feb-2009, TSa: [WSTX-191]: Actually MSV expects us to call
376 * validation anyway, in case there might be restriction(s) on
377 * textual content. Otherwise we'll get an error.
378 */
379 doValidateText(mTextAccumulator);
380
381 // [WSTX-200]: need to avoid problems when doing sub-tree
382 // validation... not a proper solution, but has to do for now
383 int lastIx = mAcceptors.size()-1;
384 if (lastIx < 0) {
385 return XMLValidator.CONTENT_ALLOW_WS;
386 }
387 Acceptor acc = (Acceptor)mAcceptors.remove(lastIx);
388 if (acc != null) { // may be null during error recovery? or not?
389 if (!acc.isAcceptState(mErrorRef) || mErrorRef.str != null) {
390 reportError(mErrorRef, XMLStreamConstants.END_ELEMENT, _qname(uri, localName, prefix));
391 }
392 }
393 if (lastIx == 0) { // root closed
394 mCurrAcceptor = null;
395 } else {
396 mCurrAcceptor = (Acceptor) mAcceptors.get(lastIx-1);
397 }
398 if (mCurrAcceptor != null && acc != null) {
399 if (!mCurrAcceptor.stepForward(acc, mErrorRef)
400 || mErrorRef.str != null) {
401 reportError(mErrorRef, XMLStreamConstants.END_ELEMENT, _qname(uri, localName, prefix));
402 }
403 int stringChecks = mCurrAcceptor.getStringCareLevel();
404 switch (stringChecks) {
405 case Acceptor.STRING_PROHIBITED: // only WS
406 return XMLValidator.CONTENT_ALLOW_WS;
407 case Acceptor.STRING_IGNORE: // anything (mixed content models)
408 return XMLValidator.CONTENT_ALLOW_ANY_TEXT;
409 case Acceptor.STRING_STRICT: // validatable (data-oriented)
410 return XMLValidator.CONTENT_ALLOW_VALIDATABLE_TEXT;
411 default:
412 throw new IllegalArgumentException("Internal error: unexpected string care level value return by MSV: "+stringChecks);
413 }
414 }
415 return XMLValidator.CONTENT_ALLOW_ANY_TEXT;
416 }
417
418 @Override
419 public void validateText(String text, boolean lastTextSegment)
420 throws XMLStreamException
421 {
422 /* If we got here, then it's likely we do need to call onText2().
423 * (not guaranteed, though; in case of multiple parallel validators,
424 * only one of them may actually be interested)
425 */
426 mTextAccumulator.addText(text);
427 if (lastTextSegment) {
428 doValidateText(mTextAccumulator);
429 }
430 }
431
432 @Override
433 public void validateText(char[] cbuf, int textStart, int textEnd,
434 boolean lastTextSegment)
435 throws XMLStreamException
436 {
437 /* If we got here, then it's likely we do need to call onText().
438 * (not guaranteed, though; in case of multiple parallel validators,
439 * only one of them may actually be interested)
440 */
441 mTextAccumulator.addText(cbuf, textStart, textEnd);
442 if (lastTextSegment) {
443 doValidateText(mTextAccumulator);
444 }
445 }
446
447 @Override
448 public void validationCompleted(boolean eod)
449 throws XMLStreamException
450 {
451 /* Ok, so, we should verify that there are no undefined
452 * IDREF/IDREFS references. But only if we hit EOF, not
453 * if validation was cancelled.
454 */
455 if (eod) {
456 if (mIdDefs != null) {
457 ElementId ref = mIdDefs.getFirstUndefined();
458 if (ref != null) { // problem!
459 String msg = "Undefined ID '"+ref.getId()
460 +"': referenced from element <"
461 +ref.getElemName()+">, attribute '"
462 +ref.getAttrName()+"'";
463 reportError(msg, ref.getLocation());
464 }
465 }
466 }
467 }
468
469 /*
470 ///////////////////////////////////////////////////////////
471 // Attribute info access
472 ///////////////////////////////////////////////////////////
473 */
474
475 // // // Access to type info
476
477 @Override
478 public String getAttributeType(int index)
479 {
480 // !!! TBI
481 return null;
482 }
483
484 @Override
485 public int getIdAttrIndex()
486 {
487 // !!! TBI
488 return -1;
489 }
490
491 @Override
492 public int getNotationAttrIndex()
493 {
494 // !!! TBI
495 return -1;
496 }
497
498 /*
499 ///////////////////////////////////////////////////////////
500 // Internal methods
501 ///////////////////////////////////////////////////////////
502 */
503
504 PrefixedName getElementPName()
505 {
506 return PrefixedName.valueOf(mContext.getCurrentElementName());
507 }
508
509 PrefixedName getAttrPName()
510 {
511 return new PrefixedName(mCurrAttrPrefix, mCurrAttrLocalName);
512 }
513
514 void doValidateText(TextAccumulator textAcc)
515 throws XMLStreamException
516 {
517 if (mCurrAcceptor != null) {
518 String str = textAcc.getAndClear();
519 DatatypeRef typeRef = null;
520 if (!mCurrAcceptor.onText2(str, this, mErrorRef, typeRef)
521 || mErrorRef.str != null) {
522 reportError(mErrorRef, CDATA, _startTagAsQName());
523 }
524 }
525 }
526
527 private void reportError(StringRef errorRef, int type, QName name) throws XMLStreamException
528 {
529 String msg = errorRef.str;
530 errorRef.str = null;
531 if (msg == null || msg.isEmpty()) {
532 switch (type) {
533 case START_ELEMENT:
534 msg = "Unknown reason (at start element "+_name(name, "<", ">")+")";
535 break;
536 case END_ELEMENT:
537 msg = "Unknown reason (at end element "+_name(name, "</", ">")+")";
538 break;
539 case ATTRIBUTE:
540 msg = "Unknown reason (at attribute "+_name(name, "'", "'")+")";
541 break;
542 case CDATA:
543 default:
544 msg = "Unknown reason (at CDATA section, inside element "+_name(name, "<", ">")+")";
545 break;
546 }
547 }
548 reportError(msg);
549 }
550
551 private void reportError(String msg)
552 throws XMLStreamException
553 {
554 reportError(msg, mContext.getValidationLocation());
555 }
556
557 private void reportError(String msg, Location loc)
558 throws XMLStreamException
559 {
560 XMLValidationProblem prob = new XMLValidationProblem(loc, msg, XMLValidationProblem.SEVERITY_ERROR);
561 prob.setReporter(this);
562 mContext.reportProblem(prob);
563 }
564
565 private String _name(QName qn, String prefix, String suffix) {
566 if (qn == null) {
567 return "UNKNOWN";
568 }
569 String name = qn.getLocalPart();
570 String p = qn.getPrefix();
571 if (p != null && !p.isEmpty()) {
572 name = p + ":" + name;
573 }
574 return prefix + name + suffix;
575 }
576
577 private QName _startTagAsQName() {
578 return _qname(mStartTag.namespaceURI, mStartTag.localName, mStartTagPrefix);
579 }
580
581 private QName _qname(String ns, String local, String prefix) {
582 if (prefix == null) {
583 prefix = "";
584 }
585 if (ns == null) {
586 ns = "";
587 }
588 // should we even allow this?
589 if (local == null) {
590 local = "";
591 }
592 return new QName(ns, local, prefix);
593 }
594 }