if (namespace.equals(schema.getTargetNamespace()) )
throw new SchemaException("the 'namespace' attribute in the <import> element cannot be the same of the targetNamespace of the global schema");
//-- Schema object to hold import schema
boolean addSchema = false;
Schema importedSchema = schema.getImportedSchema(namespace, true);
//-- Have we already imported this XML Schema file?
if (state.processed(schemaLocation)) {
if (importedSchema == null)
schema.addImportedSchema(state.getSchema(schemaLocation));
return;
}
boolean alreadyLoaded = false;
if (importedSchema == null) {
if (uri instanceof SchemaLocation) {
importedSchema = ((SchemaLocation)uri).getSchema();
schema.addImportedSchema(importedSchema);
alreadyLoaded = true;
}
else {
importedSchema = new Schema();
addSchema = true;
}
}
else {
// check schema location, if different, allow merge
if (hasLocation) {
String tmpLocation = importedSchema.getSchemaLocation();
alreadyLoaded = schemaLocation.equals(tmpLocation) || importedSchema.includeProcessed(schemaLocation);
//-- keep track of the original schemaLocation as an include
if(! alreadyLoaded) {
importedSchema.addInclude(tmpLocation);
}
} else {
//-- only namespace can be used, no way to distinguish
//-- multiple imports...mark as alreadyLoaded
//-- see W3C XML Schema 1.0 Recommendation (part 1)
//-- section 4.2.3...
//-- <quote>... Given that the schemaLocation [attribute] is only
//-- a hint, it is open to applications to ignore all but the
//-- first <import> for a given namespace, regardless of the
//-- <em>actual value</em> of schemaLocation, but such a strategy
//-- risks missing useful information when new schemaLocations
//-- are offered.</quote>
alreadyLoaded = true;
}
}
state.markAsProcessed(schemaLocation, importedSchema);
if (alreadyLoaded) return;
//-- Parser Schema
Parser parser = null;
try {
parser = getSchemaContext().getParser();
}
catch(RuntimeException rte) {}
if (parser == null) {
throw new SchemaException("Error failed to create parser for import");
}
//-- Create Schema object and setup unmarshaller
SchemaUnmarshaller schemaUnmarshaller = new SchemaUnmarshaller(getSchemaContext(), state);
schemaUnmarshaller.setURIResolver(getURIResolver());
schemaUnmarshaller.setSchema(importedSchema);
Sax2ComponentReader handler = new Sax2ComponentReader(schemaUnmarshaller);
parser.setDocumentHandler(handler);
parser.setErrorHandler(handler);
try {
InputSource source = new InputSource(uri.getReader());
source.setSystemId(uri.getAbsoluteURI());
parser.parse(source);
}
catch(java.io.IOException ioe) {
throw new SchemaException("Error reading import file '"+schemaLocation+"': "+ ioe);
}
catch(org.xml.sax.SAXException sx) {
throw new SchemaException(sx);
}
//-- Add schema to list of imported schemas (if not already present)
if (addSchema)
{
importedSchema.setSchemaLocation(schemaLocation);
schema.addImportedSchema(importedSchema);
}
}