source: trunk/src/xmlpatterns/schema/qxsdvalidatinginstancereader.cpp@ 944

Last change on this file since 944 was 561, checked in by Dmitry A. Kuminov, 16 years ago

trunk: Merged in qt 4.6.1 sources.

  • Property svn:eol-style set to native
File size: 52.7 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtXmlPatterns module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "qxsdvalidatinginstancereader_p.h"
43
44#include "qabstractdatetime_p.h"
45#include "qacceltreeresourceloader_p.h"
46#include "qbase64binary_p.h"
47#include "qboolean_p.h"
48#include "qcommonnamespaces_p.h"
49#include "qderivedinteger_p.h"
50#include "qduration_p.h"
51#include "qgenericstaticcontext_p.h"
52#include "qhexbinary_p.h"
53#include "qnamespaceresolver_p.h"
54#include "qpatternplatform_p.h"
55#include "qqnamevalue_p.h"
56#include "qsourcelocationreflection_p.h"
57#include "qvaluefactory_p.h"
58#include "qxmlnamepool.h"
59#include "qxmlquery_p.h"
60#include "qxmlschema_p.h"
61#include "qxsdschemahelper_p.h"
62#include "qxsdschemamerger_p.h"
63#include "qxsdstatemachine_p.h"
64#include "qxsdstatemachinebuilder_p.h"
65#include "qxsdtypechecker_p.h"
66
67#include "qxsdschemadebugger_p.h"
68
69#include <QtCore/QFile>
70#include <QtXmlPatterns/QXmlQuery>
71#include <QtXmlPatterns/QXmlResultItems>
72
73QT_BEGIN_NAMESPACE
74
75using namespace QPatternist;
76
77namespace QPatternist
78{
79 template <>
80 template <>
81 bool XsdStateMachine<XsdTerm::Ptr>::inputEqualsTransition<QXmlName>(QXmlName name, XsdTerm::Ptr term) const
82 {
83 if (term->isElement()) {
84 return (XsdElement::Ptr(term)->name(m_namePool) == name);
85 } else if (term->isWildcard()) {
86 // wildcards using XsdWildcard::absentNamespace, so we have to fix that here
87 if (name.namespaceURI() == StandardNamespaces::empty) {
88 name.setNamespaceURI(m_namePool->allocateNamespace(XsdWildcard::absentNamespace()));
89 }
90
91 return XsdSchemaHelper::wildcardAllowsExpandedName(name, XsdWildcard::Ptr(term), m_namePool);
92 }
93
94 return false;
95 }
96}
97
98XsdValidatingInstanceReader::XsdValidatingInstanceReader(XsdValidatedXmlNodeModel *model, const QUrl &documentUri, const XsdSchemaContext::Ptr &context)
99 : XsdInstanceReader(model, context)
100 , m_model(model)
101 , m_namePool(m_context->namePool())
102 , m_xsiNilName(m_namePool->allocateQName(CommonNamespaces::XSI, QLatin1String("nil")))
103 , m_xsiTypeName(m_namePool->allocateQName(CommonNamespaces::XSI, QLatin1String("type")))
104 , m_xsiSchemaLocationName(m_namePool->allocateQName(CommonNamespaces::XSI, QLatin1String("schemaLocation")))
105 , m_xsiNoNamespaceSchemaLocationName(m_namePool->allocateQName(CommonNamespaces::XSI, QLatin1String("noNamespaceSchemaLocation")))
106 , m_documentUri(documentUri)
107{
108 m_idRefsType = m_context->schemaTypeFactory()->createSchemaType(m_namePool->allocateQName(CommonNamespaces::WXS, QLatin1String("IDREFS")));
109}
110
111void XsdValidatingInstanceReader::addSchema(const XsdSchema::Ptr &schema, const QUrl &locationUrl)
112{
113 if (!m_mergedSchemas.contains(locationUrl)) {
114 m_mergedSchemas.insert(locationUrl, QStringList() << schema->targetNamespace());
115 } else {
116 QStringList &targetNamespaces = m_mergedSchemas[locationUrl];
117 if (targetNamespaces.contains(schema->targetNamespace()))
118 return;
119
120 targetNamespaces.append(schema->targetNamespace());
121 }
122
123 const XsdSchemaMerger merger(m_schema, schema);
124 m_schema = merger.mergedSchema();
125/*
126 XsdSchemaDebugger dbg(m_namePool);
127 dbg.dumpSchema(m_schema);
128*/
129}
130
131bool XsdValidatingInstanceReader::read()
132{
133 while (!atEnd()) {
134 readNext();
135
136 if (isEndElement())
137 return true;
138
139 if (isStartElement()) {
140 const QXmlName elementName = name();
141 const QXmlItem currentItem = item();
142 bool hasStateMachine = false;
143 XsdElement::Ptr processedElement;
144
145 if (!validate(hasStateMachine, processedElement))
146 return false;
147
148 read();
149
150 if (processedElement) { // for wildcard with 'skip' we have no element
151 m_model->setAssignedElement(currentItem.toNodeModelIndex(), processedElement);
152
153 // check identity constraints after all child nodes have been
154 // validated, so that we know there assigned types
155 validateIdentityConstraint(processedElement, currentItem);
156 }
157
158 if (!m_stateMachines.isEmpty() && hasStateMachine) {
159 if (!m_stateMachines.top().inEndState()) {
160 error(QtXmlPatterns::tr("Element %1 is missing child element.").arg(formatKeyword(m_namePool->displayName(elementName))));
161 return false;
162 }
163 m_stateMachines.pop();
164 }
165 }
166 }
167
168 // final validations
169
170 // check IDREF occurrences
171 const QStringList ids = m_model->idIdRefBindingIds();
172 QSetIterator<QString> it(m_idRefs);
173 while (it.hasNext()) {
174 const QString id = it.next();
175 if (!ids.contains(id)) {
176 error(QtXmlPatterns::tr("There is one IDREF value with no corresponding ID: %1.").arg(formatKeyword(id)));
177 return false;
178 }
179 }
180
181 return true;
182}
183
184void XsdValidatingInstanceReader::error(const QString &msg) const
185{
186 m_context.data()->error(msg, XsdSchemaContext::XSDError, sourceLocation());
187}
188
189bool XsdValidatingInstanceReader::loadSchema(const QString &targetNamespace, const QUrl &location)
190{
191 const AutoPtr<QNetworkReply> reply(AccelTreeResourceLoader::load(location, m_context->networkAccessManager(),
192 m_context, AccelTreeResourceLoader::ContinueOnError));
193 if (!reply)
194 return true;
195
196 // we have to create a separated schema context here, that however shares the type factory
197 XsdSchemaContext::Ptr context(new XsdSchemaContext(m_namePool));
198 context->m_schemaTypeFactory = m_context->m_schemaTypeFactory;
199
200 QXmlSchemaPrivate schema(context);
201 schema.load(reply.data(), location, targetNamespace);
202 if (!schema.isValid()) {
203 error(QtXmlPatterns::tr("Loaded schema file is invalid."));
204 return false;
205 }
206
207 addSchema(schema.m_schemaParserContext->schema(), location);
208
209 return true;
210}
211
212bool XsdValidatingInstanceReader::validate(bool &hasStateMachine, XsdElement::Ptr &processedElement)
213{
214 // first check if a custom schema is defined
215 if (hasAttribute(m_xsiSchemaLocationName)) {
216 const QString schemaLocation = attribute(m_xsiSchemaLocationName);
217 const QStringList parts = schemaLocation.split(QLatin1Char(' '), QString::SkipEmptyParts);
218 if ((parts.count()%2) == 1) {
219 error(QtXmlPatterns::tr("%1 contains invalid data.").arg(formatKeyword(m_namePool, m_xsiSchemaLocationName)));
220 return false;
221 }
222
223 for (int i = 0; i < parts.count(); i += 2) {
224 const QString identifier = QString::fromLatin1("%1 %2").arg(parts.at(i)).arg(parts.at(i + 1));
225 if (m_processedSchemaLocations.contains(identifier))
226 continue;
227 else
228 m_processedSchemaLocations.insert(identifier);
229
230 // check constraint 4) from http://www.w3.org/TR/xmlschema-1/#schema-loc (only valid for XML Schema 1.0?)
231 if (m_processedNamespaces.contains(parts.at(i))) {
232 error(QtXmlPatterns::tr("xsi:schemaLocation namespace %1 has already appeared earlier in the instance document.").arg(formatKeyword(parts.at(i))));
233 return false;
234 }
235
236 QUrl url(parts.at(i + 1));
237 if (url.isRelative()) {
238 Q_ASSERT(m_documentUri.isValid());
239
240 url = m_documentUri.resolved(url);
241 }
242
243 loadSchema(parts.at(i), url);
244 }
245 }
246
247 if (hasAttribute(m_xsiNoNamespaceSchemaLocationName)) {
248 const QString schemaLocation = attribute(m_xsiNoNamespaceSchemaLocationName);
249
250 if (!m_processedSchemaLocations.contains(schemaLocation)) {
251 m_processedSchemaLocations.insert(schemaLocation);
252
253 if (m_processedNamespaces.contains(QString())) {
254 error(QtXmlPatterns::tr("xsi:noNamespaceSchemaLocation cannot appear after the first no-namespace element or attribute."));
255 return false;
256 }
257
258 QUrl url(schemaLocation);
259 if (url.isRelative()) {
260 Q_ASSERT(m_documentUri.isValid());
261
262 url = m_documentUri.resolved(url);
263 }
264
265 loadSchema(QString(), url);
266 }
267 }
268
269 m_processedNamespaces.insert(m_namePool->stringForNamespace(name().namespaceURI()));
270
271 if (!m_schema) {
272 error(QtXmlPatterns::tr("No schema defined for validation."));
273 return false;
274 }
275
276 // check if we are 'inside' a type definition
277 if (m_stateMachines.isEmpty()) {
278 // find out the type of the top-level element
279 XsdElement::Ptr element = elementByName(name());
280 if (!element) {
281 if (!hasAttribute(m_xsiTypeName)) {
282 error(QtXmlPatterns::tr("No definition for element %1 available.").arg(formatKeyword(m_namePool, name())));
283 return false;
284 }
285
286 // This instance document has an element with no definition in the schema
287 // but an explicitly given type, that is fine according to the spec.
288 // We will create an element definition manually here and continue the
289 // normal validation process
290 element = XsdElement::Ptr(new XsdElement());
291 element->setName(name());
292 element->setIsAbstract(false);
293 element->setIsNillable(hasAttribute(m_xsiNilName));
294
295 const QString type = qNameAttribute(m_xsiTypeName);
296 const QXmlName typeName = convertToQName(type);
297
298 const SchemaType::Ptr elementType = typeByName(typeName);
299 if (!elementType) {
300 error(QtXmlPatterns::tr("Specified type %1 is not known to the schema.").arg(formatType(m_namePool, typeName)));
301 return false;
302 }
303 element->setType(elementType);
304 }
305
306 // rememeber the element we process
307 processedElement = element;
308
309 if (!validateElement(element, hasStateMachine)) {
310 return false;
311 }
312
313 } else {
314 if (!m_stateMachines.top().proceed<QXmlName>(name())) {
315 error(QtXmlPatterns::tr("Element %1 is not defined in this scope.").arg(formatKeyword(m_namePool, name())));
316 return false;
317 }
318
319 const XsdTerm::Ptr term = m_stateMachines.top().lastTransition();
320 if (term->isElement()) {
321 const XsdElement::Ptr element(term);
322
323 // rememeber the element we process
324 processedElement = element;
325
326 if (!validateElement(element, hasStateMachine))
327 return false;
328
329 } else {
330 const XsdWildcard::Ptr wildcard(term);
331 if (wildcard->processContents() != XsdWildcard::Skip) {
332 XsdElement::Ptr elementDeclaration = elementByName(name());
333 if (!elementDeclaration) {
334 if (hasAttribute(m_xsiTypeName)) {
335 // This instance document has an element with no definition in the schema
336 // but an explicitly given type, that is fine according to the spec.
337 // We will create an element definition manually here and continue the
338 // normal validation process
339 elementDeclaration = XsdElement::Ptr(new XsdElement());
340 elementDeclaration->setName(name());
341 elementDeclaration->setIsAbstract(false);
342 elementDeclaration->setIsNillable(hasAttribute(m_xsiNilName));
343
344 const QString type = qNameAttribute(m_xsiTypeName);
345 const QXmlName typeName = convertToQName(type);
346
347 const SchemaType::Ptr elementType = typeByName(typeName);
348 if (!elementType) {
349 error(QtXmlPatterns::tr("Specified type %1 is not known to the schema.").arg(formatType(m_namePool, typeName)));
350 return false;
351 }
352 elementDeclaration->setType(elementType);
353 }
354 }
355
356 if (!elementDeclaration) {
357 if (wildcard->processContents() == XsdWildcard::Strict) {
358 error(QtXmlPatterns::tr("Declaration for element %1 does not exist.").arg(formatKeyword(m_namePool->displayName(name()))));
359 return false;
360 } else {
361 // in this case we put a state machine for the xs:anyType on the statemachine stack,
362 // so we accept every content of this element
363
364 createAndPushStateMachine(anyType()->contentType()->particle());
365 hasStateMachine = true;
366 }
367 } else {
368 if (!validateElement(elementDeclaration, hasStateMachine)) {
369 if (wildcard->processContents() == XsdWildcard::Strict) {
370 error(QtXmlPatterns::tr("Element %1 contains invalid content.").arg(formatKeyword(m_namePool->displayName(name()))));
371 return false;