Index: src/test/java/org/exolab/castor/xml/XMLContextTest.java =================================================================== --- src/test/java/org/exolab/castor/xml/XMLContextTest.java (revision 7270) +++ src/test/java/org/exolab/castor/xml/XMLContextTest.java (working copy) @@ -3,6 +3,7 @@ import junit.framework.TestCase; import org.castor.test.entity.Entity; +import org.castor.xml.InternalContext; import org.exolab.castor.mapping.Mapping; import org.xml.sax.InputSource; @@ -11,7 +12,7 @@ private static final String MAPPING_FILE = "org/castor/test/entity/mapping.xml"; /** - * Test {@link XMLContext} by providing a generated package. + * Test {@link InternalContext} by providing a generated package. * @throws Exception */ public void testXMLContextByPackage() throws Exception { @@ -36,15 +37,13 @@ */ public void testXMLContextByMapping() throws Exception { - - Mapping mapping = XMLContext.createMapping(); + XMLContext xmlContext = new XMLContext(); + Mapping mapping = xmlContext.createMapping(); mapping.loadMapping(new InputSource(getResource(MAPPING_FILE))); - XMLContext context = new XMLContext(); - context.addMapping(mapping); - assertNotNull (context); + xmlContext.addMapping(mapping); - Unmarshaller unmarshaller = context.createUnmarshaller(); + Unmarshaller unmarshaller = xmlContext.createUnmarshaller(); assertNotNull(unmarshaller); unmarshaller.setClass(Entity.class); Index: src/test/java/org/exolab/castor/xml/TestUnmarshaller.java =================================================================== --- src/test/java/org/exolab/castor/xml/TestUnmarshaller.java (revision 7270) +++ src/test/java/org/exolab/castor/xml/TestUnmarshaller.java (working copy) @@ -17,7 +17,7 @@ import junit.framework.TestCase; -import org.exolab.castor.util.Configuration.Property; +import org.castor.xml.XMLConfiguration; /** * Test case for testing various pieces of functionality of {@link Unmarshaller}. @@ -29,18 +29,19 @@ */ public void testSetProperty() { - Unmarshaller unmarshaller = new Unmarshaller(); + XMLContext xmlContext = new XMLContext(); + Unmarshaller unmarshaller = xmlContext.createUnmarshaller(); assertNotNull(unmarshaller); String lenientSequenceValidation = - unmarshaller.getProperty(Property.LenientSequenceOrder); + unmarshaller.getProperty(XMLConfiguration.LENIENT_SEQUENCE_ORDER); assertNotNull(lenientSequenceValidation); assertEquals("false", lenientSequenceValidation); - unmarshaller.setProperty(Property.LenientSequenceOrder, "true"); + unmarshaller.setProperty(XMLConfiguration.LENIENT_SEQUENCE_ORDER, "true"); lenientSequenceValidation = - unmarshaller.getProperty(Property.LenientSequenceOrder); + unmarshaller.getProperty(XMLConfiguration.LENIENT_SEQUENCE_ORDER); assertNotNull(lenientSequenceValidation); assertEquals("true", lenientSequenceValidation); } Index: src/test/java/org/castor/xml/XMLConfigurationTest.java =================================================================== --- src/test/java/org/castor/xml/XMLConfigurationTest.java (revision 0) +++ src/test/java/org/castor/xml/XMLConfigurationTest.java (revision 0) @@ -0,0 +1,104 @@ +/* + * Copyright 2007 Joachim Grueneis + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.castor.xml; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.castor.core.util.Configuration; + +import junit.framework.Assert; +import junit.framework.TestCase; + +/** + * The XMLConfiguration test has one goal - check if the proper defaults + * are in place. + * + * @author Joachim Grueneis, jgrueneis_at_gmail_dot_com + * @version $Id$ + */ +public class XMLConfigurationTest extends TestCase { + private static final Log LOG = LogFactory.getLog(XMLConfigurationTest.class); + + private Configuration _configuration; + + public XMLConfigurationTest(final String name) { + super(name); + } + + public void setUp() { + _configuration = XMLConfiguration.newInstance(); + Assert.assertNotNull( + "Configuration must exist after call to newInstance()", _configuration); + Assert.assertNotNull( + "Application class loader must not be null", + _configuration.getApplicationClassLoader()); + Assert.assertNotNull( + "Domain class loader must not be null", + _configuration.getDomainClassLoader()); + } + + public void testNewInstanceClassLoaderClassLoader() { + Configuration c = XMLConfiguration.newInstance(null, null); + Assert.assertNotNull( + "Configuration must exist after call to newInstance()", c); +// Assert.assertNotNull( +// "Application class loader must not be null", +// c.getApplicationClassLoader()); +// Assert.assertNotNull( +// "Domain class loader must not be null", +// c.getDomainClassLoader()); + } + + public void testGetBooleanString() { + Boolean notExistingProperty = _configuration.getBoolean("Something which doesn't exist"); + Assert.assertNull("A not existing property needs to return null", notExistingProperty); + } + + public void testGetBooleanStringBoolean() { + boolean notExistingPropertyWithDefault = + _configuration.getBoolean("Something which doesn't exist", true); + Assert.assertTrue( + "A not existing property with default true", + notExistingPropertyWithDefault); + } + + /** + * Tests wether the expected defaults are present or not. + */ + public void testDefaults() { + Boolean loadPackageMapping = + _configuration.getBoolean(XMLConfiguration.LOAD_PACKAGE_MAPPING); + Assert.assertEquals( + "load package mapping is expected to be set to: true", + Boolean.TRUE, loadPackageMapping); + + String serialzierFactory = _configuration.getString(XMLConfiguration.SERIALIZER_FACTORY); + Assert.assertEquals( + "check serializer factory default", + "org.exolab.castor.xml.XercesXMLSerializerFactory", + serialzierFactory); + + Boolean strictElements = _configuration.getBoolean(XMLConfiguration.STRICT_ELEMENTS); + Assert.assertEquals("strict elements default", Boolean.FALSE, strictElements); + + Boolean marshallingValidation = + _configuration.getBoolean(XMLConfiguration.MARSHALLING_VALIDATION); + Assert.assertEquals("marshallingValidation", Boolean.TRUE, marshallingValidation); + + Boolean useIntrospection = _configuration.getBoolean(XMLConfiguration.USE_INTROSPECTION); + Assert.assertEquals("useIntrospection", Boolean.TRUE, useIntrospection); + } +} Index: src/bugs/xml/c1586/TextContentTest.java =================================================================== --- src/bugs/xml/c1586/TextContentTest.java (revision 7270) +++ src/bugs/xml/c1586/TextContentTest.java (working copy) @@ -5,6 +5,7 @@ import org.exolab.castor.mapping.Mapping; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.Unmarshaller; +import org.exolab.castor.xml.XMLContext; import org.xml.sax.InputSource; @@ -16,6 +17,7 @@ public class TextContentTest extends TestCase { private static final String MAPPING_FILE = "mapping.xml"; + private XMLContext xmlContext; private Mapping mapping; private Marshaller marshaller; private StringWriter writer; @@ -26,6 +28,7 @@ */ protected void setUp() throws Exception { super.setUp(); + this.xmlContext = new XMLContext(); // das Test Objekt vorbereiten this.writer = new StringWriter(); } @@ -36,7 +39,7 @@ protected void tearDown() throws Exception { super.tearDown(); this.writer = null; - + this.xmlContext = null; } /** @@ -48,20 +51,25 @@ mapping.loadMapping(new InputSource(getClass().getResourceAsStream(MAPPING_FILE))); // den Marshaller erzeugen - marshaller = new Marshaller(writer); + marshaller = xmlContext.createMarshaller(); + marshaller.setWriter(writer); +// marshaller = new Marshaller(writer); marshaller.setMapping(mapping); marshaller.setEncoding("UTF-8"); marshaller.setValidation(true); // den Unmarshaller erzeugen - unmarshaller = new Unmarshaller(); + unmarshaller = xmlContext.createUnmarshaller(); +// unmarshaller = new Unmarshaller(); unmarshaller.setClassLoader(getClass().getClassLoader()); unmarshaller.setValidation(false); unmarshaller.setMapping(mapping); unmarshaller.setWhitespacePreserve(true); // den Marshaller erzeugen - marshaller = new Marshaller(writer); + marshaller = xmlContext.createMarshaller(); + marshaller.setWriter(writer); +// marshaller = new Marshaller(writer); marshaller.setMapping(mapping); marshaller.setEncoding("UTF-8"); marshaller.setValidation(true); @@ -76,13 +84,16 @@ mapping.loadMapping(getClass().getResource(MAPPING_FILE)); // den Marshaller erzeugen - marshaller = new Marshaller(writer); + marshaller = xmlContext.createMarshaller(); + marshaller.setWriter(writer); +// marshaller = new Marshaller(writer); marshaller.setMapping(mapping); marshaller.setEncoding("UTF-8"); marshaller.setValidation(true); // den Unmarshaller erzeugen - unmarshaller = new Unmarshaller(); + unmarshaller = xmlContext.createUnmarshaller(); +// unmarshaller = new Unmarshaller(); unmarshaller.setClassLoader(getClass().getClassLoader()); unmarshaller.setValidation(false); unmarshaller.setMapping(mapping); Index: src/bugs/xml/c1342/Test1342.java =================================================================== --- src/bugs/xml/c1342/Test1342.java (revision 7270) +++ src/bugs/xml/c1342/Test1342.java (working copy) @@ -4,14 +4,13 @@ import java.io.StringWriter; import junit.framework.TestCase; - import net.sf.cglib.proxy.Factory; +import org.castor.xml.XMLConfiguration; import org.exolab.castor.mapping.Mapping; -import org.exolab.castor.util.Configuration; -import org.exolab.castor.util.LocalConfiguration; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.Unmarshaller; +import org.exolab.castor.xml.XMLContext; public final class Test1342 extends TestCase { private static final String MAPPING_FILE = "mapping.xml"; @@ -145,17 +144,29 @@ * @throws Exception For any exception thrown. */ public void testMarshalSimpleBeanProxy() throws Exception { - Configuration config = LocalConfiguration.getInstance(); - config.getProperties().setProperty( - Configuration.Property.ProxyInterfaces, "net.sf.cglib.proxy.Factory"); + XMLContext xmlContext = new XMLContext(); + xmlContext.setProperty(XMLConfiguration.PROXY_INTERFACES, "net.sf.cglib.proxy.Factory"); - Mapping mapping = new Mapping(); + Mapping mapping = xmlContext.createMapping(); mapping.loadMapping(getClass().getResource(MAPPING_FILE).toExternalForm()); StringWriter out = new StringWriter(); - Marshaller marshaller = new Marshaller(out); + Marshaller marshaller = xmlContext.createMarshaller(); + marshaller.setWriter(out); marshaller.setMapping(mapping); +// Joachim 2007-09-04 before XMLContext was introduced it looked like: +// Configuration config = LocalConfiguration.getInstance(); +// config.getProperties().setProperty( +// XMLConfiguration.PROXY_INTERFACES, "net.sf.cglib.proxy.Factory"); +// +// Mapping mapping = new Mapping(); +// mapping.loadMapping(getClass().getResource(MAPPING_FILE).toExternalForm()); +// +// StringWriter out = new StringWriter(); +// Marshaller marshaller = new Marshaller(out); +// marshaller.setMapping(mapping); + Bean bean = new Bean(new Integer(999), "element of 999", null); Bean proxy = (Bean) Proxy.newInstance(bean); @@ -187,17 +198,29 @@ * @throws Exception For any exception thrown. */ public void testMarshalReferingBeanProxy() throws Exception { - Configuration config = LocalConfiguration.getInstance(); - config.getProperties().setProperty( - Configuration.Property.ProxyInterfaces, "net.sf.cglib.proxy.Factory"); + XMLContext xmlContext = new XMLContext(); + xmlContext.setProperty(XMLConfiguration.PROXY_INTERFACES, "net.sf.cglib.proxy.Factory"); - Mapping mapping = new Mapping(); + Mapping mapping = xmlContext.createMapping(); mapping.loadMapping(getClass().getResource(MAPPING_FILE).toExternalForm()); StringWriter out = new StringWriter(); - Marshaller marshaller = new Marshaller(out); + Marshaller marshaller = xmlContext.createMarshaller(); + marshaller.setWriter(out); marshaller.setMapping(mapping); +// Joachim 2007-09-04 before XMLContext was introduced it looked like: +// Configuration config = LocalConfiguration.getInstance(); +// config.getProperties().setProperty( +// XMLConfiguration.PROXY_INTERFACES, "net.sf.cglib.proxy.Factory"); +// +// Mapping mapping = new Mapping(); +// mapping.loadMapping(getClass().getResource(MAPPING_FILE).toExternalForm()); +// +// StringWriter out = new StringWriter(); +// Marshaller marshaller = new Marshaller(out); +// marshaller.setMapping(mapping); + Bean refered = new Bean(new Integer(999), "element of 999", null); Bean referedProxy = (Bean) Proxy.newInstance(refered); Index: src/main/java/org/exolab/castor/dsml/Importer.java =================================================================== --- src/main/java/org/exolab/castor/dsml/Importer.java (revision 7270) +++ src/main/java/org/exolab/castor/dsml/Importer.java (working copy) @@ -56,6 +56,7 @@ import org.xml.sax.Parser; import org.xml.sax.InputSource; import org.castor.util.Messages; +import org.castor.xml.InternalContext; import org.exolab.castor.util.Configuration; import org.exolab.castor.util.LocalConfiguration; @@ -68,9 +69,9 @@ */ public abstract class Importer { + private InternalContext _xmlContext = new InternalContext(); - private Configuration _config = LocalConfiguration.getInstance(); - +// private Configuration _config = LocalConfiguration.getInstance(); private ImportDescriptor _importDesc; @@ -110,14 +111,14 @@ public void importDocument( InputStream stream ) throws ImportExportException { - importDocument( _config.getParser(), new InputSource( stream ) ); + importDocument( _xmlContext.getParser(), new InputSource( stream ) ); } public void importDocument( Reader reader ) throws ImportExportException { - importDocument( _config.getParser(), new InputSource( reader ) ); + importDocument( _xmlContext.getParser(), new InputSource( reader ) ); } @@ -143,14 +144,14 @@ public void readImportDescriptor( InputStream input ) throws IOException, SAXException { - readImportDescriptor( _config.getParser(), new InputSource( input ) ); + readImportDescriptor( _xmlContext.getParser(), new InputSource( input ) ); } public void readImportDescriptor( Reader input ) throws IOException, SAXException { - readImportDescriptor( _config.getParser(), new InputSource( input ) ); + readImportDescriptor( _xmlContext.getParser(), new InputSource( input ) ); } Index: src/main/java/org/exolab/castor/dsml/Exporter.java =================================================================== --- src/main/java/org/exolab/castor/dsml/Exporter.java (revision 7270) +++ src/main/java/org/exolab/castor/dsml/Exporter.java (working copy) @@ -56,6 +56,7 @@ import org.xml.sax.SAXException; import org.xml.sax.Parser; import org.xml.sax.InputSource; +import org.castor.xml.InternalContext; import org.exolab.castor.util.Configuration; import org.exolab.castor.util.LocalConfiguration; import org.exolab.castor.dsml.SearchDescriptor; @@ -71,8 +72,9 @@ public abstract class Exporter { + private InternalContext _xmlContext = new InternalContext(); - private Configuration _config = LocalConfiguration.getInstance(); +// private Configuration _config = LocalConfiguration.getInstance(); private SearchDescriptor _searchDesc; @@ -85,7 +87,7 @@ throws ImportExportException { try { - export( _config.getSerializer( output ), serverSchema, importPolicy ); + export( _xmlContext.getSerializer( output ), serverSchema, importPolicy ); } catch ( IOException except ) { throw new ImportExportException( except ); } @@ -96,7 +98,7 @@ throws ImportExportException { try { - export( _config.getSerializer( output ), serverSchema, importPolicy ); + export( _xmlContext.getSerializer( output ), serverSchema, importPolicy ); } catch ( IOException except ) { throw new ImportExportException( except ); } @@ -135,14 +137,14 @@ public void readSearchDescriptor( InputStream input ) throws IOException, SAXException { - readSearchDescriptor( _config.getParser(), new InputSource( input ) ); + readSearchDescriptor( _xmlContext.getParser(), new InputSource( input ) ); } public void readSearchDescriptor( Reader input ) throws IOException, SAXException { - readSearchDescriptor( _config.getParser(), new InputSource( input ) ); + readSearchDescriptor( _xmlContext.getParser(), new InputSource( input ) ); } Index: src/main/java/org/exolab/castor/tools/MappingTool.java =================================================================== --- src/main/java/org/exolab/castor/tools/MappingTool.java (revision 7270) +++ src/main/java/org/exolab/castor/tools/MappingTool.java (working copy) @@ -52,9 +52,8 @@ import java.util.Hashtable; import java.util.Properties; -import org.castor.mapping.BindingType; -import org.castor.xml.JavaNaming; -import org.castor.xml.JavaNamingImpl; +import org.castor.xml.BackwardCompatibilityContext; +import org.castor.xml.InternalContext; import org.exolab.castor.mapping.FieldDescriptor; import org.exolab.castor.mapping.MappingException; import org.exolab.castor.mapping.loader.CollectionHandlers; @@ -69,11 +68,9 @@ import org.exolab.castor.mapping.xml.types.FieldMappingCollectionType; import org.exolab.castor.util.CommandLineOptions; import org.exolab.castor.util.dialog.ConsoleDialog; -import org.exolab.castor.xml.ClassDescriptorResolverFactory; -import org.exolab.castor.xml.Introspector; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.XMLClassDescriptor; -import org.exolab.castor.xml.XMLClassDescriptorResolver; +import org.exolab.castor.xml.XMLContext; import org.exolab.castor.xml.XMLFieldDescriptor; /** @@ -89,19 +86,13 @@ private static final String UNDERSCORE = "_"; /** Hashtable of already generated mappings. */ - private final Hashtable _mappings; + private Hashtable _mappings; - /** ClassDescriptorResolver for loading compiled descriptors. */ - private final XMLClassDescriptorResolver _resolver; - - /** Introspector to use if _forceIntrospection is enabled. */ - private Introspector _introspector = null; - /** * The internal MappingLoader to use for checking whether or not we can find * the proper accessor methods. */ - private final MappingToolMappingLoader _mappingLoader; + private MappingToolMappingLoader _mappingLoader; /** * Boolean to indicate that we should always perform introspection for each @@ -110,24 +101,15 @@ private boolean _forceIntrospection = false; /** - * The {@link JavaNaming} implementation to use. - * - * @since 1.1.3 + * The XMLContext (mother of all dwelling). */ - private JavaNaming _javaNaming; + private InternalContext _internalContext; /** * Constructor, builds up the relations. - * - * @param javaNaming - * a JavaNaming methods needs to be specified */ - public MappingTool(final JavaNaming javaNaming) { - _mappings = new Hashtable(); - _resolver = (XMLClassDescriptorResolver) ClassDescriptorResolverFactory - .createClassDescriptorResolver(BindingType.XML); - _javaNaming = javaNaming; - _mappingLoader = new MappingToolMappingLoader(_javaNaming); + public MappingTool() { + super(); } // --MappingTool /** @@ -179,7 +161,8 @@ MappingTool tool; try { - tool = new MappingTool(new JavaNamingImpl()); + XMLContext xmlContext = new XMLContext(); + tool = xmlContext.createMappingTool(); tool.addClass(classname); Writer writer = null; @@ -301,11 +284,11 @@ boolean introspected = false; try { if (_forceIntrospection) { - xmlClass = _introspector.generateClassDescriptor(cls); + xmlClass = _internalContext.getIntrospector().generateClassDescriptor(cls); introspected = true; } else { - xmlClass = (XMLClassDescriptor) _resolver.resolve(cls); - introspected = _introspector.introspected(xmlClass); + xmlClass = (XMLClassDescriptor) _internalContext.getXMLClassDescriptorResolver().resolve(cls); + introspected = _internalContext.getIntrospector().introspected(xmlClass); } } catch (Exception except) { throw new MappingException(except); @@ -454,11 +437,6 @@ */ public void setForceIntrospection(final boolean force) { _forceIntrospection = force; - if (force) { - if (_introspector == null) { - _introspector = new Introspector(); - } - } } // -- setForceInstrospection /** @@ -488,5 +466,14 @@ throw new MappingException(except); } } // -- write -} // -- MappingTool + /** + * To set the XMLContext to be used. + * @param internalContext the XMLContext to be used + */ + public void setInternalContext(final InternalContext internalContext) { + _internalContext = internalContext; + _mappings = new Hashtable(); + _mappingLoader = new MappingToolMappingLoader(_internalContext.getJavaNaming()); + } +} // -- MappingTool Index: src/main/java/org/exolab/castor/xml/XMLMappingLoader.java =================================================================== --- src/main/java/org/exolab/castor/xml/XMLMappingLoader.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/XMLMappingLoader.java (working copy) @@ -49,18 +49,16 @@ */ package org.exolab.castor.xml; + import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.Properties; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.castor.mapping.BindingType; -import org.castor.util.Messages; import org.exolab.castor.mapping.ClassDescriptor; import org.exolab.castor.mapping.CollectionHandler; import org.exolab.castor.mapping.FieldDescriptor; @@ -76,21 +74,17 @@ import org.exolab.castor.mapping.loader.Types; import org.exolab.castor.mapping.xml.BindXml; import org.exolab.castor.mapping.xml.ClassMapping; -import org.exolab.castor.mapping.xml.FieldHandlerDef; import org.exolab.castor.mapping.xml.FieldMapping; import org.exolab.castor.mapping.xml.MapTo; import org.exolab.castor.mapping.xml.MappingRoot; -import org.exolab.castor.mapping.xml.Param; import org.exolab.castor.mapping.xml.Property; import org.exolab.castor.mapping.xml.types.BindXmlAutoNamingType; import org.exolab.castor.mapping.xml.types.FieldMappingCollectionType; -import org.exolab.castor.util.LocalConfiguration; import org.exolab.castor.xml.handlers.ContainerFieldHandler; import org.exolab.castor.xml.handlers.ToStringFieldHandler; import org.exolab.castor.xml.util.ContainerElement; import org.exolab.castor.xml.util.XMLClassDescriptorAdapter; import org.exolab.castor.xml.util.XMLClassDescriptorImpl; -import org.exolab.castor.xml.util.XMLClassDescriptorResolverImpl; import org.exolab.castor.xml.util.XMLContainerElementFieldDescriptor; import org.exolab.castor.xml.util.XMLFieldDescriptorImpl; import org.exolab.castor.xml.validators.IdRefValidator; @@ -105,6 +99,8 @@ * @version $Revision$ $Date: 2006-02-23 01:37:50 -0700 (Thu, 23 Feb 2006) $ */ public final class XMLMappingLoader extends AbstractMappingLoader { + /** Logger to be used. */ + private static final Log LOG = LogFactory.getLog(XMLMappingLoader.class); //----------------------------------------------------------------------------------- /** The default xml prefix used on certain attributes such as xml:lang, xml:base, @@ -118,7 +114,7 @@ private static final String NCNAME = "NCName"; /** The string argument for the valueOf method, used for introspection. */ - private static final Class[] STRING_ARG = { String.class }; + private static final Class[] STRING_ARG = {String.class}; /** Factory method name for type-safe enumerations. This is primarily for allowing * users to map classes that were created by Castor's SourceGenerator. */ @@ -126,26 +122,16 @@ //----------------------------------------------------------------------------------- - /** A reference to the internal ClassDescriptorResolver. */ - private XMLClassDescriptorResolverImpl _cdResolver; - - /** The default NodeType for primitives. */ - private NodeType _primitiveNodeType = null; - - /** Naming conventions. */ - private XMLNaming _naming = null; - //----------------------------------------------------------------------------------- /** - * Creates a new XMLMappingLoader + * Creates a new XMLMappingLoader. + * Joachim 2007-08-19: called via ClassLoader from XMLMappingLoaderFactory.getMappingLoader() + * must not be modified!!! + * @param loader the class loader to use */ - public XMLMappingLoader(ClassLoader loader) { + public XMLMappingLoader(final ClassLoader loader) { super(loader); - - LocalConfiguration config = LocalConfiguration.getInstance(); - _primitiveNodeType = config.getPrimitiveNodeType(); - _naming = config.getXMLNaming(); } //----------------------------------------------------------------------------------- @@ -163,208 +149,241 @@ public void loadMapping(final MappingRoot mapping, final Object param) throws MappingException { if (loadMapping()) { - createFieldHandlers(mapping); - createClassDescriptors(mapping); + createFieldHandlers(mapping); + createClassDescriptors(mapping); } } //----------------------------------------------------------------------------------- - - - protected final ClassDescriptor createClassDescriptor(final ClassMapping clsMap) + /** + * To create the class descriptor for the given class mapping. + * Throws IllegalStateException if the class has no valid internal context. + * @param clsMap the class mapping information to process + * @return the {@link ClassDescriptor} created for the class mapping + * @throws MappingException ... + */ + protected ClassDescriptor createClassDescriptor(final ClassMapping clsMap) throws MappingException { - if (clsMap.getAutoComplete()) { - if ((clsMap.getMapTo() == null) && - ((clsMap.getClassChoice() == null) || - (clsMap.getClassChoice().getFieldMappingCount() == 0)) && - (clsMap.getIdentityCount() == 0)) - { - // If we make it here we simply try to load a compiled mapping - if (_cdResolver == null) { createResolver(); } - try { - ClassDescriptor clsDesc = _cdResolver.resolve(clsMap.getName()); - if (clsDesc != null) { return clsDesc; } - } catch(ResolverException rx) { - - } - } + // execution makes no sense without a context or without a resolver... + if ((getInternalContext() == null) + || (getInternalContext().getXMLClassDescriptorResolver() == null)) { + String message = "Internal context or class descriptor resolver within are not valid"; + LOG.warn(message); + throw new IllegalStateException(message); } - // Create the class descriptor. XMLClassDescriptorAdapter xmlClassDesc = new XMLClassDescriptorAdapter(); - - // Obtain the Java class. - Class javaClass = resolveType(clsMap.getName()); - if (clsMap.getVerifyConstructable()) { - if (!Types.isConstructable(javaClass, true)) { - throw new MappingException( - "mapping.classNotConstructable", javaClass.getName()); - } - } - xmlClassDesc.setJavaClass(javaClass); - // Obtain XML name. - String xmlName; - MapTo mapTo = clsMap.getMapTo(); - if ((mapTo != null) && (mapTo.getXml() != null)) { - xmlName = mapTo.getXml(); - } else { - String clsName = javaClass.getName(); - int idx = clsName.lastIndexOf('.'); - if (idx >= 0) { clsName = clsName.substring(idx + 1); } - xmlName = _naming.toXMLName(clsName); - } - xmlClassDesc.setXMLName(xmlName); + // Introspection and package level stuff needs to be disabled !! + getInternalContext().getXMLClassDescriptorResolver().setUseIntrospection(false); + getInternalContext().getXMLClassDescriptorResolver().setLoadPackageMappings(false); - // If this class extends another class, we need to obtain the extended - // class and make sure this class indeed extends it. - ClassDescriptor extDesc = getExtended(clsMap, javaClass); - xmlClassDesc.setExtends((XMLClassDescriptor) extDesc); - - // Create all field descriptors. - AbstractFieldDescriptor[] allFields = createFieldDescriptors(clsMap, javaClass); - - // Make sure there are no two fields with the same name. - checkFieldNameDuplicates(allFields, javaClass); - - // Identify identity and normal fields. Note that order must be preserved. - List fieldList = new ArrayList(allFields.length); - List idList = new ArrayList(); - if (extDesc == null) { - // Sort fields into 2 lists based on identity definition of field. - for (int i = 0; i < allFields.length; i++) { - if (!allFields[i].isIdentity()) { - fieldList.add(allFields[i]); - } else { - idList.add(allFields[i]); + try { + if (clsMap.getAutoComplete()) { + if ((clsMap.getMapTo() == null) + && ((clsMap.getClassChoice() == null) + || (clsMap.getClassChoice().getFieldMappingCount() == 0)) + && (clsMap.getIdentityCount() == 0)) { + // If we make it here we simply try to load a compiled mapping + try { + ClassDescriptor clsDesc = + getInternalContext() + .getXMLClassDescriptorResolver().resolve(clsMap.getName()); + if (clsDesc != null) { return clsDesc; } + } catch (ResolverException e) { + if (LOG.isDebugEnabled()) { + String message = + new StringBuffer().append("Ignoring exception: ").append(e) + .append(" at resolving: ").append(clsMap.getName()).toString(); + LOG.debug(message); + } + } } } - if (idList.size() == 0) { - // Found no identities based on identity definition of field. - // Try to find identities based on identity definition on class. - String[] idNames = clsMap.getIdentity(); - - FieldDescriptor identity; - for (int i = 0; i < idNames.length; i++) { - identity = findIdentityByName(fieldList, idNames[i], javaClass); - if (identity != null) { - idList.add(identity); + // Obtain the Java class. + Class javaClass = resolveType(clsMap.getName()); + if (clsMap.getVerifyConstructable()) { + if (!Types.isConstructable(javaClass, true)) { + throw new MappingException( + "mapping.classNotConstructable", javaClass.getName()); + } + } + xmlClassDesc.setJavaClass(javaClass); + + // Obtain XML name. + String xmlName; + MapTo mapTo = clsMap.getMapTo(); + if ((mapTo != null) && (mapTo.getXml() != null)) { + xmlName = mapTo.getXml(); + } else { + String clsName = javaClass.getName(); + int idx = clsName.lastIndexOf('.'); + if (idx >= 0) { clsName = clsName.substring(idx + 1); } + xmlName = getInternalContext().getXMLNaming().toXMLName(clsName); + } + xmlClassDesc.setXMLName(xmlName); + + // If this class extends another class, we need to obtain the extended + // class and make sure this class indeed extends it. + ClassDescriptor extDesc = getExtended(clsMap, javaClass); + xmlClassDesc.setExtends((XMLClassDescriptor) extDesc); + + // Create all field descriptors. + AbstractFieldDescriptor[] allFields = createFieldDescriptors(clsMap, javaClass); + + // Make sure there are no two fields with the same name. + checkFieldNameDuplicates(allFields, javaClass); + + // Identify identity and normal fields. Note that order must be preserved. + List fieldList = new ArrayList(allFields.length); + List idList = new ArrayList(); + if (extDesc == null) { + // Sort fields into 2 lists based on identity definition of field. + for (int i = 0; i < allFields.length; i++) { + if (!allFields[i].isIdentity()) { + fieldList.add(allFields[i]); } else { - throw new MappingException("mapping.identityMissing", - idNames[i], javaClass.getName()); + idList.add(allFields[i]); } } + + if (idList.size() == 0) { + // Found no identities based on identity definition of field. + // Try to find identities based on identity definition on class. + String[] idNames = clsMap.getIdentity(); + + FieldDescriptor identity; + for (int i = 0; i < idNames.length; i++) { + identity = findIdentityByName(fieldList, idNames[i], javaClass); + if (identity != null) { + idList.add(identity); + } else { + throw new MappingException("mapping.identityMissing", + idNames[i], javaClass.getName()); + } + } + } + } else { + // Add all fields of extending class to field list. + for (int i = 0; i < allFields.length; i++) { fieldList.add(allFields[i]); } + + // Add identity of extended class to identity list. + if (extDesc.getIdentity() != null) { idList.add(extDesc.getIdentity()); } + + // Search redefined identities in extending class. + FieldDescriptor identity; + for (int i = 0; i < idList.size(); i++) { + String idname = ((FieldDescriptor) idList.get(i)).getFieldName(); + identity = findIdentityByName(fieldList, idname, javaClass); + if (identity != null) { idList.set(i, identity); } + } } - } else { - // Add all fields of extending class to field list. - for (int i = 0; i < allFields.length; i++) { fieldList.add(allFields[i]); } - // Add identity of extended class to identity list. - if (extDesc.getIdentity() != null) { idList.add(extDesc.getIdentity()); } + FieldDescriptor xmlId = null; + if (idList.size() != 0) { xmlId = (FieldDescriptor) idList.get(0); } - // Search redefined identities in extending class. - FieldDescriptor identity; - for (int i = 0; i < idList.size(); i++) { - String idname = ((FieldDescriptor) idList.get(i)).getFieldName(); - identity = findIdentityByName(fieldList, idname, javaClass); - if (identity != null) { idList.set(i, identity); } + if (xmlId != null) { xmlClassDesc.setIdentity((XMLFieldDescriptorImpl) xmlId); } + for (int i = 0; i < fieldList.size(); i++) { + FieldDescriptor fieldDesc = (FieldDescriptor) fieldList.get(i); + if (fieldDesc != null) { + xmlClassDesc.addFieldDescriptor((XMLFieldDescriptorImpl) fieldDesc); + } } - } - - FieldDescriptor xmlId = null; - if (idList.size() != 0) { xmlId = (FieldDescriptor) idList.get(0); } - - if (xmlId != null) { xmlClassDesc.setIdentity((XMLFieldDescriptorImpl) xmlId); } - for (int i = 0; i < fieldList.size(); i++) { - FieldDescriptor fieldDesc = (FieldDescriptor) fieldList.get(i); - if (fieldDesc != null) { - xmlClassDesc.addFieldDescriptor((XMLFieldDescriptorImpl) fieldDesc); - } - } - - if (clsMap.getAutoComplete()) { - - XMLClassDescriptor referenceDesc = null; - Class type = xmlClassDesc.getJavaClass(); - - //-- check compiled descriptors - if (_cdResolver == null) { createResolver(); } - try { - referenceDesc = (XMLClassDescriptor) _cdResolver.resolve(type); - } catch (ResolverException rx) { - throw new MappingException(rx); - } + if (clsMap.getAutoComplete()) { - if (referenceDesc == null) { - Introspector introspector = new Introspector(); + XMLClassDescriptor referenceDesc = null; + + Class type = xmlClassDesc.getJavaClass(); + + //-- check compiled descriptors + if ((getInternalContext() == null) + || (getInternalContext().getXMLClassDescriptorResolver() == null)) { + String message = "Internal context or class descriptor resolver within are not valid"; + LOG.warn(message); + throw new IllegalStateException(message); + } try { - referenceDesc = introspector.generateClassDescriptor(type); - if (clsMap.getExtends() != null) { - //-- clear parent from introspected descriptor since - //-- a mapping was provided in the mapping file - ((XMLClassDescriptorImpl)referenceDesc).setExtends(null); + referenceDesc = (XMLClassDescriptor) getInternalContext().getXMLClassDescriptorResolver().resolve(type); + } catch (ResolverException rx) { + throw new MappingException(rx); + } + + if (referenceDesc == null) { + Introspector introspector = getInternalContext().getIntrospector(); + try { + referenceDesc = introspector.generateClassDescriptor(type); + if (clsMap.getExtends() != null) { + //-- clear parent from introspected descriptor since + //-- a mapping was provided in the mapping file + ((XMLClassDescriptorImpl) referenceDesc).setExtends(null); + } + } catch (MarshalException mx) { + String error = "unable to introspect class '" + + type.getName() + "' for auto-complete: "; + throw new MappingException(error + mx.getMessage()); } - } catch (MarshalException mx) { - String error = "unable to introspect class '" + - type.getName() + "' for auto-complete: "; - throw new MappingException(error + mx.getMessage()); } - } - //-- check for identity - String identity = ""; - if (clsMap.getIdentityCount() > 0) - identity = clsMap.getIdentity(0); + //-- check for identity + String identity = ""; + if (clsMap.getIdentityCount() > 0) { + identity = clsMap.getIdentity(0); + } - - FieldDescriptor[] xmlFields2 = xmlClassDesc.getFields(); + + FieldDescriptor[] xmlFields2 = xmlClassDesc.getFields(); - // Attributes - XMLFieldDescriptor[] introFields = referenceDesc.getAttributeDescriptors(); - for (int i = 0; ifieldName is in fields */ @@ -506,7 +518,7 @@ if (nodeType == null) { if (isPrimitive(javaClass)) - nodeType = _primitiveNodeType; + nodeType = getInternalContext().getPrimitiveNodeType(); else nodeType = NodeType.Element; } @@ -517,11 +529,11 @@ //-- Collections to be handled properly. if ((!deriveNameByClass) && ((xmlName == null) && (match == null))) { - xmlName = _naming.toXMLName( fieldDesc.getFieldName() ); + xmlName = getInternalContext().getXMLNaming().toXMLName( fieldDesc.getFieldName() ); match = xmlName + ' ' + fieldDesc.getFieldName(); } - xmlDesc = new XMLFieldDescriptorImpl( fieldDesc, xmlName, nodeType, _primitiveNodeType ); + xmlDesc = new XMLFieldDescriptorImpl( fieldDesc, xmlName, nodeType, getInternalContext().getPrimitiveNodeType() ); //-- transient? xmlDesc.setTransient(isXMLTransient); @@ -719,12 +731,16 @@ * @param loadPackageMappings a boolean that enables or * disables the loading of package specific mapping files */ - public void setLoadPackageMappings(boolean loadPackageMappings) - { - if (_cdResolver == null) { - createResolver(); + public void setLoadPackageMappings(final boolean loadPackageMappings) { + if ((getInternalContext() == null) + || (getInternalContext().getXMLClassDescriptorResolver() == null)) { + String message = "Internal context or class descriptor resolver within are not valid"; + LOG.warn(message); + throw new IllegalStateException(message); } - _cdResolver.setLoadPackageMappings(loadPackageMappings); + getInternalContext() + .getXMLClassDescriptorResolver() + .setLoadPackageMappings(loadPackageMappings); } //-- setLoadPackageMappings @@ -763,7 +779,7 @@ = new XMLFieldDescriptorImpl(fieldDesc, fieldDesc.getXMLName(), fieldDesc.getNodeType(), - _primitiveNodeType); + getInternalContext().getPrimitiveNodeType()); //-- nullify xmlName so that auto-naming will be enabled, //-- we can't do this in the constructor because //-- XMLFieldDescriptorImpl will create a default one. @@ -784,7 +800,7 @@ //-- Change fieldType of original field descriptor and //-- return new descriptor - return new XMLContainerElementFieldDescriptor(fieldDesc, _primitiveNodeType); + return new XMLContainerElementFieldDescriptor(fieldDesc, getInternalContext().getPrimitiveNodeType()); } //-- createWrapperDescriptor /** Index: src/main/java/org/exolab/castor/xml/XMLContext.java =================================================================== --- src/main/java/org/exolab/castor/xml/XMLContext.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/XMLContext.java (working copy) @@ -15,11 +15,26 @@ */ package org.exolab.castor.xml; +import java.io.IOException; +import java.io.Writer; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.castor.mapping.BindingType; import org.castor.mapping.MappingUnmarshaller; +import org.castor.xml.InternalContext; import org.exolab.castor.mapping.Mapping; import org.exolab.castor.mapping.MappingException; import org.exolab.castor.mapping.MappingLoader; +import org.exolab.castor.tools.MappingTool; +import org.exolab.castor.util.ChangeLog2XML; +import org.exolab.castor.xml.schema.Resolver; +import org.exolab.castor.xml.schema.ScopableResolver; +import org.exolab.castor.xml.schema.reader.SchemaReader; +import org.exolab.castor.xml.schema.writer.SchemaWriter; +import org.exolab.castor.xml.util.ResolverStrategy; +import org.exolab.castor.xml.util.resolvers.CastorXMLStrategy; +import org.xml.sax.InputSource; /** * Bootstrap class for Castor XML that allows you to load information about the @@ -29,21 +44,37 @@ * @since 1.1.2 */ public class XMLContext { - + /** Logger to be used. */ + private static final Log LOG = LogFactory.getFactory().getInstance(XMLContext.class); + /** - * {@link XMLClassDescriptorResolver} instance used for caching XML-related - * class descriptors. + * The internal XML context is the class which holds a couple of Castor states as it + * provides some central methods needed in various places of Castor. */ - private XMLClassDescriptorResolver resolver; + private InternalContext _internalContext; /** - * Creates an instance of {@link XMLContext}, preconfigured with class descriptors - * loaded for the given package name. + * Creates an instance of {@link XMLContext} with an empty internal XML context. */ public XMLContext() { - resolver = (XMLClassDescriptorResolver) ClassDescriptorResolverFactory - .createClassDescriptorResolver(BindingType.XML); - resolver.setClassLoader(getClass().getClassLoader()); + _internalContext = new InternalContext(); + + _internalContext.setClassLoader(getClass().getClassLoader()); + + XMLClassDescriptorResolver cdr = (XMLClassDescriptorResolver) ClassDescriptorResolverFactory + .createClassDescriptorResolver(BindingType.XML); + cdr.setInternalContext(_internalContext); + _internalContext.setXMLClassDescriptorResolver(cdr); + + Introspector introspector = new Introspector(); + introspector.setInternalContext(_internalContext); + _internalContext.setIntrospector(introspector); + + ResolverStrategy resolverStrategy = new CastorXMLStrategy(); + _internalContext.setResolverStrategy(resolverStrategy); + + Resolver schemaResolver = new ScopableResolver(); + _internalContext.setSchemaResolver(schemaResolver); } /** @@ -52,33 +83,26 @@ * descriptors will be derived. * @throws MappingException If the {@link Mapping} cannot be loaded and analyzed successfully. */ - public void addMapping(Mapping mapping) throws MappingException { + public void addMapping(final Mapping mapping) throws MappingException { MappingUnmarshaller mappingUnmarshaller = new MappingUnmarshaller(); - MappingLoader mappingLoader = mappingUnmarshaller.getMappingLoader(mapping, BindingType.XML); - resolver.setMappingLoader(mappingLoader); + mappingUnmarshaller.setInternalContext(_internalContext); + MappingLoader mappingLoader = + mappingUnmarshaller.getMappingLoader(mapping, BindingType.XML); + _internalContext.getXMLClassDescriptorResolver() + .setMappingLoader(mappingLoader); } -// /** -// * Instructs Castor to load class descriptors from the mapping given. -// * @param mapping Castor XML mapping (file), from which the required class -// * descriptors will be derived. -// */ -// public static Mapping loadMapping(InputSource mappingFile) { -// Mapping mapping = XMLContext.createMapping(); -// mapping.loadMapping(mappingFile); -// return mapping; -// } -// /** * Loads the class descriptor for the class instance specified. The use of this method is useful - * when no mapping is used, as happens when the domain classes hase been generated + * when no mapping is used, as happens when the domain classes has been generated * using the XML code generator (in which case instead of a mapping file class * descriptor files will be generated). * - * @param className Name of the class for which the associated descriptor should be loaded. + * @param clazz the class for which the associated descriptor should be loaded. + * @throws ResolverException in case that resolving the Class fails fatally */ - public void addClass(final String className) throws ResolverException { - resolver.addClass(className); + public void addClass(final Class clazz) throws ResolverException { + _internalContext.getXMLClassDescriptorResolver().addClass(clazz); } /** @@ -87,10 +111,11 @@ * using the XML code generator (in which case instead of a mapping file class * descriptor files will be generated). * - * @param className Name of the class for which the associated descriptor should be loaded. + * @param clazzes the classes for which the associated descriptor should be loaded. + * @throws ResolverException in case that resolving the Class fails fatally */ - public void addClasses(final String[] classNames) throws ResolverException { - resolver.addClasses(classNames); + public void addClasses(final Class[] clazzes) throws ResolverException { + _internalContext.getXMLClassDescriptorResolver().addClasses(clazzes); } /** @@ -103,10 +128,11 @@ * file with your generated classes (as generated by the XML code generator). *

* @param packageName The package name for the (descriptor) classes - * @throws ResolverException If there's a problem loading class descriptors for the given package. + * @throws ResolverException + * If there's a problem loading class descriptors for the given package. */ public void addPackage(final String packageName) throws ResolverException { - resolver.addPackage(packageName); + _internalContext.getXMLClassDescriptorResolver().addPackage(packageName); } /** @@ -119,17 +145,18 @@ * files with your generated classes (as generated by the XML code generator). *

* @param packageNames The package names for the (descriptor) classes - * @throws ResolverException If there's a problem loading class descriptors for the given package. + * @throws ResolverException + * If there's a problem loading class descriptors for the given package. */ public void addPackages(final String[] packageNames) throws ResolverException { - resolver.addPackages(packageNames); + _internalContext.getXMLClassDescriptorResolver().addPackages(packageNames); } /** * Creates an instance of a Castor XML specific {@link Mapping} instance. * @return a Castor XML specific {@link Mapping} instance. */ - public static Mapping createMapping() { + public Mapping createMapping() { Mapping mapping = new Mapping(); // mapping.setBindingType(BindingType.XML); return mapping; @@ -140,8 +167,11 @@ * @return A new {@link Marshaller} instance. */ public Marshaller createMarshaller() { + if (LOG.isDebugEnabled()) { + LOG.debug("Creating new Marshaller instance."); + } Marshaller marshaller = new Marshaller(); - marshaller.setResolver(resolver); + marshaller.setInternalContext(_internalContext); return marshaller; } @@ -152,19 +182,104 @@ * descriptors cached as loaded above. */ public Unmarshaller createUnmarshaller() { - Unmarshaller unmarshaller = new Unmarshaller(); - unmarshaller.setResolver(resolver); + if (LOG.isDebugEnabled()) { + LOG.debug("Creating new Unmarshaller instance."); + } + Unmarshaller unmarshaller = new Unmarshaller(_internalContext); return unmarshaller; } + + /** + * To create a schema reader instance for reading XSD files. + * @param inputSource the InputSource to read from + * @return the SchemaReader instance created and initialized + */ + public SchemaReader createSchemaReader(final InputSource inputSource) { + if (LOG.isDebugEnabled()) { + LOG.debug("Creating new SchemaReader instance."); + } + SchemaReader sr = new SchemaReader(); + sr.setInternalContext(_internalContext); + sr.setInputSource(inputSource); + return sr; + } + + /** + * To create a schema writer instance for writing XSD files. + * @param writer the Writer to write the text representation of the schema to + * @return the SchemaWriter instance created and initialized + * @throws IOException in case that initialization of SchemaWriter fails + */ + public SchemaWriter createSchemaWriter(final Writer writer) throws IOException { + if (LOG.isDebugEnabled()) { + LOG.debug("Creating new SchemaWriter instance."); + } + SchemaWriter sw = new SchemaWriter(); + sw.setInternalContext(_internalContext); + sw.setDocumentHandler(writer); + return sw; + } /** - * Sets an application-specific {@link XMLClassDescriptorResolver} instance - * @param resolver + * To create a MappingTool instance. + * @return the MappingTool instance ready to use */ - public void setResolver(XMLClassDescriptorResolver resolver) { - this.resolver = resolver; + public MappingTool createMappingTool() { + if (LOG.isDebugEnabled()) { + LOG.debug("Creating new MappingTool instance."); + } + MappingTool mt = new MappingTool(); + mt.setInternalContext(_internalContext); + return mt; } - + /** + * To create a new {@link ChangeLog2XML} instance. + * @return the {@link ChangeLog2XML} instance ready to use + */ + public ChangeLog2XML createChangeLog2XML() { + if (LOG.isDebugEnabled()) { + LOG.debug("Creating new ChangeLog2XML instance."); + } + ChangeLog2XML changeLog2XML = new ChangeLog2XML(); + changeLog2XML.setInternalContext(_internalContext); + return changeLog2XML; + } + + /** + * To set properties for marshalling and unmarshalling behavior. + * @param propertyName name of the property to set + * @param value the value to set to + */ + public void setProperty(final String propertyName, final Object value) { + _internalContext.setProperty(propertyName, value); + } + + /** + * To set properties for marshalling and unmarshalling behavior. + * @param propertyName name of the property to set + * @param value the value to set to + */ + public void setProperty(final String propertyName, final boolean value) { + _internalContext.setProperty(propertyName, value); + } + + /** + * To get the value of a specific property. + * @param propertyName name of the Property + * @return the value (Object) of the property + */ + public Object getProperty(final String propertyName) { + return _internalContext.getProperty(propertyName); + } + + /** + * To get the {@link InternalContext} as used when instantiating other + * classes. + * + * @return the {@link InternalContext} used + */ + public InternalContext getInternalContext() { + return _internalContext; + } } - Index: src/main/java/org/exolab/castor/xml/XMLClassDescriptorResolver.java =================================================================== --- src/main/java/org/exolab/castor/xml/XMLClassDescriptorResolver.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/XMLClassDescriptorResolver.java (working copy) @@ -1,217 +1,291 @@ /** * Redistribution and use of this software and associated documentation - * ("Software"), with or without modification, are permitted provided - * that the following conditions are met: - * - * 1. Redistributions of source code must retain copyright - * statements and notices. Redistributions must also contain a - * copy of this document. - * - * 2. Redistributions in binary form must reproduce the - * above copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * 3. The name "Exolab" must not be used to endorse or promote - * products derived from this Software without prior written - * permission of Intalio, Inc. For written permission, - * please contact info@exolab.org. - * - * 4. Products derived from this Software may not be called "Exolab" - * nor may "Exolab" appear in their names without prior written - * permission of Intalio, Inc. Exolab is a registered - * trademark of Intalio, Inc. - * - * 5. Due credit should be given to the Exolab Project - * (http://www.exolab.org/). - * - * THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT - * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL - * INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * + * ("Software"), with or without modification, are permitted provided that the + * following conditions are met: + * + * 1. Redistributions of source code must retain copyright statements and + * notices. Redistributions must also contain a copy of this document. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. The name "Exolab" must not be used to endorse or promote products derived + * from this Software without prior written permission of Intalio, Inc. For + * written permission, please contact info@exolab.org. + * + * 4. Products derived from this Software may not be called "Exolab" nor may + * "Exolab" appear in their names without prior written permission of Intalio, + * Inc. Exolab is a registered trademark of Intalio, Inc. + * + * 5. Due credit should be given to the Exolab Project (http://www.exolab.org/). + * + * THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * * Copyright 1999 (C) Intalio, Inc. All Rights Reserved. - * - * This file was originally developed by Keith Visco during the - * course of employment at Intalio Inc. - * All portions of this file developed by Keith Visco after Jan 19 2005 are - * Copyright (C) 2005 Keith Visco. All Rights Reserved. * + * This file was originally developed by Keith Visco during the course of + * employment at Intalio Inc. All portions of this file developed by Keith Visco + * after Jan 19 2005 are Copyright (C) 2005 Keith Visco. All Rights Reserved. + * * $Id: ClassDescriptorResolver.java 5951 2006-05-30 22:18:48Z bsnyder $ */ - package org.exolab.castor.xml; import java.util.Iterator; +import org.castor.xml.InternalContext; +import org.exolab.castor.xml.util.ResolverStrategy; /** * An interface for finding or "resolving" XMLClassDescriptor classes. * - *
- * Note: - * This interface is used by the marshalling Framework for - * resolving XMLClassDescriptors for non-primitive types. - * There are no guarantees that this class will be called for - * java native classes. + *
Note: This interface is used by the marshalling Framework for + * resolving XMLClassDescriptors for non-primitive types. There are no + * guarantees that this class will be called for java native classes. * * @author Keith Visco - * @version $Revision: 5951 $ $Date: 2005-02-28 17:41:38 -0700 (Mon, 28 Feb 2005) $ + * @version $Revision: 5951 $ $Date: 2005-02-28 17:41:38 -0700 (Mon, 28 Feb + * 2005) $ */ public interface XMLClassDescriptorResolver extends ClassDescriptorResolver { - -// /** -// * Returns the XMLClassDescriptor for the given class -// * @param type the Class to find the XMLClassDescriptor for -// * @return the XMLClassDescriptor for the given class -// **/ -// ClassDescriptor resolve(Class type) throws ResolverException; - + /** - * Returns the XMLClassDescriptor for the given class name + * To set the XMLContext to be used. * - * @param className the class name to find the XMLClassDescriptor for + * @param xmlContext + * the XMLContext to be used + */ + void setInternalContext(final InternalContext xmlContext); + + /** + * Enables or disables introspection. Introspection is enabled by default. + * + * @param enable + * a flag to indicate whether or not introspection is allowed. + */ + void setUseIntrospection(final boolean enable); + + /** + * Sets whether or not to look for and load package specific mapping files + * (".castor.xml"). + * + * @param loadPackageMappings + * a boolean that enables or disables the loading of package + * specific mapping files + */ + void setLoadPackageMappings(final boolean loadPackageMappings); + + /** + * Sets the ClassLoader to use when loading class descriptors. + * + * @param loader + * the ClassLoader to use + */ + void setClassLoader(ClassLoader loader); + + /** + * The resolver strategy to use for class and package resolving. Will set + * the current attributes into the new strategy. + * + * @param resolverStrategy + * the ResolverStrategy to use for resolve calls + */ + void setResolverStrategy(final ResolverStrategy resolverStrategy); + + /** + * To set the Introspector to be used. It is stored as attribute of resolver + * and set as property into the current strategy. + * + * @param introspector + * the Introspector to use + */ + void setIntrospector(final Introspector introspector); + + /** + * Returns the XMLClassDescriptor for the given class name. + * + * @param className + * the class name to find the XMLClassDescriptor for * @return the XMLClassDescriptor for the given class name + * @throws ResolverException in case that resolving fails unrecoverable */ - XMLClassDescriptor resolve(String className) - throws ResolverException; - + XMLClassDescriptor resolve(String className) throws ResolverException; + /** - * Returns the XMLClassDescriptor for the given class name + * Returns the XMLClassDescriptor for the given class name. * - * @param className the class name to find the XMLClassDescriptor for - * @param loader the ClassLoader to use + * @param className + * the class name to find the XMLClassDescriptor for + * @param loader + * the ClassLoader to use * @return the XMLClassDescriptor for the given class name + * @throws ResolverException in case that resolving fails unrecoverable */ - XMLClassDescriptor resolve(String className, ClassLoader loader) - throws ResolverException; - + XMLClassDescriptor resolve(String className, ClassLoader loader) throws ResolverException; + /** - * Returns the first XMLClassDescriptor that matches the given - * XML name and namespaceURI. Null is returned if no descriptor - * can be found. - * - * @param xmlName The class name to find the XMLClassDescriptor for. - * @param loader The ClassLoader to use. + * Returns the first XMLClassDescriptor that matches the given XML name and + * namespaceURI. Null is returned if no descriptor can be found. + * + * @param xmlName + * The class name to find the XMLClassDescriptor for. + * @param namespaceURI + * The namespace URI to identify the XMLClassDescriptor. + * @param loader + * The ClassLoader to use. * @return The XMLClassDescriptor for the given XML name. + * @throws ResolverException in case that resolving fails unrecoverable */ - XMLClassDescriptor resolveByXMLName - (String xmlName, String namespaceURI, ClassLoader loader) - throws ResolverException; + XMLClassDescriptor resolveByXMLName(String xmlName, String namespaceURI, ClassLoader loader) + throws ResolverException; /** - * Returns an enumeration of XMLClassDescriptor objects that - * match the given xml name. - * - * @param xmlName The class name to find the XMLClassDescriptor for. - * @param loader The ClassLoader to use. + * Returns an enumeration of XMLClassDescriptor objects that match the given + * xml name. + * + * @param xmlName + * The class name to find the XMLClassDescriptor for. + * @param namespaceURI + * The namespace URI to identify the XMLClassDescriptor. + * @param loader + * The ClassLoader to use. * @return An Iterator of XMLClassDescriptor objects. + * @throws ResolverException in case that resolving fails unrecoverable */ - Iterator resolveAllByXMLName - (String xmlName, String namespaceURI, ClassLoader loader) - throws ResolverException; - + Iterator resolveAllByXMLName(String xmlName, String namespaceURI, ClassLoader loader) + throws ResolverException; + /** - * Sets the ClassLoader to use when loading class descriptors - * @param loader the ClassLoader to use - **/ - void setClassLoader(ClassLoader loader); - - /** - * Loads the class descriptor for the class instance specified. The use of this method is useful - * when no mapping is used, as happens when the domain classes hase been generated - * using the XML code generator (in which case instead of a mapping file class - * descriptor files will be generated). + * Loads the class descriptor for the class instance specified. The use of + * this method is useful when no mapping is used, as happens when the domain + * classes hase been generated using the XML code generator (in which case + * instead of a mapping file class descriptor files will be generated). * - * @param className Name of the class for which the associated descriptor should be loaded. - * @throws ResolverException If there's an unrecoverable problem with resolving a certain class. - */ - public void addClass(final String className) throws ResolverException; + * @param className + * Name of the class for which the associated descriptor should + * be loaded. + * @throws ResolverException + * If there's an unrecoverable problem with resolving a certain + * class. + */ + void addClass(final String className) throws ResolverException; /** - * Loads the class descriptors for the class instances specified. The use of this method is useful - * when no mapping is used, as happens when the domain classes hase been generated - * using the XML code generator (in which case instead of a mapping file class - * descriptor files will be generated). + * Loads the class descriptors for the class instances specified. The use of + * this method is useful when no mapping is used, as happens when the domain + * classes hase been generated using the XML code generator (in which case + * instead of a mapping file class descriptor files will be generated). * - * @param classNames Names of the classes for which the associated descriptors should be loaded. - * @throws ResolverException If there's an unrecoverable problem with resolving a certain class. - */ - public void addClasses(final String[] classNames) throws ResolverException; - + * @param classNames + * Names of the classes for which the associated descriptors + * should be loaded. + * @throws ResolverException + * If there's an unrecoverable problem with resolving a certain + * class. + */ + void addClasses(final String[] classNames) throws ResolverException; + /** - * Loads the class descriptor for the class instance specified. The use of this method is useful - * when no mapping is used, as happens when the domain classes have been generated - * using the XML code generator (in which case instead of a mapping file class - * descriptor files will be generated). + * Loads the class descriptor for the class instance specified. The use of + * this method is useful when no mapping is used, as happens when the domain + * classes have been generated using the XML code generator (in which case + * instead of a mapping file class descriptor files will be generated). * - * @param clazz Class for which the associated descriptor should be loaded. - * @throws ResolverException If there's an unrecoverable problem with resolving a certain class. - */ - public void addClass(final Class clazz) throws ResolverException; + * @param clazz + * Class for which the associated descriptor should be loaded. + * @throws ResolverException + * If there's an unrecoverable problem with resolving a certain + * class. + */ + void addClass(final Class clazz) throws ResolverException; /** - * Loads the class descriptors for the class instances specified. The use of this method is useful - * when no mapping is used, as happens when the domain classes hase been generated - * using the XML code generator (in which case instead of a mapping file class - * descriptor files will be generated). + * Loads the class descriptors for the class instances specified. The use of + * this method is useful when no mapping is used, as happens when the domain + * classes hase been generated using the XML code generator (in which case + * instead of a mapping file class descriptor files will be generated). * - * @param clazzes Classes for which the associated descriptors should be loaded. - * @throws ResolverException If there's an unrecoverable problem with resolving a certain class. - */ - public void addClasses(final Class[] clazzes) throws ResolverException; + * @param clazzes + * Classes for which the associated descriptors should be loaded. + * @throws ResolverException + * If there's an unrecoverable problem with resolving a certain + * class. + */ + void addClasses(final Class[] clazzes) throws ResolverException; /** - * Loads class descriptors from the package specified. The use of this method is useful - * when no mapping is used, as happens when the domain classes hase been generated - * using the XML code generator (in which case instead of a mapping file class - * descriptor files will be generated). + * Loads class descriptors from the package specified. The use of this + * method is useful when no mapping is used, as happens when the domain + * classes hase been generated using the XML code generator (in which case + * instead of a mapping file class descriptor files will be generated). *

- * Please note that this functionality will work only if you provide the .castor.cdr - * file with your generated classes (as generated by the XML code generator). + * Please note that this functionality will work only if you provide the + * .castor.cdr file with your generated classes (as generated by + * the XML code generator). *

- * @param packageName The package name for the (descriptor) classes - * @throws ResolverException If there's a problem loading class descriptors for the given package. + * + * @param packageName + * The package name for the (descriptor) classes + * @throws ResolverException + * If there's a problem loading class descriptors for the given + * package. */ - public void addPackage(final String packageName) throws ResolverException; + void addPackage(final String packageName) throws ResolverException; /** - * Loads class descriptors from the packages specified. The use of this method is useful - * when no mapping is used, as happens when the domain classes hase been generated - * using the XML code generator (in which case instead of a mapping file class - * descriptor files will be generated). + * Loads class descriptors from the packages specified. The use of this + * method is useful when no mapping is used, as happens when the domain + * classes hase been generated using the XML code generator (in which case + * instead of a mapping file class descriptor files will be generated). *

- * Please note that this functionality will work only if you provide the .castor.cdr - * files with your generated classes (as generated by the XML code generator). + * Please note that this functionality will work only if you provide the + * .castor.cdr files with your generated classes (as generated by + * the XML code generator). *

- * @param packageNames The package names for the (descriptor) classes - * @throws ResolverException If there's a problem loading class descriptors for the given package. + * + * @param packageNames + * The package names for the (descriptor) classes + * @throws ResolverException + * If there's a problem loading class descriptors for the given + * package. */ - public void addPackages(final String[] packageNames) throws ResolverException; - + void addPackages(final String[] packageNames) throws ResolverException; + /** - * Loads class descriptors from the package specified. The use of this method is useful - * when no mapping is used, as happens when the domain classes hase been generated - * using the XML code generator (in which case instead of a mapping file class - * descriptor files will be generated). + * Loads class descriptors from the package specified. The use of this + * method is useful when no mapping is used, as happens when the domain + * classes hase been generated using the XML code generator (in which case + * instead of a mapping file class descriptor files will be generated). *

- * Please note that this functionality will work only if you provide the .castor.cdr - * file with your generated classes (as generated by the XML code generator). + * Please note that this functionality will work only if you provide the + * .castor.cdr file with your generated classes (as generated by + * the XML code generator). *

- * @param packageName The package name for the (descriptor) classes - * @throws ResolverException If there's a problem loading class descriptors for the given package. + * + * @param packageName + * The package name for the (descriptor) classes + * @throws ResolverException + * If there's a problem loading class descriptors for the given + * package. * @deprecated Please use e.g. #addPackage(String) instead. */ - void loadClassDescriptors(final String packageName) - throws ResolverException; - -} //-- ClassDescriptorResolver + void loadClassDescriptors(final String packageName) throws ResolverException; + + /** + * To clear the descriptor cache. + * @since 1.1.3 + */ + void cleanDescriptorCache(); + +} // -- ClassDescriptorResolver Index: src/main/java/org/exolab/castor/xml/UnmarshalHandler.java =================================================================== --- src/main/java/org/exolab/castor/xml/UnmarshalHandler.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/UnmarshalHandler.java (working copy) @@ -66,6 +66,7 @@ import org.castor.mapping.BindingType; import org.castor.util.Base64Decoder; import org.castor.util.HexDecoder; +import org.castor.xml.XMLConfiguration; import org.exolab.castor.mapping.ClassDescriptor; import org.exolab.castor.mapping.ExtendedFieldHandler; import org.exolab.castor.mapping.FieldHandler; @@ -166,21 +167,23 @@ */ private boolean _clearCollections = false; - /** - * The Castor configuration. - */ - private Configuration _config = null; + // TODO: Joachim 2007-09-04 remove me +// /** +// * The Castor configuration. +// */ +// private Configuration _config = null; /** * The SAX Document Locator. **/ private Locator _locator = null; - /** - * The ClassDescriptorResolver which is used to "resolve" - * or find ClassDescriptors. - **/ - private XMLClassDescriptorResolver _cdResolver = null; +// TODO: Joachim +// /** +// * The ClassDescriptorResolver which is used to "resolve" +// * or find ClassDescriptors. +// **/ +// private XMLClassDescriptorResolver _cdResolver = null; /** * The IDResolver for resolving IDReferences. @@ -451,15 +454,15 @@ _reuseObjects = reuse; } //-- setReuseObjects - /** - * Sets the ClassDescriptorResolver to use for loading and - * resolving ClassDescriptors - * - * @param cdResolver the ClassDescriptorResolver to use - **/ - public void setResolver(XMLClassDescriptorResolver cdResolver) { - this._cdResolver = cdResolver; - } //-- setResolver +// /** +// * Sets the ClassDescriptorResolver to use for loading and +// * resolving ClassDescriptors +// * +// * @param cdResolver the ClassDescriptorResolver to use +// **/ +// public void setResolver(XMLClassDescriptorResolver cdResolver) { +// this._cdResolver = cdResolver; +// } //-- setResolver /** * Sets the root (top-level) object to use for unmarshalling into. @@ -873,7 +876,7 @@ ValidationException last = null; //-- check unresolved references - if (_resolveTable != null && !_config.getLenientIdValidation()) { + if (_resolveTable != null && !getInternalContext().getLenientIdValidation()) { Enumeration enumeration = _resolveTable.keys(); while (enumeration.hasMoreElements()) { Object ref = enumeration.nextElement(); @@ -892,10 +895,12 @@ try { Validator validator = new Validator(); ValidationContext context = new ValidationContext(); - context.setResolver(_cdResolver); - context.setConfiguration(_config); +// context.setResolver(_cdResolver); + // TODO: Joachim 2007-09-04 remove me +// context.setConfiguration(_config); + context.setInternalContext(getInternalContext()); validator.validate(state.object, context); - if (!_config.getLenientIdValidation()) { + if (!getInternalContext().getLenientIdValidation()) { validator.checkUnresolvedIdrefs(context); } context.cleanup(); @@ -1457,14 +1462,20 @@ _topClass = _topObject.getClass(); } } - if (_cdResolver == null) { - if (_topClass == null) { - String err = "The class for the root element '" + - name + "' could not be found."; - throw new SAXException(err); - } - _cdResolver = (XMLClassDescriptorResolver) ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML); - _cdResolver.setClassLoader(_loader); +// if (_cdResolver == null) { +// if (_topClass == null) { +// String err = "The class for the root element '" + +// name + "' could not be found."; +// throw new SAXException(err); +// } +// _cdResolver = (XMLClassDescriptorResolver) ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML); +// _cdResolver.setClassLoader(_loader); +// } + if (getInternalContext().getXMLClassDescriptorResolver() == null) { + // Joachim 2007-09-04 check is new + String message = "XMLClassDescriptorResolver is not set!"; + LOG.warn(message); + throw new IllegalStateException(message); } _topState = new UnmarshalState(); @@ -1789,7 +1800,7 @@ if ((descriptor == null) && (!targetState.wrapper)) { MarshalFramework.InheritanceMatch[] matches = null; try { - matches = searchInheritance(name, namespace, classDesc, _cdResolver); + matches = searchInheritance(name, namespace, classDesc); // TODO: Joachim, _cdResolver); } catch(MarshalException rx) { //-- TODO: @@ -1863,7 +1874,7 @@ count++; } - if (descriptor != null && isValidating() && !_config.getLenientSequenceOrder()) { + if (descriptor != null && isValidating() && !getInternalContext().getLenientSequenceOrder()) { try { classDesc.checkDescriptorForCorrectOrderWithinSequence(descriptor, parentState, name); } catch (ValidationException e) { @@ -1901,8 +1912,10 @@ //-- If we are skipping elements that have appeared in the XML but for //-- which we have no mapping, increase the ignore depth counter and return - boolean lenientElementStrictnessForIntrospection = Boolean.valueOf( - _config.getProperty("org.exolab.castor.xml.lenient.introspected.element.strictness", "true")).booleanValue(); + boolean lenientElementStrictnessForIntrospection = + getInternalContext() + .getBooleanProperty(XMLConfiguration.LENIENT_INTROSPECTED_ELEMENT_STRICTNESS) + .booleanValue(); if (! _strictElements) { ++_ignoreElementDepth; //-- remove the StateInfo we just added @@ -2433,19 +2446,20 @@ //- Protected Methods -/ //---------------------/ - /** - * Sets the current Castor configuration. Currently this - * Configuration is only used during Validation (which is - * why this method is currently protected, since it has - * no effect at this point on the actual configuration of - * the unmarshaller) - * - * Currently, this method should only be called by the - * Unmarshaller. - */ - protected void setConfiguration(Configuration config) { - _config = config; - } //-- setConfiguration + // TODO: Joachim 2007-09-04 remove me +// /** +// * Sets the current Castor configuration. Currently this +// * Configuration is only used during Validation (which is +// * why this method is currently protected, since it has +// * no effect at this point on the actual configuration of +// * the unmarshaller) +// * +// * Currently, this method should only be called by the +// * Unmarshaller. +// */ +// protected void setConfiguration(Configuration config) { +// _config = config; +// } //-- setConfiguration //-------------------/ //- Private Methods -/ @@ -2536,7 +2550,7 @@ XMLClassDescriptor classDesc = null; try { - classDesc = _cdResolver.resolveByXMLName(type, typeNamespaceURI, _loader); + classDesc = getInternalContext().getXMLClassDescriptorResolver().resolveByXMLName(type, typeNamespaceURI, _loader); if (classDesc != null) return classDesc.getJavaClass().getName(); @@ -2552,7 +2566,7 @@ if ((mappedPackage != null) && (mappedPackage.length() > 0)) { adjClassName = mappedPackage + "." + className; } - classDesc = _cdResolver.resolve(adjClassName, _loader); + classDesc = getInternalContext().getXMLClassDescriptorResolver().resolve(adjClassName, _loader); if (classDesc != null) return classDesc.getJavaClass().getName(); @@ -2561,7 +2575,7 @@ adjClassName = currentPackage + '.' + className; } - classDesc = _cdResolver.resolve(adjClassName, _loader); + classDesc = getInternalContext().getXMLClassDescriptorResolver().resolve(adjClassName, _loader); if (classDesc != null) return classDesc.getJavaClass().getName(); @@ -2570,7 +2584,7 @@ //-- that was marshalled with a previous Castor. A //-- bug fix in the XMLMappingLoader prevents old //-- xsi:type that are missing the "java:" - classDesc = _cdResolver.resolve(type, _loader); + classDesc = getInternalContext().getXMLClassDescriptorResolver().resolve(type, _loader); if (classDesc != null) return classDesc.getJavaClass().getName(); } @@ -2938,7 +2952,7 @@ if (classDesc.getIdentity() == descriptor) { try { - _idResolver.bind(attValue, parent, isValidating() && !_config.getLenientIdValidation()); + _idResolver.bind(attValue, parent, isValidating() && !getInternalContext().getLenientIdValidation()); } catch (ValidationException e) { throw new SAXException("Duplicate ID " + attValue + " encountered.", e); } @@ -3354,15 +3368,16 @@ if (_class.isArray()) return null; if (isPrimitive(_class)) return null; - if (_cdResolver == null) - _cdResolver = (XMLClassDescriptorResolver) - ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML); +// TODO: Joachim +// if (_cdResolver == null) +// _cdResolver = (XMLClassDescriptorResolver) +// ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML); XMLClassDescriptor classDesc = null; try { - classDesc = (XMLClassDescriptor) _cdResolver.resolve(_class); + classDesc = (XMLClassDescriptor) getInternalContext().getXMLClassDescriptorResolver().resolve(_class); } catch(ResolverException rx) { // TODO @@ -3390,14 +3405,15 @@ (String className, ClassLoader loader) throws SAXException { - if (_cdResolver == null) - _cdResolver = (XMLClassDescriptorResolver) - ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML); +// TODO: Joachim +// if (_cdResolver == null) +// _cdResolver = (XMLClassDescriptorResolver) +// ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML); XMLClassDescriptor classDesc = null; try { - classDesc = _cdResolver.resolve(className, loader); + classDesc = getInternalContext().getXMLClassDescriptorResolver().resolve(className, loader); } catch(ResolverException rx) { throw new SAXException(rx); @@ -3424,7 +3440,7 @@ { try { - return _cdResolver.resolveByXMLName(name, namespace, loader); + return getInternalContext().getXMLClassDescriptorResolver().resolveByXMLName(name, namespace, loader); } catch(ResolverException rx) { throw new SAXException(rx); Index: src/main/java/org/exolab/castor/xml/Introspector.java =================================================================== --- src/main/java/org/exolab/castor/xml/Introspector.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/Introspector.java (working copy) @@ -55,6 +55,8 @@ import java.util.Vector; import org.castor.xml.JavaNaming; +import org.castor.xml.XMLConfiguration; +import org.castor.xml.InternalContext; import org.exolab.castor.mapping.CollectionHandler; import org.exolab.castor.mapping.FieldHandler; import org.exolab.castor.mapping.FieldHandlerFactory; @@ -86,39 +88,7 @@ */ public final class Introspector { - /** - * The property name for enabling collection wrapping. - * The property controls whether or not collections - * (arrays, vectors, etc) should be wrapped in a container element. - * For example: - * - *

-     *    <foos>
-     *       <foo>foo1</foo>
-     *       <foo>foo2</foo>
-     *    </foos>
-     *
-     *   instead of the default:
-     *
-     *    <foos>foo1<foos>
-     *    <foos>foo2</foos>
-     *
-     * 
- * - * Use this property with a value of true or false in the - * castor.properties file - * - * org.exolab.castor.xml.introspector.wrapCollections=true - * -or- - * org.exolab.castor.xml.introspector.wrapCollections=false - * - * This property is false by default. - */ - public static final String WRAP_COLLECTIONS_PROPERTY = - "org.exolab.castor.xml.introspector.wrapCollections"; - - /** * The default FieldHandlerFactory */ private FieldHandlerFactory DEFAULT_HANDLER_FACTORY = new DefaultFieldHandlerFactory(); @@ -169,7 +139,7 @@ /** * The naming conventions to use **/ - private XMLNaming _naming = null; + private XMLNaming _xmlNaming = null; /** * The NodeType to use for primitives @@ -227,6 +197,8 @@ */ private JavaNaming _javaNaming; + private InternalContext _internalContext; + /** * Creates a new instance of the Introspector. */ @@ -239,40 +211,27 @@ * * @param classLoader */ - public Introspector(ClassLoader classLoader) { + public Introspector(final ClassLoader classLoader) { super(); _classLoader = classLoader; init(); } //-- Introspector private void init() { - - LocalConfiguration config = LocalConfiguration.getInstance(); - - if (_defaultNaming == null) { - _defaultNaming = config.getXMLNaming(_classLoader); + if (_internalContext != null) { + _javaNaming = _internalContext.getJavaNaming(); + _xmlNaming = _internalContext.getXMLNaming(); + setPrimitiveNodeType(_internalContext.getPrimitiveNodeType()); + _wrapCollectionsInContainer = _internalContext.getBooleanProperty(XMLConfiguration.WRAP_COLLECTIONS_PROPERTY).booleanValue(); + _saveMapKeys = + _internalContext.getBooleanProperty(XMLConfiguration.SAVE_MAP_KEYS).booleanValue(); } - _naming = _defaultNaming; - _javaNaming = config.getJavaNaming(); - - setPrimitiveNodeType(config.getPrimitiveNodeType()); - - //-- wrap collections in a container element? - String wrap = config.getProperty(WRAP_COLLECTIONS_PROPERTY, null); - if (wrap != null) { - _wrapCollectionsInContainer = Boolean.valueOf(wrap).booleanValue(); - } - - //-- Save Hashtable / Map keys ? - String saveKeys = config.getProperty(Configuration.Property.SaveMapKeys, null); - if (saveKeys != null) { - if ("false".equals(saveKeys) || "off".equals(saveKeys)) { - _saveMapKeys = false; - } - } - } //-- init + public void setInternalContext(InternalContext internalContext) { + _internalContext = internalContext; + init(); + } /** * Registers the given "generalized" FieldHandlerFactory with this @@ -525,7 +484,7 @@ MethodSet methodSet = (MethodSet) enumeration.nextElement(); //-- create XMLFieldDescriptor - String xmlName = _naming.toXMLName(methodSet.fieldName); + String xmlName = _xmlNaming.toXMLName(methodSet.fieldName); boolean isCollection = false; @@ -771,7 +730,7 @@ } String fieldName = field.getName(); - String xmlName = _naming.toXMLName(fieldName); + String xmlName = _xmlNaming.toXMLName(fieldName); //-- Create FieldHandler first, before the XMLFieldDescriptor //-- in case we need to use a custom handler @@ -983,9 +942,9 @@ **/ public void setNaming(XMLNaming naming) { if (naming == null) - _naming = _defaultNaming; + _xmlNaming = _defaultNaming; else - _naming = naming; + _xmlNaming = naming; } //-- setNaming /** Index: src/main/java/org/exolab/castor/xml/Unmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/Unmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/Unmarshaller.java (working copy) @@ -45,8 +45,6 @@ package org.exolab.castor.xml; - -//-- castor imports import java.io.PrintWriter; import java.io.Reader; import java.util.HashMap; @@ -57,11 +55,11 @@ import org.apache.commons.logging.LogFactory; import org.castor.mapping.BindingType; import org.castor.mapping.MappingUnmarshaller; +import org.castor.xml.InternalContext; +import org.castor.xml.XMLConfiguration; import org.exolab.castor.mapping.Mapping; import org.exolab.castor.mapping.MappingException; import org.exolab.castor.mapping.MappingLoader; -import org.exolab.castor.util.Configuration; -import org.exolab.castor.util.LocalConfiguration; import org.exolab.castor.util.ObjectFactory; import org.exolab.castor.xml.location.FileLocation; import org.exolab.castor.xml.util.DOMEventProducer; @@ -72,6 +70,7 @@ import org.xml.sax.Parser; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; + /** * An unmarshaller to allowing unmarshalling of XML documents to * Java Objects. The Class must specify @@ -84,7 +83,7 @@ public class Unmarshaller { /** - * Logger from commons-logging + * Logger from commons-logging. */ private static final Log LOG = LogFactory.getLog(Unmarshaller.class); @@ -93,13 +92,8 @@ //----------------------------/ /** - * The class descriptor resolver + * The Class that this Unmarshaller was created with. */ - private XMLClassDescriptorResolver _cdResolver = null; - - /** - * The Class that this Unmarshaller was created with - */ private Class _class = null; /** @@ -107,17 +101,11 @@ * arrays) should be cleared upon initial use by Castor. * False by default for backward compatibility. */ - private boolean _clearCollections = false; + private boolean _clearCollections = false; /** - * Castor configuration + * A user specified IDResolver for resolving IDREFs. */ - private Configuration _config = null; - - - /** - * A user specified IDResolver for resolving IDREFs - */ private IDResolver _idResolver = null; /** @@ -184,67 +172,101 @@ /** * An optional factory for unmarshalling objects */ - private ObjectFactory _objectFactory; + private ObjectFactory _objectFactory; + + /** + * The Castor XML context to use at unmarshalling. + */ + private InternalContext _internalContext; //----------------/ //- Constructors -/ //----------------/ + public Unmarshaller(final Class clazz) { + this(new XMLContext().getInternalContext(), clazz); + } + /** - * Creates a new basic Unmarshaller + * Creates a new basic Unmarshaller. * * When using this constructor it will most likely be * necessary to use a mapping file or ClassDescriptorResolver * So that the Unmarshaller can find the classes during the * unmarshalling process. */ - public Unmarshaller() { - this((Class)null, (ClassLoader)null); + public Unmarshaller(final InternalContext internalContext) { + this(internalContext, (Class) null, (ClassLoader) null); } //-- Unmarshaller() /** - * Creates a new Unmarshaller with the given Class + * Creates a new Unmarshaller with the given Class. * * @param c the Class to create the Unmarshaller for, this * may be null, if the Unmarshaller#setMapping is called * to load a mapping for the root element of xml document. */ - public Unmarshaller(Class c) { - this(c, null); + public Unmarshaller(final InternalContext internalContext, final Class c) { + this(internalContext, c, null); } //-- Unmarshaller(Class) /** - * Creates a new Unmarshaller with the given Class + * Creates a new Unmarshaller with the given Class. * + * @param internalContext the context to be used, for config, and such... * @param c the Class to create the Unmarshaller for, this * may be null, if the Unmarshaller#setMapping is called * to load a mapping for the root element of xml document. * @param loader The ClassLoader to use. */ - public Unmarshaller(Class c, ClassLoader loader) { + public Unmarshaller(final InternalContext internalContext, final Class c, final ClassLoader loader) { super(); - initConfig(); + + _internalContext = internalContext; + _validate = _internalContext.marshallingValidation(); + _ignoreExtraElements = (!_internalContext.strictElements()); + + //-- process namespace to package mappings + String mappings = + _internalContext.getStringProperty(XMLConfiguration.NAMESPACE_PACKAGE_MAPPINGS); + if (mappings != null) { + StringTokenizer tokens = new StringTokenizer(mappings, ","); + while (tokens.hasMoreTokens()) { + String token = tokens.nextToken(); + int sepIdx = token.indexOf('='); + if (sepIdx < 0) { + continue; + } + String ns = token.substring(0, sepIdx).trim(); + String javaPackage = token.substring(sepIdx + 1).trim(); + addNamespaceToPackageMapping(ns, javaPackage); + } + } + setClass(c); _loader = loader; if ((loader == null) && (c != null)) { _loader = c.getClassLoader(); } - _cdResolver = (XMLClassDescriptorResolver) - ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML); - _cdResolver.setClassLoader(loader); + _internalContext.setClassLoader(_loader); + } //-- Unmarshaller(Class) + public Unmarshaller(final Mapping mapping) throws MappingException { + this(new XMLContext().getInternalContext(), mapping); + } /** - * Creates a new Unmarshaller with the given Mapping + * Creates a new Unmarshaller with the given Mapping. * + * @param internalContext the internal context to use * @param mapping The Mapping to use. + * @throws MappingException in case that Unmarshaller fails to be instantiated */ - public Unmarshaller(Mapping mapping) - throws MappingException - { - super(); - initConfig(); + public Unmarshaller(final InternalContext internalContext, final Mapping mapping) + throws MappingException { + this(internalContext, null, null); +// initConfig(); if (mapping != null) { setMapping(mapping); this._loader = mapping.getClassLoader(); @@ -253,14 +275,16 @@ /** - * Creates a new Unmarshaller with the given Object + * Creates a new Unmarshaller with the given Object. * + * @param internalContext the internal context to use * @param root the instance to unmarshal into. This * may be null, if the Unmarshaller#setMapping is called * to load a mapping for the root element of xml document. */ - public Unmarshaller(Object root) { - initConfig(); + public Unmarshaller(final InternalContext internalContext, final Object root) { + this(internalContext, null, null); +// initConfig(); if (root != null) { final Class clazz = root.getClass(); setClass(clazz); @@ -268,35 +292,10 @@ } _instanceObj = root; } //-- Unmarshaller(Class) - - /** - * Used by constructors to get configuration information - */ - private void initConfig() { - _config = LocalConfiguration.getInstance(); - _validate = _config.marshallingValidation(); - _ignoreExtraElements = (!_config.strictElements()); - - //-- process namespace to package mappings - String mappings = _config.getProperty(Configuration.Property.NamespacePackages, null); - if (mappings != null) { - StringTokenizer tokens = new StringTokenizer(mappings, ","); - while(tokens.hasMoreTokens()) { - String token = tokens.nextToken(); - int sepIdx = token.indexOf('='); - if (sepIdx < 0) continue; - String ns = token.substring(0,sepIdx).trim(); - String javaPackage = token.substring(sepIdx+1).trim(); - addNamespaceToPackageMapping(ns, javaPackage); - } - } - - - } //-- initConfig /** * Adds a mapping from the given namespace URI to the given - * package name + * package name. * * @param nsURI the namespace URI to map from * @param packageName the package name to map to @@ -322,18 +321,12 @@ UnmarshalHandler handler = new UnmarshalHandler(_class); - if (_cdResolver == null) { - _cdResolver = (XMLClassDescriptorResolver) - ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML); - _cdResolver.setClassLoader(_loader); - } - handler.setResolver(_cdResolver); handler.setClearCollections(_clearCollections); handler.setReuseObjects(_reuseObjects); handler.setValidation(_validate); handler.setIgnoreExtraAttributes(_ignoreExtraAtts); handler.setIgnoreExtraElements(_ignoreExtraElements); - handler.setConfiguration(_config); + handler.setInternalContext(_internalContext); handler.setWhitespacePreserve(_wsPreserve); // If the object factory has been set, set it on the handler @@ -504,16 +497,10 @@ _loader = mapping.getClassLoader(); } - if (_cdResolver == null) { - _cdResolver = (XMLClassDescriptorResolver) ClassDescriptorResolverFactory - .createClassDescriptorResolver(BindingType.XML); - - _cdResolver.setClassLoader(_loader); - } - MappingUnmarshaller mum = new MappingUnmarshaller(); + mum.setInternalContext(_internalContext); MappingLoader resolver = mum.getMappingLoader(mapping, BindingType.XML); - _cdResolver.setMappingLoader(resolver); + _internalContext.getXMLClassDescriptorResolver().setMappingLoader(resolver); } /** @@ -530,26 +517,6 @@ } //-- setReuseObjects /** - * Sets the ClassDescriptorResolver to use during unmarshalling - * @param cdr the ClassDescriptorResolver to use - * @see #setMapping - *
- * Note: This method will nullify any Mapping - * currently being used by this Unmarshaller - **/ - public void setResolver( XMLClassDescriptorResolver cdr ) { - - if (cdr != null) - _cdResolver = cdr; - else { - _cdResolver = (XMLClassDescriptorResolver) - ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML); - _cdResolver.setClassLoader(_loader); - } - - } //-- setResolver - - /** * Sets an optional {@link UnmarshalListener} to receive pre and * post unmarshal notification for each Object in the tree. * An UnmarshalListener is often used to allow objects to @@ -683,15 +650,15 @@ //-- First try XMLReader try { - reader = _config.getXMLReader(); + reader = _internalContext.getXMLReader(); if (entityResolver != null) reader.setEntityResolver(entityResolver); - } catch(RuntimeException rx) { + } catch (RuntimeException rx) { LOG.debug("Unable to create SAX XMLReader, attempting SAX Parser."); } if (reader == null) { - parser = _config.getParser(); + parser = _internalContext.getParser(); if (parser == null) throw new MarshalException("Unable to create SAX Parser."); if (entityResolver != null) @@ -714,10 +681,10 @@ parser.parse(source); } } - catch(java.io.IOException ioe) { + catch (java.io.IOException ioe) { throw new MarshalException(ioe); } - catch(org.xml.sax.SAXException sx) { + catch (org.xml.sax.SAXException sx) { convertSAXExceptionToMarshalException(handler, sx); } @@ -808,8 +775,10 @@ * @param clazz The root class to be used during unmarshalling. * @return An {@link Unmarshaller} instance. */ - private static Unmarshaller createUnmarshaller(Class clazz) { - Unmarshaller unmarshaller = new Unmarshaller(clazz); + private static Unmarshaller createUnmarshaller(final Class clazz) { + XMLContext xmlContext = new XMLContext(); + Unmarshaller unmarshaller = xmlContext.createUnmarshaller(); + unmarshaller.setClass(clazz); // TODO: Should this be at level INFO? if (LOG.isDebugEnabled()) { @@ -869,36 +838,58 @@ return unmarshaller.unmarshal(node); } //-- void unmarshal(Writer) - /** - * Set an object factory for the unmarshaller. This - * factory will be used to construct the objects being - * unmarshalled. - * @param objectFactory Factory used for constructing objects - * during unmarshalling. - */ - public void setObjectFactory(ObjectFactory objectFactory) { - this._objectFactory = objectFactory; - } // -- setObjectFactory + /** + * Set an object factory for the unmarshaller. This factory will be used to + * construct the objects being unmarshalled. + * + * @param objectFactory + * Factory used for constructing objects during unmarshalling. + */ + public void setObjectFactory(final ObjectFactory objectFactory) { + this._objectFactory = objectFactory; + } // -- setObjectFactory - /** - * Returns the value of the given Castor XML-specific property. - * @param name Qualified name of the CASTOR XML-specific property. - * @return The current value of the given property. - * @since 1.1.2 - */ - public String getProperty(final String name) { - return _config.getProperties().getProperty(name); - } + /** + * Returns the value of the given Castor XML-specific property. + * + * @param name + * Qualified name of the CASTOR XML-specific property. + * @return The current value of the given property. + * @since 1.1.2 + */ + public String getProperty(final String name) { + Object propertyValue = _internalContext.getProperty(name); + if ((propertyValue != null) && !(propertyValue instanceof String)) { + String message = + "Requested property: " + name + + " is not of type String, but: " + propertyValue.getClass() + + " throwing IllegalStateException."; + LOG.warn(message); + throw new IllegalStateException(message); + } + return (String) propertyValue; + } - /** + /** * Sets a custom value of a given Castor XML-specific property. - * @param name Name of the Castor XML property - * @param value Custom value to set. + * + * @param name + * Name of the Castor XML property + * @param value + * Custom value to set. * @since 1.1.2 - */ - public void setProperty(final String name, final String value) { - _config.getProperties().setProperty(name, value); - } + */ + public void setProperty(final String name, final String value) { + _internalContext.setProperty(name, value); + } + + /** + * To set the internal XML Context to be used. + * @param xmlContext the context to be used + */ + public void setInternalContext(final InternalContext xmlContext) { + _internalContext = xmlContext; + } } //-- Unmarshaller Index: src/main/java/org/exolab/castor/xml/ValidationContext.java =================================================================== --- src/main/java/org/exolab/castor/xml/ValidationContext.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/ValidationContext.java (working copy) @@ -50,6 +50,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.castor.xml.InternalContext; import org.exolab.castor.util.Configuration; import org.exolab.castor.util.LocalConfiguration; @@ -61,24 +62,24 @@ * @version $Revision$ $Date: 2004-10-06 02:10:17 -0600 (Wed, 06 Oct 2004) $ */ public class ValidationContext { - /** Logger for debugging and error information. */ private static final Log LOG = LogFactory.getLog(ValidationContext.class); - /** The Castor configuration. */ - private Configuration _config = null; + /** The Castor internal context - mother of all dwelling. */ + private InternalContext _internalContext = null; + /** A flag to indicate fail-fast validation. When true, the first error * encounted will cause a Validation Exception. When false, the validator * should attempt to validate as much as possible, collecting as many errors * as possible before throwing a validation exception. */ private boolean _failFast = true; - /** The ClassDescriptorResolver to be used for loading and resolving - * ClassDescriptors during validation. */ - private XMLClassDescriptorResolver _resolver = null; + /** The List of objects marked as validated. */ private final Set _validated = new HashSet(); + /** The Set of already encountered IDs (of type <xsd:ID>). */ private final Set _ids = new HashSet(); + /** The Set of temporary unreseolved IDREFS. */ private final Set _unresolvedIdrefs = new HashSet(); @@ -90,24 +91,28 @@ } /** - * Returns the Configuration to use during validation. - * - * @return the Configuration to use. Will never be null. + * To get the {@link InternalContext} to use. + * @return the {@link InternalContext} to use */ - public Configuration getConfiguration() { - if (_config == null) { - _config = LocalConfiguration.getInstance(); - } - return _config; - } + public InternalContext getInternalContext() { + return _internalContext; + } /** + * To set which {@link InternalContext} should be used. + * @param internalContext the {@link InternalContext} to use + */ + public void setInternalContext(final InternalContext internalContext) { + _internalContext = internalContext; + } + + /** * Returns the ClassDescriptorResolver to use during validation. * * @return the ClassDescriptorResolver to use. May be null. */ - public XMLClassDescriptorResolver getResolver() { - return _resolver; + public XMLClassDescriptorResolver getClassDescriptorResolver() { + return _internalContext.getXMLClassDescriptorResolver(); } /** @@ -126,15 +131,6 @@ } /** - * Sets the Configuration used during validation. - * - * @param config the Configuration to use - */ - public void setConfiguration(final Configuration config) { - _config = config; - } - - /** * Sets the fail-fast flag. Fail-fast is enabled by default. When fail-fast * is enabled (default or by setting the flag to true) the validation * process will throw an exception upon the first error encountered. When @@ -154,15 +150,6 @@ } /** - * Sets the ClassDescriptorResolver to use during validation. - * - * @param resolver the ClassDescriptorResolver to use. - */ - public void setResolver(final XMLClassDescriptorResolver resolver) { - _resolver = resolver; - } - - /** * Checks whether an object has already been validated. * @param object The object for which the check should be performed * @return True if the object specified has already been validated. @@ -209,7 +196,7 @@ if (!_ids.contains(id)) { _ids.add(id); _unresolvedIdrefs.remove(id); - } else if (!_config.getLenientIdValidation()){ + } else if (!_internalContext.getLenientIdValidation()){ throw new ValidationException ("ID " + id + " is already used within current document."); } } @@ -251,5 +238,4 @@ _validated.clear(); _unresolvedIdrefs.clear(); } - } Index: src/main/java/org/exolab/castor/xml/MarshalFramework.java =================================================================== --- src/main/java/org/exolab/castor/xml/MarshalFramework.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/MarshalFramework.java (working copy) @@ -45,8 +45,11 @@ package org.exolab.castor.xml; +import java.util.Iterator; +import java.util.Vector; + +import org.castor.xml.InternalContext; import org.castor.xml.JavaNaming; -import org.castor.xml.JavaNamingImpl; import org.exolab.castor.mapping.ClassDescriptor; import org.exolab.castor.mapping.CollectionHandler; import org.exolab.castor.mapping.FieldDescriptor; @@ -54,10 +57,7 @@ import org.exolab.castor.mapping.loader.CollectionHandlers; import org.exolab.castor.util.ReflectionUtil; -import java.util.Iterator; -import java.util.Vector; - /** * A core class for common code shared throughout the * Marshalling Framework @@ -165,12 +165,12 @@ //-----------------------------/ //- Private variables -/ //-----------------------------/ - + /** - * The {@link JavaNaming} to use at unmarhsalling. + * The {@link InternalContext} to use at all un-marshal actions. * @since 1.1.3 */ - private JavaNaming _javaNaming; + private InternalContext _internalContext; //-----------------------------/ //- Public methods -/ @@ -180,7 +180,7 @@ * We need some stuff initialized here. */ public MarshalFramework() { - _javaNaming = new JavaNamingImpl(); + _internalContext = new InternalContext(); } /** @@ -188,16 +188,33 @@ * @return the JavaNaming to be used */ public JavaNaming getJavaNaming() { - return _javaNaming; + return _internalContext.getJavaNaming(); } /** * To set the {@link JavaNaming} instance to be used. * @param javaNaming the JavaNaming to be used + * TODO: joachim remove me if possible! */ - public void setJavaNaming(final JavaNaming javaNaming) { - _javaNaming = javaNaming; + private void setJavaNaming(final JavaNaming javaNaming) { + _internalContext.setJavaNaming(javaNaming); } + + /** + * To get the {@link InternalContext} to use. + * @return the {@link InternalContext} to use + */ + public InternalContext getInternalContext() { + return _internalContext; + } + + /** + * To set the {@link InternalContext} to use. + * @param internalContext the {@link InternalContext} to use + */ + public void setInternalContext(final InternalContext internalContext) { + _internalContext = internalContext; + } /** * Returns true if the given Class is a considered a @@ -457,7 +474,7 @@ */ protected InheritanceMatch[] searchInheritance(final String name, final String namespace, - final XMLClassDescriptor classDesc, final XMLClassDescriptorResolver cdResolver) + final XMLClassDescriptor classDesc) throws MarshalException { Iterator classDescriptorIterator = null; @@ -480,11 +497,14 @@ className = pkg + className; } } - cdResolver.resolve(className, classDesc.getClass().getClassLoader()); + getInternalContext().getXMLClassDescriptorResolver().resolve( + className, classDesc.getClass().getClassLoader()); //-- end Not-Yet-Loaded descriptor logic //-- resolve all by XML name + namespace URI - classDescriptorIterator = cdResolver.resolveAllByXMLName(name, namespace, null); + classDescriptorIterator = + getInternalContext().getXMLClassDescriptorResolver().resolveAllByXMLName( + name, namespace, null); } catch (ResolverException rx) { Throwable actual = rx.getCause(); Index: src/main/java/org/exolab/castor/xml/schema/SimpleTypesFactory.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/SimpleTypesFactory.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/SimpleTypesFactory.java (working copy) @@ -52,6 +52,8 @@ import java.util.Vector; import java.util.Hashtable; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.castor.util.Messages; import org.exolab.castor.util.LocalConfiguration; import org.exolab.castor.mapping.Mapping; @@ -75,6 +77,10 @@ * @version $Revision$ $Date: 2006-04-25 15:08:23 -0600 (Tue, 25 Apr 2006) $ **/ public class SimpleTypesFactory { + /** + * The Logger instance to use. + */ + private static final Log LOG = LogFactory.getLog(SimpleTypesFactory.class); //Type Codes: @@ -426,10 +432,14 @@ TypeList typeList = (TypeList)unmarshaller.unmarshal( new org.xml.sax.InputSource(is) ); //print what we just read (only in debug mode and if we have a logWriter) - LocalConfiguration config = LocalConfiguration.getInstance(); - if (config.debug() && getLogWriter()!= null) { - typeList.Print(getLogWriter()); + // TODO: Joachim 2007-09-04 remove me + // LocalConfiguration config = LocalConfiguration.getInstance(); + if (LOG.isDebugEnabled()) { + LOG.debug(typeList.toString()); } + //if (config.debug() && getLogWriter()!= null) { + // typeList.Print(getLogWriter()); + //} //Store the types by name in the typesByName and typesByCode hashtables //and create for each its associated SimpleType instance. Index: src/main/java/org/exolab/castor/xml/schema/reader/RedefineUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/RedefineUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/RedefineUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.net.*; import org.exolab.castor.xml.*; import org.exolab.castor.xml.schema.*; @@ -92,16 +93,19 @@ * The XML Schema imported */ - public RedefineUnmarshaller - (Schema schema, AttributeSet atts, Resolver resolver, URIResolver uriResolver, Locator locator, SchemaUnmarshallerState state) - throws XMLException - { - super(); + public RedefineUnmarshaller( + final InternalContext internalContext, + final Schema schema, + final AttributeSet atts, + final URIResolver uriResolver, + final Locator locator, + final SchemaUnmarshallerState state) + throws XMLException { + super(internalContext); if (schema == null) { String err = SchemaNames.REDEFINE + " must be used with an existing parent XML Schema."; throw new SchemaException(err); } - setResolver(resolver); setURIResolver(uriResolver); URILocation uri = null; @@ -177,14 +181,14 @@ //-- Parser Schema Parser parser = null; try { - parser = state.getConfiguration().getParser(); + parser = getInternalContext().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(state); + SchemaUnmarshaller schemaUnmarshaller = new SchemaUnmarshaller(getInternalContext(), state); schemaUnmarshaller.setURIResolver(getURIResolver()); schemaUnmarshaller.setSchema(importedSchema); Sax2ComponentReader handler = new Sax2ComponentReader(schemaUnmarshaller); @@ -270,24 +274,24 @@ //-- if (name.equals(SchemaNames.ANNOTATION)) { - _unmarshaller = new AnnotationUnmarshaller(atts); + _unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } //-- else if (name.equals(SchemaNames.ATTRIBUTE_GROUP)) { - _unmarshaller = new AttributeGroupUnmarshaller(_schema, atts); + _unmarshaller = new AttributeGroupUnmarshaller(getInternalContext(), _schema, atts); } //-- else if (name.equals(SchemaNames.COMPLEX_TYPE)) { _unmarshaller - = new ComplexTypeUnmarshaller(_schema, atts, getResolver()); + = new ComplexTypeUnmarshaller(getInternalContext(), _schema, atts); } //-- else if (name.equals(SchemaNames.SIMPLE_TYPE)) { - _unmarshaller = new SimpleTypeUnmarshaller(_schema, atts); + _unmarshaller = new SimpleTypeUnmarshaller(getInternalContext(), _schema, atts); } //-- else if (name.equals(SchemaNames.GROUP)) { - _unmarshaller = new ModelGroupUnmarshaller(_schema, atts, getResolver()); + _unmarshaller = new ModelGroupUnmarshaller(getInternalContext(), _schema, atts); } else { //--Exception here Index: src/main/java/org/exolab/castor/xml/schema/reader/ElementUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/ElementUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/ElementUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -107,17 +108,17 @@ //----------------/ /** - * Creates a new ElementUnmarshaller + * Creates a new ElementUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param schema the Schema to which the Element belongs * @param atts the AttributeList - * @param resolver the resolver being used for reference resolving **/ - public ElementUnmarshaller - (final Schema schema, final AttributeSet atts, final Resolver resolver) - throws XMLException - { - super(); - setResolver(resolver); + public ElementUnmarshaller( + final InternalContext internalContext, + final Schema schema, + final AttributeSet atts) + throws XMLException { + super(internalContext); this._schema = schema; @@ -237,7 +238,7 @@ } else if (minOccurs > 1) _element.setMaxOccurs(minOccurs); - charUnmarshaller = new CharacterUnmarshaller(); + charUnmarshaller = new CharacterUnmarshaller(getInternalContext()); } //-- ElementUnmarshaller //-----------/ @@ -305,7 +306,7 @@ "element definitions."); foundAnnotation = true; - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else if (SchemaNames.COMPLEX_TYPE.equals(name)) { @@ -326,7 +327,7 @@ foundComplexType = true; unmarshaller - = new ComplexTypeUnmarshaller(_schema, atts, getResolver()); + = new ComplexTypeUnmarshaller(getInternalContext(), _schema, atts); } else if (SchemaNames.SIMPLE_TYPE.equals(name)) { @@ -345,20 +346,17 @@ "'keyref' and 'unique' elements."); foundSimpleType = true; - unmarshaller = new SimpleTypeUnmarshaller(_schema, atts); + unmarshaller = new SimpleTypeUnmarshaller(getInternalContext(), _schema, atts); } else if (SchemaNames.KEY.equals(name) || SchemaNames.KEYREF.equals(name) || SchemaNames.UNIQUE.equals(name)) { foundIdentityConstraint = true; - unmarshaller = new IdentityConstraintUnmarshaller(name, atts); + unmarshaller = new IdentityConstraintUnmarshaller(getInternalContext(), name, atts); } else illegalElement(name); - unmarshaller.setResolver(getResolver()); - unmarshaller.setDocumentLocator(getDocumentLocator()); - } //-- startElement /** Index: src/main/java/org/exolab/castor/xml/schema/reader/WildcardUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/WildcardUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/WildcardUnmarshaller.java (working copy) @@ -45,6 +45,7 @@ package org.exolab.castor.xml.schema.reader; +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -106,42 +107,49 @@ //----------------/ //- Constructors -/ //----------------/ - public WildcardUnmarshaller - (ComplexType complexType, Schema schema, String element, AttributeSet atts, Resolver resolver) - { - super(); - _wildcard = new Wildcard(complexType); - init(schema, element, atts, resolver); + public WildcardUnmarshaller( + final InternalContext internalContext, + final ComplexType complexType, + final Schema schema, + final String element, + final AttributeSet atts) { + this(internalContext, schema, element, atts, new Wildcard(complexType)); } - public WildcardUnmarshaller - (Group group, Schema schema, String element, AttributeSet atts, Resolver resolver) - { - super(); - _wildcard = new Wildcard(group); - init(schema, element, atts, resolver); + public WildcardUnmarshaller( + final InternalContext internalContext, + final Group group, + final Schema schema, + final String element, + final AttributeSet atts) { + this(internalContext, schema, element, atts, new Wildcard(group)); } - public WildcardUnmarshaller - (AttributeGroup attGroup, Schema schema, String element, AttributeSet atts, Resolver resolver) - { - super(); - _wildcard = new Wildcard(attGroup); - init(schema, element, atts, resolver); + public WildcardUnmarshaller( + final InternalContext internalContext, + final AttributeGroup attGroup, + final Schema schema, + final String element, + final AttributeSet atts) { + this(internalContext, schema, element, atts, new Wildcard(attGroup)); } /** - * Creates a new WildcardUnmarshaller + * Creates a new WildcardUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param schema the Schema to which the Wildcard belongs * @param element the name of the element * @param atts the AttributeList - * @param resolver the resolver being used for reference resolving **/ - public void init - (Schema schema, String element, AttributeSet atts, Resolver resolver) - { - setResolver(resolver); + private WildcardUnmarshaller( + final InternalContext internalContext, + final Schema schema, + final String element, + final AttributeSet atts, + final Wildcard wildcard) { + super(internalContext); + _wildcard = wildcard; this._schema = schema; this._element = element; @@ -278,7 +286,7 @@ } //-- if (SchemaNames.ANNOTATION.equals(name)) { - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else { Index: src/main/java/org/exolab/castor/xml/schema/reader/AppInfoUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/AppInfoUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/AppInfoUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -84,13 +85,15 @@ //----------------/ /** - * Creates a new AppInfoUnmarshaller + * Creates a new AppInfoUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param atts the AttributeList **/ - public AppInfoUnmarshaller(AttributeSet atts) - throws XMLException - { - super(); + public AppInfoUnmarshaller( + final InternalContext internalContext, + final AttributeSet atts) + throws XMLException { + super(internalContext); _appInfo = new AppInfo(); _appInfo.setSource(atts.getValue(SchemaNames.SOURCE_ATTR)); Index: src/main/java/org/exolab/castor/xml/schema/reader/CharacterUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/CharacterUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/CharacterUnmarshaller.java (working copy) @@ -45,6 +45,7 @@ package org.exolab.castor.xml.schema.reader; +import org.castor.xml.InternalContext; import org.exolab.castor.xml.XMLException; /** @@ -58,11 +59,13 @@ private StringBuffer sb = null; private String currentName = null; + /** - * Creates a new StringUnmarshaller + * Creates a new StringUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from **/ - public CharacterUnmarshaller() { - super(); + public CharacterUnmarshaller(final InternalContext internalContext) { + super(internalContext); sb = new StringBuffer(); } //-- CharacterUnmarshaller Index: src/main/java/org/exolab/castor/xml/schema/reader/SchemaUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/SchemaUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/SchemaUnmarshaller.java (working copy) @@ -46,18 +46,32 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages -import org.exolab.castor.xml.*; -import org.exolab.castor.xml.util.AttributeSetImpl; -import org.exolab.castor.xml.schema.*; -import org.exolab.castor.net.URIResolver; -import org.exolab.castor.net.util.URIResolverImpl; - +import java.io.InputStream; import java.util.Enumeration; import java.util.HashMap; import java.util.Properties; import java.util.StringTokenizer; -import java.io.InputStream; +import org.castor.xml.InternalContext; +import org.exolab.castor.net.URIResolver; +import org.exolab.castor.net.util.URIResolverImpl; +import org.exolab.castor.xml.AttributeSet; +import org.exolab.castor.xml.Namespaces; +import org.exolab.castor.xml.XMLException; +import org.exolab.castor.xml.schema.Annotation; +import org.exolab.castor.xml.schema.AttributeDecl; +import org.exolab.castor.xml.schema.AttributeGroupDecl; +import org.exolab.castor.xml.schema.ComplexType; +import org.exolab.castor.xml.schema.ElementDecl; +import org.exolab.castor.xml.schema.Form; +import org.exolab.castor.xml.schema.ModelGroup; +import org.exolab.castor.xml.schema.RedefineSchema; +import org.exolab.castor.xml.schema.Schema; +import org.exolab.castor.xml.schema.SchemaException; +import org.exolab.castor.xml.schema.SchemaNames; +import org.exolab.castor.xml.schema.ScopableResolver; +import org.exolab.castor.xml.schema.SimpleType; +import org.exolab.castor.xml.util.AttributeSetImpl; /** * @author Keith Visco @@ -101,11 +115,6 @@ boolean skipAll = false; - /** - * The ID Resolver - **/ - Resolver _resolver = null; - Schema _schema = null; private boolean foundSchemaDef = false; @@ -125,49 +134,69 @@ //- Constructors -/ //----------------/ - public SchemaUnmarshaller() - throws XMLException - { - this(null, null, null); + public SchemaUnmarshaller(final InternalContext internalContext) + throws XMLException { + this(internalContext, null, null); foundSchemaDef = false; } //-- SchemaUnmarshaller - public SchemaUnmarshaller(SchemaUnmarshallerState state) - throws XMLException - { - this(null, null, null); + public SchemaUnmarshaller( + final InternalContext internalContext, + final SchemaUnmarshallerState state) + throws XMLException { + this(internalContext, null, null); _state = state; foundSchemaDef = false; } //-- SchemaUnmarshaller - public SchemaUnmarshaller(boolean include, SchemaUnmarshallerState state, URIResolver uriResolver) - throws XMLException - { - this(null, null, uriResolver); + /** + * Called from IncludeUnmarshaller. + * @param internalContext + * @param include + * @param state + * @param uriResolver + * @throws XMLException + */ + public SchemaUnmarshaller( + final InternalContext internalContext, + final boolean include, + final SchemaUnmarshallerState state, + final URIResolver uriResolver) + throws XMLException { + + this(internalContext, null, uriResolver); _state = state; _include = include; foundSchemaDef = false; } //--backward compatibility - public SchemaUnmarshaller(AttributeSet atts, Resolver resolver) - throws XMLException - { - this(atts, resolver, null); + public SchemaUnmarshaller( + final InternalContext internalContext, + final AttributeSet atts) + throws XMLException { + this(internalContext, atts, null); } - public SchemaUnmarshaller(AttributeSet atts, Resolver resolver, URIResolver uriResolver) - throws XMLException - { - super(); + private SchemaUnmarshaller( + final InternalContext internalContext, + final AttributeSet atts, + final URIResolver uriResolver) + throws XMLException { + super(internalContext); + _schema = new Schema(); //--initialize the schema to ensure that the default namespace //--is not set _schema.removeNamespace(""); - setResolver(resolver); - if (uriResolver == null) - uriResolver = new URIResolverImpl(); - setURIResolver(uriResolver); + if (getResolver() == null) { + setResolver(new ScopableResolver()); + } + if (uriResolver == null) { + setURIResolver(new URIResolverImpl()); + } else { + setURIResolver(uriResolver); + } foundSchemaDef = true; _state = new SchemaUnmarshallerState(); init(atts); @@ -383,15 +412,7 @@ } } //-- handleRemapping - - public void setResolver(Resolver resolver) { - if (resolver == null) resolver = new ScopableResolver(); - super.setResolver(resolver); - _resolver = resolver; - } //-- setResolver - - /** * Signals the start of an element with the given name. * @@ -481,48 +502,48 @@ //-- if (name.equals(SchemaNames.ANNOTATION)) { - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } //-- else if (name.equals(SchemaNames.ATTRIBUTE)) { - unmarshaller = new AttributeUnmarshaller(_schema,atts, getResolver()); + unmarshaller = new AttributeUnmarshaller(getInternalContext(), _schema,atts); } //-- else if (name.equals(SchemaNames.ATTRIBUTE_GROUP)) { - unmarshaller = new AttributeGroupUnmarshaller(_schema, atts); + unmarshaller = new AttributeGroupUnmarshaller(getInternalContext(), _schema, atts); } //-- else if (name.equals(SchemaNames.COMPLEX_TYPE)) { unmarshaller - = new ComplexTypeUnmarshaller(_schema, atts, _resolver); + = new ComplexTypeUnmarshaller(getInternalContext(), _schema, atts); } //-- else if (name.equals(SchemaNames.ELEMENT)) { unmarshaller - = new ElementUnmarshaller(_schema, atts, _resolver); + = new ElementUnmarshaller(getInternalContext(), _schema, atts); } //-- else if (name.equals(SchemaNames.SIMPLE_TYPE)) { - unmarshaller = new SimpleTypeUnmarshaller(_schema, atts); + unmarshaller = new SimpleTypeUnmarshaller(getInternalContext(), _schema, atts); } //-- else if (name.equals(SchemaNames.GROUP)) { - unmarshaller = new ModelGroupUnmarshaller(_schema, atts, _resolver); + unmarshaller = new ModelGroupUnmarshaller(getInternalContext(), _schema, atts); } //-- else if (name.equals(SchemaNames.INCLUDE)) { unmarshaller - = new IncludeUnmarshaller(_schema, atts, _resolver, getURIResolver(),getDocumentLocator(), _state); + = new IncludeUnmarshaller(getInternalContext(), _schema, atts, getURIResolver(),getDocumentLocator(), _state); } //-- else if (name.equals(SchemaNames.IMPORT)) { unmarshaller - = new ImportUnmarshaller(_schema, atts, _resolver, getURIResolver(), getDocumentLocator(), _state); + = new ImportUnmarshaller(getInternalContext(), _schema, atts, getURIResolver(), getDocumentLocator(), _state); } //-- else if (name.equals(SchemaNames.REDEFINE)) { unmarshaller - = new RedefineUnmarshaller(_schema, atts, _resolver, getURIResolver(), getDocumentLocator(), _state); + = new RedefineUnmarshaller(getInternalContext(), _schema, atts, getURIResolver(), getDocumentLocator(), _state); } else { //-- we should throw a new Exception here @@ -532,10 +553,10 @@ System.out.print(name); System.out.print("> elements are either currently unsupported "); System.out.println("or non-valid schema elements."); - unmarshaller = new UnknownUnmarshaller(name); + unmarshaller = new UnknownUnmarshaller(getInternalContext(), name); } - unmarshaller.setDocumentLocator(getDocumentLocator()); +// unmarshaller.setDocumentLocator(getDocumentLocator()); } //-- startElement @@ -626,7 +647,7 @@ complexType = ((ComplexTypeUnmarshaller)unmarshaller).getComplexType(); _schema.addComplexType(complexType); if (complexType.getName() != null) { - _resolver.addResolvable(complexType.getReferenceId(), complexType); + getResolver().addResolvable(complexType.getReferenceId(), complexType); } else { System.out.println("warning: top-level complexType with no name."); @@ -637,7 +658,7 @@ SimpleType simpleType = null; simpleType = ((SimpleTypeUnmarshaller)unmarshaller).getSimpleType(); _schema.addSimpleType(simpleType); - _resolver.addResolvable(simpleType.getReferenceId(), simpleType); + getResolver().addResolvable(simpleType.getReferenceId(), simpleType); } //-- else if (name.equals(SchemaNames.ELEMENT)) { Index: src/main/java/org/exolab/castor/xml/schema/reader/SchemaUnmarshallerState.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/SchemaUnmarshallerState.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/SchemaUnmarshallerState.java (working copy) @@ -59,9 +59,6 @@ * @version $Revision$ $Date: 2004-09-21 08:09:24 -0600 (Tue, 21 Sep 2004) $ */ class SchemaUnmarshallerState { - - - private Configuration _config = null; private Hashtable _processed = null; @@ -117,12 +114,12 @@ * * @see #setConfiguration */ - Configuration getConfiguration() { - if (_config == null) { - _config = LocalConfiguration.getInstance(); - } - return _config; - } //-- setConfiguraiton +// Configuration getConfiguration() { +// if (_config == null) { +// _config = LocalConfiguration.getInstance(); +// } +// return _config; +// } //-- setConfiguraiton /** * Returns the schema corresponding to the given schemaLocation @@ -140,8 +137,8 @@ * * @param config the Configuration to set */ - void setConfiguration(Configuration config) { - _config = config; - } //-- setConfiguraiton +// void setConfiguration(Configuration config) { +// _config = config; +// } //-- setConfiguraiton } //-- SchemaUnmarshallerState Index: src/main/java/org/exolab/castor/xml/schema/reader/ComplexContentUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/ComplexContentUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/ComplexContentUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -90,27 +91,31 @@ //----------------/ /** - * Creates a new ComplexContentUnmarshaller + * Creates a new ComplexContentUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param complexType the complexType we are unmarshalling * @param atts the AttributeList - * @param resolver the resolver being used for reference resolving **/ - public ComplexContentUnmarshaller - (ComplexType complexType, AttributeSet atts, Resolver resolver) - throws XMLException - { + public ComplexContentUnmarshaller( + final InternalContext internalContext, + final ComplexType complexType, + final AttributeSet atts) + throws XMLException { + super(internalContext); _complexType = complexType; - //-- read contentType + //-- read contentType String content = atts.getValue(SchemaNames.MIXED); - if (content != null) { - if (content.equals("true")) - _complexType.setContentType(ContentType.valueOf("mixed")); - if (content.equals("false")) - _complexType.setContentType(ContentType.valueOf("elementOnly")); - } + if (content != null) { + if (content.equals("true")) { + _complexType.setContentType(ContentType.valueOf("mixed")); + } + if (content.equals("false")) { + _complexType.setContentType(ContentType.valueOf("elementOnly")); + } + } } //-- ComplexContentUnmarshaller @@ -175,7 +180,7 @@ foundExtension = true; ExtensionUnmarshaller extension = - new ExtensionUnmarshaller(_complexType, atts, getResolver()); + new ExtensionUnmarshaller(getInternalContext(), _complexType, atts); unmarshaller = extension; } //-- restriction @@ -192,7 +197,7 @@ foundRestriction = true; unmarshaller= - new ComplexContentRestrictionUnmarshaller(_complexType, atts, getResolver()); + new ComplexContentRestrictionUnmarshaller(getInternalContext(), _complexType, atts); } //-- annotation else if (name.equals(SchemaNames.ANNOTATION)) { @@ -205,11 +210,10 @@ "of a 'complexContent' element."); foundAnnotation = true; - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else illegalElement(name); - unmarshaller.setDocumentLocator(getDocumentLocator()); } //-- startElement /** Index: src/main/java/org/exolab/castor/xml/schema/reader/AttributeUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/AttributeUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/AttributeUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -95,15 +96,14 @@ //- Constructors -/ //----------------/ - public AttributeUnmarshaller - (Schema schema, AttributeSet atts, Resolver resolver) + public AttributeUnmarshaller( + final InternalContext internalContext, + final Schema schema, + final AttributeSet atts) { - super(); + super(internalContext); this._schema = schema; - setResolver(resolver); - - _attribute = new AttributeDecl(schema); //--@ref @@ -232,7 +232,7 @@ "an attribute declaration."); foundAnnotation = true; - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else if (SchemaNames.SIMPLE_TYPE.equals(name)) { if (foundSimpleType) @@ -240,7 +240,7 @@ "an attribute declaration."); foundSimpleType = true; - unmarshaller = new SimpleTypeUnmarshaller(_schema, atts); + unmarshaller = new SimpleTypeUnmarshaller(getInternalContext(), _schema, atts); } else { illegalElement(name); Index: src/main/java/org/exolab/castor/xml/schema/reader/ComplexTypeUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/ComplexTypeUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/ComplexTypeUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -108,22 +109,23 @@ //----------------/ /** - * Creates a new ComplexTypeUnmarshaller + * Creates a new ComplexTypeUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param schema the Schema to which the ComplexType belongs * @param atts the AttributeList - * @param resolver the resolver being used for reference resolving **/ - public ComplexTypeUnmarshaller - (Schema schema, AttributeSet atts, Resolver resolver) - throws XMLException - { - super(); - setResolver(resolver); + public ComplexTypeUnmarshaller( + final InternalContext internalContext, + final Schema schema, + final AttributeSet atts) + throws XMLException { + super(internalContext); + this._schema = schema; _complexType = schema.createComplexType(); - _complexType.useResolver(resolver); + _complexType.useResolver(getResolver()); //-- handle attributes String attValue = null; @@ -250,7 +252,7 @@ foundAnyAttribute = true; allowAnnotation = true; unmarshaller - = new WildcardUnmarshaller(_complexType, _schema, name, atts, getResolver()); + = new WildcardUnmarshaller(getInternalContext(), _complexType, _schema, name, atts); } //-- attribute declarations @@ -267,7 +269,7 @@ foundAttributes = true; allowAnnotation = false; unmarshaller - = new AttributeUnmarshaller(_schema, atts, getResolver()); + = new AttributeUnmarshaller(getInternalContext(), _schema, atts); } //-- attribute group declarations else if (SchemaNames.ATTRIBUTE_GROUP.equals(name)) { @@ -291,7 +293,7 @@ foundAttributes = true; allowAnnotation = false; unmarshaller - = new AttributeGroupUnmarshaller(_schema, atts); + = new AttributeGroupUnmarshaller(getInternalContext(), _schema, atts); } //-- simpleContent else if (SchemaNames.SIMPLE_CONTENT.equals(name)) { @@ -314,7 +316,7 @@ allowAnnotation = false; _complexType.setSimpleContent(true); unmarshaller - = new SimpleContentUnmarshaller(_complexType, atts, getResolver()); + = new SimpleContentUnmarshaller(getInternalContext(), _complexType, atts); } //-- complexContent else if (SchemaNames.COMPLEX_CONTENT.equals(name)) { @@ -338,7 +340,7 @@ _complexType.setComplexContent(true); unmarshaller - = new ComplexContentUnmarshaller(_complexType, atts, getResolver()); + = new ComplexContentUnmarshaller(getInternalContext(), _complexType, atts); } //-- else if ( name.equals(SchemaNames.GROUP) ) @@ -360,7 +362,7 @@ foundModelGroup = true; allowAnnotation = false; unmarshaller - = new ModelGroupUnmarshaller(_schema, atts, getResolver()); + = new ModelGroupUnmarshaller(getInternalContext(), _schema, atts); } //-- ModelGroup declarations (choice, all, sequence) else if ( (SchemaNames.isGroupName(name)) && (name != SchemaNames.GROUP) ) @@ -383,11 +385,11 @@ foundModelGroup = true; allowAnnotation = false; unmarshaller - = new GroupUnmarshaller(_schema, name, atts, getResolver()); + = new GroupUnmarshaller(getInternalContext(), _schema, name, atts); } else if (name.equals(SchemaNames.ANNOTATION)) { if (allowAnnotation) { - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); allowAnnotation = false; foundAnnotation = true; } @@ -402,7 +404,6 @@ } else illegalElement(name); - unmarshaller.setDocumentLocator(getDocumentLocator()); } //-- startElement /** Index: src/main/java/org/exolab/castor/xml/schema/reader/ImportUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/ImportUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/ImportUnmarshaller.java (working copy) @@ -46,21 +46,32 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages -import org.exolab.castor.net.*; -import org.exolab.castor.xml.*; -import org.exolab.castor.xml.schema.*; -import org.xml.sax.*; +import org.castor.xml.InternalContext; +import org.exolab.castor.net.URIException; +import org.exolab.castor.net.URILocation; +import org.exolab.castor.net.URIResolver; +import org.exolab.castor.xml.AttributeSet; +import org.exolab.castor.xml.XMLException; +import org.exolab.castor.xml.schema.Schema; +import org.exolab.castor.xml.schema.SchemaException; +import org.exolab.castor.xml.schema.SchemaNames; +import org.xml.sax.InputSource; +import org.xml.sax.Locator; +import org.xml.sax.Parser; public class ImportUnmarshaller extends ComponentReader { - public ImportUnmarshaller - (Schema schema, AttributeSet atts, Resolver resolver, URIResolver uriResolver, Locator locator, SchemaUnmarshallerState state) - throws XMLException - { - super(); - setResolver(resolver); + public ImportUnmarshaller( + final InternalContext internalContext, + final Schema schema, + final AttributeSet atts, + final URIResolver uriResolver, + final Locator locator, + final SchemaUnmarshallerState state) + throws XMLException { + super(internalContext); setURIResolver(uriResolver); URILocation uri = null; @@ -177,14 +188,14 @@ //-- Parser Schema Parser parser = null; try { - parser = state.getConfiguration().getParser(); + parser = getInternalContext().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(state); + SchemaUnmarshaller schemaUnmarshaller = new SchemaUnmarshaller(getInternalContext(), state); schemaUnmarshaller.setURIResolver(getURIResolver()); schemaUnmarshaller.setSchema(importedSchema); Sax2ComponentReader handler = new Sax2ComponentReader(schemaUnmarshaller); Index: src/main/java/org/exolab/castor/xml/schema/reader/AnnotationUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/AnnotationUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/AnnotationUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -86,13 +87,14 @@ //----------------/ /** - * Creates a new AnnotationUnmarshaller + * Creates a new AnnotationUnmarshaller. + * @param internalContext the XMLContext to get some configuration settings from * @param atts the AttributeList **/ - public AnnotationUnmarshaller (AttributeSet atts) + public AnnotationUnmarshaller (final InternalContext internalContext, final AttributeSet atts) throws XMLException { - super(); + super(internalContext); _annotation = new Annotation(); @@ -156,10 +158,10 @@ } if (SchemaNames.APPINFO.equals(name)) { - unmarshaller = new AppInfoUnmarshaller(atts); + unmarshaller = new AppInfoUnmarshaller(getInternalContext(), atts); } else if (SchemaNames.DOCUMENTATION.equals(name)) { - unmarshaller = new DocumentationUnmarshaller(atts); + unmarshaller = new DocumentationUnmarshaller(getInternalContext(), atts); } else illegalElement(name); Index: src/main/java/org/exolab/castor/xml/schema/reader/ExtensionUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/ExtensionUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/ExtensionUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -102,19 +103,18 @@ //----------------/ /** - * Creates a new ExtensionUnmarshaller + * Creates a new ExtensionUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param complexType the ComplexType being unmarshalled * @param atts the AttributeList - * @param resolver the resolver being used for reference resolving **/ - public ExtensionUnmarshaller - (ComplexType complexType, AttributeSet atts, Resolver resolver) - throws XMLException - { - super(); + public ExtensionUnmarshaller ( + final InternalContext internalContext, + final ComplexType complexType, + final AttributeSet atts) + throws XMLException { + super(internalContext); - setResolver(resolver); - _complexType = complexType; _schema = complexType.getSchema(); @@ -209,14 +209,14 @@ //-- if (SchemaNames.ANY_ATTRIBUTE.equals(name)) { unmarshaller - = new WildcardUnmarshaller(_complexType, _schema, name, atts, getResolver()); + = new WildcardUnmarshaller(getInternalContext(), _complexType, _schema, name, atts); } //-- attribute declarations else if (SchemaNames.ATTRIBUTE.equals(name)) { foundAttributes = true; unmarshaller - = new AttributeUnmarshaller(_schema, atts, getResolver()); + = new AttributeUnmarshaller(getInternalContext(), _schema, atts); } //-- attribute group declarations else if (SchemaNames.ATTRIBUTE_GROUP.equals(name)) { @@ -232,7 +232,7 @@ foundAttributes = true; unmarshaller - = new AttributeGroupUnmarshaller(_schema, atts); + = new AttributeGroupUnmarshaller(getInternalContext(), _schema, atts); } //-- else if ( name.equals(SchemaNames.GROUP) ) @@ -247,7 +247,7 @@ foundModelGroup = true; unmarshaller - = new ModelGroupUnmarshaller(_schema, atts, getResolver()); + = new ModelGroupUnmarshaller(getInternalContext(), _schema, atts); } else if (SchemaNames.isGroupName(name) && (name != SchemaNames.GROUP) ) { if (foundAttributes) @@ -265,7 +265,7 @@ foundModelGroup = true; unmarshaller - = new GroupUnmarshaller(_schema, name, atts, getResolver()); + = new GroupUnmarshaller(getInternalContext(), _schema, name, atts); } //-- element declarations else if (SchemaNames.ANY_ATTRIBUTE.equals(name)) { @@ -282,11 +282,10 @@ "an 'extension' element."); foundAnnotation = true; - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else illegalElement(name); - unmarshaller.setDocumentLocator(getDocumentLocator()); } //-- startElement /** Index: src/main/java/org/exolab/castor/xml/schema/reader/ModelGroupUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/ModelGroupUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/ModelGroupUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -106,16 +107,17 @@ //----------------/ /** - * Creates a new ModelGroupUnmarshaller + * Creates a new ModelGroupUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param schema the Schema to which the ModelGroup belongs * @param atts the AttributeList - * @param resolver the resolver being used for reference resolving **/ - public ModelGroupUnmarshaller - (Schema schema, AttributeSet atts, Resolver resolver) - { - super(); - setResolver(resolver); + public ModelGroupUnmarshaller( + final InternalContext internalContext, + final Schema schema, + final AttributeSet atts) { + super(internalContext); + this._schema = schema; _group = new ModelGroup(_schema); @@ -248,12 +250,12 @@ "element definitions."); foundAnnotation = true; - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else if (SchemaNames.isGroupName(name)) { unmarshaller - = new GroupUnmarshaller(_schema, name, atts, getResolver()); + = new GroupUnmarshaller(getInternalContext(), _schema, name, atts); } else { StringBuffer err = new StringBuffer("illegal element <"); Index: src/main/java/org/exolab/castor/xml/schema/reader/AttributeGroupUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/AttributeGroupUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/AttributeGroupUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -97,14 +98,17 @@ //----------------/ /** - * Creates a new AttributeGroupUnmarshaller + * Creates a new AttributeGroupUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param schema the Schema to which the AttributeGroup belongs * @param atts the AttributeList **/ - public AttributeGroupUnmarshaller(Schema schema, AttributeSet atts) - throws XMLException - { - super(); + public AttributeGroupUnmarshaller( + final InternalContext internalContext, + final Schema schema, + final AttributeSet atts) + throws XMLException { + super(internalContext); this._schema = schema; @@ -199,7 +203,7 @@ foundAnyAttribute = true; allowAnnotation = true; unmarshaller - = new WildcardUnmarshaller(_attributeGroup, _schema, name, atts, getResolver()); + = new WildcardUnmarshaller(getInternalContext(), _attributeGroup, _schema, name, atts); } //-- attribute declarations else if (SchemaNames.ATTRIBUTE.equals(name)) { @@ -209,7 +213,7 @@ error("AttributeGroup references may not have children."); unmarshaller - = new AttributeUnmarshaller(_schema, atts, getResolver()); + = new AttributeUnmarshaller(getInternalContext(), _schema, atts); } //-- element declarations else if (SchemaNames.ATTRIBUTE_GROUP.equals(name)) { @@ -217,15 +221,14 @@ if (isRef) error("AttributeGroup references may not have children."); unmarshaller - = new AttributeGroupUnmarshaller(_schema, atts); + = new AttributeGroupUnmarshaller(getInternalContext(), _schema, atts); } else if (name.equals(SchemaNames.ANNOTATION)) { if (!allowAnnotation) outOfOrder(name); - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else illegalElement(name); - unmarshaller.setDocumentLocator(getDocumentLocator()); } //-- startElement /** Index: src/main/java/org/exolab/castor/xml/schema/reader/SimpleTypeRestrictionUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/SimpleTypeRestrictionUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/SimpleTypeRestrictionUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -100,14 +101,16 @@ /** * Creates a new RestrictionUnmarshaller + * @param internalContext the internalContext to get some configuration settings from * @param typeDefinition the SimpleType being unmarshalled * @param atts the AttributeList **/ - public SimpleTypeRestrictionUnmarshaller - (SimpleTypeDefinition typeDefinition, AttributeSet atts) - throws XMLException - { - super(); + public SimpleTypeRestrictionUnmarshaller( + final InternalContext internalContext, + final SimpleTypeDefinition typeDefinition, + final AttributeSet atts) + throws XMLException { + super(internalContext); _typeDefinition = typeDefinition; _schema = typeDefinition.getSchema(); @@ -189,7 +192,7 @@ "'restriction' elements."); foundAnnotation = true; - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else if (SchemaNames.SIMPLE_TYPE.equals(name)) { if (foundSimpleType) @@ -201,12 +204,12 @@ "elements, must appear before any facets."); foundSimpleType = true; - unmarshaller = new SimpleTypeUnmarshaller(_schema, atts); + unmarshaller = new SimpleTypeUnmarshaller(getInternalContext(), _schema, atts); } else if (FacetUnmarshaller.isFacet(name)) { foundFacets = true; - unmarshaller = new FacetUnmarshaller(name, atts); + unmarshaller = new FacetUnmarshaller(getInternalContext(), name, atts); } else illegalElement(name); Index: src/main/java/org/exolab/castor/xml/schema/reader/FacetUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/FacetUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/FacetUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -91,12 +92,17 @@ //----------------/ /** - * Creates a new FacetUnmarshaller + * Creates a new FacetUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param name the name of the Facet * @param atts the AttributeList **/ - public FacetUnmarshaller (String name, AttributeSet atts) throws XMLException { - super(); + public FacetUnmarshaller ( + final InternalContext internalContext, + final String name, + final AttributeSet atts) + throws XMLException { + super(internalContext); _elementName = name; @@ -163,7 +169,7 @@ } if (SchemaNames.ANNOTATION.equals(name)) { - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else illegalElement(name); Index: src/main/java/org/exolab/castor/xml/schema/reader/IncludeUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/IncludeUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/IncludeUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.net.*; import org.exolab.castor.xml.*; import org.exolab.castor.xml.schema.*; @@ -65,13 +66,16 @@ { - public IncludeUnmarshaller - (Schema schema, AttributeSet atts, Resolver resolver, URIResolver uriResolver, - Locator locator, SchemaUnmarshallerState state) - throws XMLException - { - super(); - setResolver(resolver); + public IncludeUnmarshaller( + final InternalContext internalContext, + final Schema schema, + final AttributeSet atts, + final URIResolver uriResolver, + final Locator locator, + final SchemaUnmarshallerState state) + throws XMLException { + super(internalContext); + setURIResolver(uriResolver); URILocation uri = null; //-- Get schemaLocation @@ -137,13 +141,13 @@ return; Parser parser = null; try { - parser = state.getConfiguration().getParser(); + parser = getInternalContext().getParser(); } catch(RuntimeException rte) {} if (parser == null) { throw new SchemaException("Error failed to create parser for include"); } - SchemaUnmarshaller schemaUnmarshaller = new SchemaUnmarshaller(true, state, getURIResolver()); + SchemaUnmarshaller schemaUnmarshaller = new SchemaUnmarshaller(getInternalContext(), true, state, getURIResolver()); if (state.cacheIncludedSchemas) schemaUnmarshaller.setSchema(includedSchema); Index: src/main/java/org/exolab/castor/xml/schema/reader/SimpleContentUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/SimpleContentUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/SimpleContentUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -89,19 +90,20 @@ //----------------/ /** - * Creates a new SimpleContentUnmarshaller + * Creates a new SimpleContentUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param complexType the complexType we are unmarshalling * @param atts the AttributeList - * @param resolver the resolver being used for reference resolving **/ - public SimpleContentUnmarshaller - (ComplexType complexType, AttributeSet atts, Resolver resolver) - throws XMLException - { + public SimpleContentUnmarshaller( + final InternalContext internalContext, + final ComplexType complexType, + final AttributeSet atts) + throws XMLException { + + super(internalContext); _complexType = complexType; - setResolver(resolver); - } //-- SimpleContentUnmarshaller //-----------/ @@ -164,7 +166,7 @@ foundExtension = true; unmarshaller - = new ExtensionUnmarshaller(_complexType, atts, getResolver()); + = new ExtensionUnmarshaller(getInternalContext(), _complexType, atts); } //-- restriction else if (SchemaNames.RESTRICTION.equals(name)) { @@ -181,7 +183,7 @@ foundRestriction = true; unmarshaller = - new SimpleContentRestrictionUnmarshaller(_complexType,atts,getResolver()); + new SimpleContentRestrictionUnmarshaller(getInternalContext(), _complexType, atts); } //-- annotation else if (name.equals(SchemaNames.ANNOTATION)) { @@ -194,7 +196,7 @@ "of a 'simpleContent' element."); foundAnnotation = true; - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else illegalElement(name); Index: src/main/java/org/exolab/castor/xml/schema/reader/FieldOrSelectorUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/FieldOrSelectorUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/FieldOrSelectorUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -92,16 +93,19 @@ //----------------/ /** - * Creates a new FieldOrSelectorUnmarshaller + * Creates a new FieldOrSelectorUnmarshaller. * + * @param internalContext the internalContext to get some configuration settings from * @param elementName the name of the element being unmarshalled. * @param atts the AttributeList. **/ - public FieldOrSelectorUnmarshaller - (String elementName, AttributeSet atts) + public FieldOrSelectorUnmarshaller( + final InternalContext internalContext, + final String elementName, + final AttributeSet atts) throws XMLException { - super(); + super(internalContext); _elementName = elementName; @@ -187,7 +191,7 @@ error("Only one (1) annotation may appear as a child of '" + _elementName + "'."); _foundAnnotation = true; - _unmarshaller = new AnnotationUnmarshaller(atts); + _unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else illegalElement(name); Index: src/main/java/org/exolab/castor/xml/schema/reader/SimpleTypeListUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/SimpleTypeListUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/SimpleTypeListUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -93,13 +94,16 @@ //----------------/ /** - * Creates a new ListUnmarshaller + * Creates a new ListUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param atts the AttributeList **/ - SimpleTypeListUnmarshaller(Schema schema, AttributeSet atts) - throws XMLException - { - super(); + SimpleTypeListUnmarshaller( + final InternalContext internalContext, + final Schema schema, + final AttributeSet atts) + throws XMLException { + super(internalContext); _schema = schema; _list = new ListType(schema); @@ -204,7 +208,7 @@ "'list' elements."); foundAnnotation = true; - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else if (SchemaNames.SIMPLE_TYPE.equals(name)) { if (foundItemType) @@ -216,7 +220,7 @@ "'list' elements."); foundSimpleType = true; - unmarshaller = new SimpleTypeUnmarshaller(_schema, atts); + unmarshaller = new SimpleTypeUnmarshaller(getInternalContext(), _schema, atts); } else illegalElement(name); Index: src/main/java/org/exolab/castor/xml/schema/reader/ComplexContentRestrictionUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/ComplexContentRestrictionUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/ComplexContentRestrictionUnmarshaller.java (working copy) @@ -45,6 +45,7 @@ package org.exolab.castor.xml.schema.reader; +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -100,17 +101,18 @@ //- Constructors -/ //----------------/ /** - * Creates a new RestrictionUnmarshaller + * Creates a new RestrictionUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param complexType the complexType being unmarshalled * @param atts the AttributeList */ - public ComplexContentRestrictionUnmarshaller - (ComplexType complexType, AttributeSet atts, Resolver resolver) - throws XMLException - { - super(); - setResolver(resolver); - _complexType = complexType; + public ComplexContentRestrictionUnmarshaller( + final InternalContext internalContext, + final ComplexType complexType, + final AttributeSet atts) + throws XMLException { + super(internalContext); + _complexType = complexType; _schema = complexType.getSchema(); _complexType.setDerivationMethod(SchemaNames.RESTRICTION); @@ -217,7 +219,7 @@ "'restriction' elements."); foundAnnotation = true; - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } //-- ModelGroup declarations (choice, all, sequence, group) @@ -233,12 +235,12 @@ foundModelGroup = true; unmarshaller - = new GroupUnmarshaller(_schema, name, atts, getResolver()); + = new GroupUnmarshaller(getInternalContext(), _schema, name, atts); } else if (SchemaNames.ATTRIBUTE.equals(name)) { foundAttribute = true; - unmarshaller = new AttributeUnmarshaller(_schema,atts, getResolver()); + unmarshaller = new AttributeUnmarshaller(getInternalContext(), _schema,atts); } else if (SchemaNames.ATTRIBUTE_GROUP.equals(name)) { @@ -249,17 +251,16 @@ "attributeGroups, but not defining ones."); } foundAttributeGroup = true; - unmarshaller = new AttributeGroupUnmarshaller(_schema,atts); + unmarshaller = new AttributeGroupUnmarshaller(getInternalContext(), _schema,atts); } //-- else if (SchemaNames.ANY_ATTRIBUTE.equals(name)) { unmarshaller - = new WildcardUnmarshaller(_complexType, _schema, name, atts, getResolver()); + = new WildcardUnmarshaller(getInternalContext(), _complexType, _schema, name, atts); } else illegalElement(name); - unmarshaller.setDocumentLocator(getDocumentLocator()); } //-- startElement /** Index: src/main/java/org/exolab/castor/xml/schema/reader/UnionUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/UnionUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/UnionUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -99,12 +100,15 @@ /** * Creates a new IdentityConstraintUnmarshaller * + * @param internalContext the internalContext to get some configuration settings from * @param atts the AttributeList **/ - public UnionUnmarshaller(Schema schema, AttributeSet atts) - throws XMLException - { - super(); + public UnionUnmarshaller( + final InternalContext internalContext, + final Schema schema, + final AttributeSet atts) + throws XMLException { + super(internalContext); if (schema == null) { String err = "'schema' must not be null."; @@ -184,11 +188,11 @@ elementName() + "'."); _foundAnnotation = true; - _unmarshaller = new AnnotationUnmarshaller(atts); + _unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else if (SchemaNames.SIMPLE_TYPE.equals(name)) { _foundSimpleType = true; - _unmarshaller = new SimpleTypeUnmarshaller(_schema, atts); + _unmarshaller = new SimpleTypeUnmarshaller(getInternalContext(), _schema, atts); } else illegalElement(name); Index: src/main/java/org/exolab/castor/xml/schema/reader/SimpleTypeUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/SimpleTypeUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/SimpleTypeUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -97,15 +98,18 @@ //----------------/ /** - * Creates a new SimpleTypeUnmarshaller + * Creates a new SimpleTypeUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param schema the Schema to which the SimpleType belongs * @param atts the AttributeList **/ - public SimpleTypeUnmarshaller - (Schema schema, AttributeSet atts) + public SimpleTypeUnmarshaller( + final InternalContext internalContext, + final Schema schema, + final AttributeSet atts) throws XMLException { - super(); + super(internalContext); String name = atts.getValue(SchemaNames.NAME_ATTR); @@ -213,7 +217,7 @@ "of 'simpleType'."); foundAnnotation = true; - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else if (SchemaNames.RESTRICTION.equals(name)) { @@ -229,17 +233,17 @@ foundRestriction = true; unmarshaller - = new SimpleTypeRestrictionUnmarshaller(_simpleTypeDef, atts); + = new SimpleTypeRestrictionUnmarshaller(getInternalContext(), _simpleTypeDef, atts); } else if (SchemaNames.LIST.equals(name)) { foundList = true; Schema schema = _simpleTypeDef.getSchema(); - unmarshaller = new SimpleTypeListUnmarshaller(schema, atts); + unmarshaller = new SimpleTypeListUnmarshaller(getInternalContext(), schema, atts); } else if (SchemaNames.UNION.equals(name)) { foundUnion = true; Schema schema = _simpleTypeDef.getSchema(); - unmarshaller = new UnionUnmarshaller(schema, atts); + unmarshaller = new UnionUnmarshaller(getInternalContext(), schema, atts); } else illegalElement(name); Index: src/main/java/org/exolab/castor/xml/schema/reader/GroupUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/GroupUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/GroupUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -116,17 +117,19 @@ //----------------/ /** - * Creates a new GroupUnmarshaller + * Creates a new GroupUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param schema the Schema to which the Group belongs * @param element the element name for this type of group * @param atts the AttributeList - * @param resolver the resolver being used for reference resolving **/ - public GroupUnmarshaller - (Schema schema, String element, AttributeSet atts, Resolver resolver) - { - super(); - setResolver(resolver); + public GroupUnmarshaller( + final InternalContext internalContext, + final Schema schema, + final String element, + final AttributeSet atts) { + super(internalContext); + this._schema = schema; _group = new Group(); @@ -264,19 +267,19 @@ "element definitions."); foundAnnotation = true; - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else if (SchemaNames.ELEMENT.equals(name)) { foundElement = true; unmarshaller - = new ElementUnmarshaller(_schema, atts, getResolver()); + = new ElementUnmarshaller(getInternalContext(), _schema, atts); } //--group else if (name.equals(SchemaNames.GROUP)) { foundModelGroup = true; unmarshaller - = new ModelGroupUnmarshaller(_schema, atts, getResolver()); + = new ModelGroupUnmarshaller(getInternalContext(), _schema, atts); } //--all, sequence, choice @@ -286,14 +289,14 @@ if (SchemaNames.ALL.equals(name)) foundAll = true; unmarshaller - = new GroupUnmarshaller(_schema, name, atts, getResolver()); + = new GroupUnmarshaller(getInternalContext(), _schema, name, atts); } //--any else if (SchemaNames.ANY.equals(name)) { if (foundAll) error(" can not appear as a child of a element"); unmarshaller - = new WildcardUnmarshaller(_group, _schema, name, atts, getResolver()); + = new WildcardUnmarshaller(getInternalContext(), _group, _schema, name, atts); } else { @@ -302,7 +305,6 @@ err.append("> found in ."); throw new SchemaException(err.toString()); } - unmarshaller.setDocumentLocator(getDocumentLocator()); } //-- startElement Index: src/main/java/org/exolab/castor/xml/schema/reader/IdentityConstraintUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/IdentityConstraintUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/IdentityConstraintUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -96,16 +97,18 @@ //----------------/ /** - * Creates a new IdentityConstraintUnmarshaller + * Creates a new IdentityConstraintUnmarshaller. * + * @param internalContext the internalContext to get some configuration settings from * @param elementName the resolver being used for reference resolving * @param atts the AttributeList **/ - public IdentityConstraintUnmarshaller - (String elementName, AttributeSet atts) - throws XMLException - { - super(); + public IdentityConstraintUnmarshaller( + final InternalContext internalContext, + final String elementName, + final AttributeSet atts) + throws XMLException { + super(internalContext); _elementName = elementName; @@ -211,7 +214,7 @@ _elementName + "'."); _foundAnnotation = true; - _unmarshaller = new AnnotationUnmarshaller(atts); + _unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else if (SchemaNames.SELECTOR.equals(name)) { @@ -226,11 +229,11 @@ _foundSelector = true; - _unmarshaller = new FieldOrSelectorUnmarshaller(name, atts); + _unmarshaller = new FieldOrSelectorUnmarshaller(getInternalContext(), name, atts); } else if (SchemaNames.FIELD.equals(name)) { _foundField = true; - _unmarshaller = new FieldOrSelectorUnmarshaller(name, atts); + _unmarshaller = new FieldOrSelectorUnmarshaller(getInternalContext(), name, atts); } else illegalElement(name); Index: src/main/java/org/exolab/castor/xml/schema/reader/UnknownUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/UnknownUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/UnknownUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -71,8 +72,8 @@ //- Constructors -/ //----------------/ - public UnknownUnmarshaller(String name) { - super(); + public UnknownUnmarshaller(final InternalContext internalContext, final String name) { + super(internalContext); this.name = name; } //-- UnknownUnmarshaller Index: src/main/java/org/exolab/castor/xml/schema/reader/SchemaReader.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/SchemaReader.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/SchemaReader.java (working copy) @@ -45,39 +45,41 @@ package org.exolab.castor.xml.schema.reader; +import java.io.IOException; import java.io.Reader; -import java.io.IOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.castor.xml.BackwardCompatibilityContext; +import org.castor.xml.InternalContext; import org.exolab.castor.net.URIException; import org.exolab.castor.net.URILocation; import org.exolab.castor.net.URIResolver; -import org.exolab.castor.util.Configuration; -import org.exolab.castor.util.LocalConfiguration; import org.exolab.castor.util.NestedIOException; - +import org.exolab.castor.xml.XMLException; import org.exolab.castor.xml.schema.Schema; -import org.exolab.castor.xml.XMLException; - +import org.xml.sax.EntityResolver; +import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; -import org.xml.sax.EntityResolver; import org.xml.sax.Parser; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; -import org.xml.sax.ErrorHandler; /** - * A class for reading XML Schemas + * A class for reading XML Schemas. * * @author Keith Visco * @version $Revision$ $Date: 2004-10-05 14:27:10 -0600 (Tue, 05 Oct 2004) $ **/ public class SchemaReader { + /** The Logger to use. */ + private static final Log LOG = LogFactory.getLog(SchemaReader.class); /** - * The Castor Configuration + * The Castor XML Context... mother of all. */ - private Configuration _config = null; + private InternalContext _internalContext; /** * XML Parser instance @@ -119,35 +121,38 @@ /** - * Creates a new SchemaReader + * Old fashion style to create a SchemaReader instance. + * + * @throws IOException + * if no Parser is available */ - private SchemaReader() - throws IOException - { - //-- get default parser from Configuration - - _config = LocalConfiguration.getInstance(); - + private void init() throws IOException { + // -- get default parser from Configuration + _internalContext = new BackwardCompatibilityContext(); + Parser parser = null; - - parser = _config.getParser(); + parser = _internalContext.getParser(); + if (parser == null) { - throw new IOException("fatal error: unable to create SAX parser."); + String message = "fatal error: unable to create SAX parser."; + LOG.warn(message); + throw new IOException(message); } _parser = parser; - } //-- SchemaReader + } // -- SchemaReader /** * Creates a new SchemaReader for the given InputSource - * - * @param source the InputSource to read the Schema from. - **/ + * + * @param source + * the InputSource to read the Schema from. + */ public SchemaReader(InputSource source) throws IOException { - this(); + init(); if (source == null) throw new IllegalArgumentException("InputSource cannot be null"); @@ -165,7 +170,7 @@ public SchemaReader(Reader reader, String filename) throws IOException { - this(); + init(); if (reader == null) { String err = "The argument 'reader' must not be null."; @@ -186,7 +191,7 @@ public SchemaReader(String url) throws IOException { - this(); + init(); if (url == null) { String err = "The argument 'url' must not be null."; throw new IllegalArgumentException(err); @@ -196,6 +201,42 @@ } //-- SchemaReader /** + * New style how to create a SchemaReader instance, requiring that InternalContext + * and InputSource are set before calling {@link read}. + */ + public SchemaReader() { + super(); + } + + /** + * To set the InternalContext to be used. Also resets the parser as it depends + * of the InternalContext. + * @param internalContext the InternalContext to be used + */ + public void setInternalContext(final InternalContext internalContext) { + this._internalContext = internalContext; + + Parser p = _internalContext.getParser(); + if (p != null) { + _parser = p; + } + } + + /** + * A different way to create a SchemaReader by using an empty constructor and + * setting the InputSource afterwards. + * @param inputSource the InputSource to read the schema from + */ + public void setInputSource(final InputSource inputSource) { + if (inputSource == null) { + String message = "InputSource must not be null"; + LOG.warn(message); + throw new IllegalArgumentException(message); + } + _source = inputSource; + } + + /** * Reads the Schema from the source and returns the Schema * object model. * @@ -206,16 +247,27 @@ * * @return the new Schema created from the source of this SchemaReader **/ - public Schema read() throws IOException - { - if (_schema != null) return _schema; + public Schema read() throws IOException { + if (_schema != null) { + return _schema; + } + if (_parser == null) { + String message = "Required Parser was not specified"; + LOG.warn(message); + throw new IllegalStateException(message); + } + if (_source == null) { + String message = "Required Source was not specified"; + LOG.warn(message); + throw new IllegalStateException(message); + } SchemaUnmarshaller schemaUnmarshaller = null; try { SchemaUnmarshallerState state = new SchemaUnmarshallerState(); - state.setConfiguration(_config); +// Joachim state.setConfiguration(_config); state.cacheIncludedSchemas = _cacheIncludedSchemas; - schemaUnmarshaller = new SchemaUnmarshaller(state); + schemaUnmarshaller = new SchemaUnmarshaller(_internalContext, state); if (_uriResolver != null) schemaUnmarshaller.setURIResolver(_uriResolver); @@ -364,5 +416,4 @@ throw new NestedIOException(except); } //-- handleException - } //-- SchemaReader Index: src/main/java/org/exolab/castor/xml/schema/reader/ComponentReader.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/ComponentReader.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/ComponentReader.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.net.URIResolver; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; @@ -62,23 +63,16 @@ **/ public abstract class ComponentReader { - //--------------------/ //- Member Variables -/ //--------------------/ + /** The Castor XML context to use. */ + private InternalContext _internalContext; + + private Locator _documentLocator; /** - * The document locator - **/ - protected Locator _locator = null; - - /** - * The resolver to be used for resolving id references - **/ - private Resolver _resolver; - - /** - * The resolver to be used for resolving href + * The resolver to be used for resolving href. */ private URIResolver _uriResolver; @@ -86,9 +80,18 @@ //- Constructors -/ //----------------/ - public ComponentReader() { + private ComponentReader() { super(); } //-- ComponentReader + + /** + * To hand down a couple of configuration items to all Unmarshaller classes. + * @param internalContext the InternalContext to use + */ + protected ComponentReader(final InternalContext internalContext) { + this(); + _internalContext = internalContext; + } //-----------/ //- Methods -/ @@ -114,16 +117,12 @@ **/ public void finish() throws XMLException {} - public Locator getDocumentLocator() { - return _locator; - } //-- getLocator - /** * Returns the resolver used for resolving id references. * @return the resolver used for resolving id references. **/ public Resolver getResolver() { - return _resolver; + return _internalContext.getSchemaResolver(); } //-- getResolver /** @@ -141,7 +140,7 @@ * id references **/ public void setResolver(Resolver resolver) { - _resolver = resolver; + _internalContext.setSchemaResolver(resolver); } //-- setResolver @@ -188,8 +187,8 @@ throws XMLException { - if (_locator != null) { - err += "\n line: " + _locator.getLineNumber(); + if (getDocumentLocator() != null) { + err += "\n line: " + getDocumentLocator().getLineNumber(); } throw new XMLException(err); @@ -204,8 +203,8 @@ throws XMLException { - if (_locator != null) { - String err = "An error occured at line: " + _locator.getLineNumber(); + if (getDocumentLocator() != null) { + String err = "An error occured at line: " + getDocumentLocator().getLineNumber(); throw new XMLException(err, ex); } throw new XMLException(ex); @@ -222,8 +221,8 @@ String err = "Illegal attribute '" + attName + "' found on element <" + elementName() + ">."; - if (_locator != null) { - err += "\n line: " + _locator.getLineNumber(); + if (getDocumentLocator() != null) { + err += "\n line: " + getDocumentLocator().getLineNumber(); } throw new XMLException(err); @@ -239,8 +238,8 @@ String err = "Illegal element '" + name + "' found as child of <" + elementName() + ">."; - if (_locator != null) { - err += "\n line: " + _locator.getLineNumber(); + if (getDocumentLocator() != null) { + err += "\n line: " + getDocumentLocator().getLineNumber(); } throw new XMLException(err); @@ -269,8 +268,8 @@ String err = "redefintion of element '" + name + "' within element <" + elementName() + ">."; - if (_locator != null) { - err += "\n line: " + _locator.getLineNumber(); + if (getDocumentLocator() != null) { + err += "\n line: " + getDocumentLocator().getLineNumber(); } if (xtraInfo != null) { @@ -313,8 +312,12 @@ } } //-- toInt - public void setDocumentLocator(Locator locator) { - this._locator = locator; + public Locator getDocumentLocator() { + return _documentLocator; + } //-- getDocumentLocator + + public void setDocumentLocator(Locator documentLocator) { + _documentLocator = documentLocator; } //-- setDocumentLocator /** @@ -366,5 +369,20 @@ } //-- startElement + /** + * To set the Castor XML context to be used. + * @param internalContext the Castor XML context to be used + */ + public void setInternalContext(final InternalContext internalContext) { + _internalContext = internalContext; + } + + /** + * To get the Castor XML context used. + * @return the Castor XML context used + */ + public InternalContext getInternalContext() { + return _internalContext; + } } //-- ComponentReader Index: src/main/java/org/exolab/castor/xml/schema/reader/DocumentationUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/DocumentationUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/DocumentationUnmarshaller.java (working copy) @@ -46,6 +46,7 @@ package org.exolab.castor.xml.schema.reader; //-- imported classes and packages +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -83,11 +84,12 @@ //----------------/ /** - * Creates a new DocumentationUnmarshaller + * Creates a new DocumentationUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param atts the AttributeList **/ - public DocumentationUnmarshaller(AttributeSet atts) { - super(); + public DocumentationUnmarshaller(final InternalContext internalContext, final AttributeSet atts) { + super(internalContext); _documentation = new Documentation(); Index: src/main/java/org/exolab/castor/xml/schema/reader/SimpleContentRestrictionUnmarshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/reader/SimpleContentRestrictionUnmarshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/reader/SimpleContentRestrictionUnmarshaller.java (working copy) @@ -45,6 +45,7 @@ package org.exolab.castor.xml.schema.reader; +import org.castor.xml.InternalContext; import org.exolab.castor.xml.AttributeSet; import org.exolab.castor.xml.Namespaces; import org.exolab.castor.xml.XMLException; @@ -108,16 +109,19 @@ //- Constructors -/ //----------------/ /** - * Creates a new RestrictionUnmarshaller + * Creates a new RestrictionUnmarshaller. + * @param internalContext the internalContext to get some configuration settings from * @param complexType the complexType being unmarshalled * @param atts the AttributeList */ public SimpleContentRestrictionUnmarshaller( - ComplexType complexType, AttributeSet atts, Resolver resolver) { + final InternalContext internalContext, + final ComplexType complexType, + final AttributeSet atts) { - super(); - setResolver(resolver); - _complexType = complexType; + super(internalContext); + + _complexType = complexType; _complexType.setDerivationMethod(SchemaNames.RESTRICTION); _complexType.setRestriction(true); _schema = complexType.getSchema(); @@ -257,7 +261,7 @@ "'restriction' elements."); foundAnnotation = true; - unmarshaller = new AnnotationUnmarshaller(atts); + unmarshaller = new AnnotationUnmarshaller(getInternalContext(), atts); } else if (SchemaNames.SIMPLE_TYPE.equals(name)) { @@ -274,7 +278,7 @@ "elements, must appear before any attribute elements."); foundSimpleType = true; - unmarshaller = new SimpleTypeUnmarshaller(_schema, atts); + unmarshaller = new SimpleTypeUnmarshaller(getInternalContext(), _schema, atts); } else if (FacetUnmarshaller.isFacet(name)) { @@ -283,7 +287,7 @@ error("A 'facet', as a child of 'restriction' "+ "elements, must appear before any attribute elements."); - unmarshaller = new FacetUnmarshaller(name, atts); + unmarshaller = new FacetUnmarshaller(getInternalContext(), name, atts); if (_simpleTypeDef == null) { SimpleContent content = (SimpleContent)_complexType.getContentType(); _simpleTypeDef = new SimpleTypeDefinition(_schema, content.getTypeName(),_id); @@ -291,7 +295,7 @@ } else if (SchemaNames.ATTRIBUTE.equals(name)) { foundAttribute = true; - unmarshaller = new AttributeUnmarshaller(_schema,atts, getResolver()); + unmarshaller = new AttributeUnmarshaller(getInternalContext(), _schema, atts); } else if (SchemaNames.ATTRIBUTE_GROUP.equals(name)) { @@ -301,17 +305,15 @@ "attributeGroups, but not defining ones."); } foundAttributeGroup = true; - unmarshaller = new AttributeGroupUnmarshaller(_schema,atts); + unmarshaller = new AttributeGroupUnmarshaller(getInternalContext(), _schema, atts); } //-- else if (SchemaNames.ANY_ATTRIBUTE.equals(name)) { unmarshaller - = new WildcardUnmarshaller(_complexType, _schema, name, atts, getResolver()); + = new WildcardUnmarshaller(getInternalContext(), _complexType, _schema, name, atts); } else illegalElement(name); - - unmarshaller.setDocumentLocator(getDocumentLocator()); } //-- startElement /** Index: src/main/java/org/exolab/castor/xml/schema/writer/SchemaWriter.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/writer/SchemaWriter.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/writer/SchemaWriter.java (working copy) @@ -45,27 +45,62 @@ package org.exolab.castor.xml.schema.writer; +import java.io.IOException; import java.io.Writer; -import java.io.IOException; import java.util.Enumeration; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.castor.xml.BackwardCompatibilityContext; +import org.castor.xml.InternalContext; import org.exolab.castor.types.AnyNode; -import org.exolab.castor.util.LocalConfiguration; -import org.exolab.castor.xml.schema.*; +import org.exolab.castor.xml.Namespaces; +import org.exolab.castor.xml.Serializer; +import org.exolab.castor.xml.schema.Annotated; +import org.exolab.castor.xml.schema.Annotation; +import org.exolab.castor.xml.schema.AppInfo; +import org.exolab.castor.xml.schema.AttributeDecl; +import org.exolab.castor.xml.schema.AttributeGroup; +import org.exolab.castor.xml.schema.AttributeGroupDecl; +import org.exolab.castor.xml.schema.AttributeGroupReference; +import org.exolab.castor.xml.schema.BlockList; +import org.exolab.castor.xml.schema.ComplexType; +import org.exolab.castor.xml.schema.ContentModelGroup; +import org.exolab.castor.xml.schema.ContentType; +import org.exolab.castor.xml.schema.Documentation; +import org.exolab.castor.xml.schema.ElementDecl; +import org.exolab.castor.xml.schema.Facet; +import org.exolab.castor.xml.schema.FinalList; +import org.exolab.castor.xml.schema.Form; +import org.exolab.castor.xml.schema.Group; +import org.exolab.castor.xml.schema.IdentityConstraint; +import org.exolab.castor.xml.schema.IdentityField; +import org.exolab.castor.xml.schema.IdentitySelector; +import org.exolab.castor.xml.schema.KeyRef; +import org.exolab.castor.xml.schema.ModelGroup; +import org.exolab.castor.xml.schema.RedefineSchema; +import org.exolab.castor.xml.schema.Schema; +import org.exolab.castor.xml.schema.SchemaNames; +import org.exolab.castor.xml.schema.SimpleContent; +import org.exolab.castor.xml.schema.SimpleType; +import org.exolab.castor.xml.schema.Structure; +import org.exolab.castor.xml.schema.Union; +import org.exolab.castor.xml.schema.Wildcard; +import org.exolab.castor.xml.schema.XMLType; import org.exolab.castor.xml.schema.simpletypes.ListType; import org.exolab.castor.xml.util.AnyNode2SAX; -import org.exolab.castor.xml.Namespaces; -import org.exolab.castor.xml.Serializer; - import org.xml.sax.DocumentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributeListImpl; /** - * A class for serializing Schema models + * A class for serializing Schema models. * @author Keith Visco * @version $Revision$ $Date: 2006-04-05 13:16:42 -0600 (Wed, 05 Apr 2006) $ **/ public class SchemaWriter { + /** The Logger to use. */ + private static final Log LOG = LogFactory.getLog(SchemaWriter.class); //------------------------/ //- Schema element names -/ @@ -77,7 +112,7 @@ private static final String ANNOTATION = "annotation"; /** - * AppInfo element name + * AppInfo element name. */ private static final String APPINFO = "appinfo"; @@ -160,30 +195,34 @@ * @deprecated **/ public static boolean enable = false; + + /** Castor XML context - mother of all dwelling. */ + private InternalContext _internalContext = null; /** - * Creates a new SchemaWriter for the given Writer + * Creates a new SchemaWriter for the given Writer. * * @param writer the Writer to serialize to + * @throws IOException in case taht wrapping the Writer fails **/ - public SchemaWriter(Writer writer) - throws IOException - { + public SchemaWriter(final Writer writer) + throws IOException { + this(); + Serializer serializer = _internalContext.getSerializer(); - Serializer serializer = LocalConfiguration.getInstance().getSerializer(); - - if (serializer == null) + if (serializer == null) { throw new IOException("Unable to obtain serailizer"); + } - serializer.setOutputCharStream( writer ); + serializer.setOutputCharStream(writer); DocumentHandler handler = serializer.asDocumentHandler(); - if ( handler == null ) { + if (handler == null) { String err = "The following serializer is not SAX capable: "; err += serializer.getClass().getName(); err += "; cannot proceed."; - throw new IOException( err ); + throw new IOException(err); } _handler = handler; @@ -191,23 +230,80 @@ } //-- SchemaWriter /** - * Creates a new SchemaWriter for the given DocumentHandler + * Creates a new SchemaWriter for the given DocumentHandler. * * @param handler the DocumentHandler to send events to **/ - public SchemaWriter(DocumentHandler handler) { + public SchemaWriter(final DocumentHandler handler) { + this(); - if (handler == null) + if (handler == null) { throw new IllegalArgumentException("DocumentHandler must not be null."); + } _handler = handler; - } //-- SchemaWriter + /** + * A constructor to create an empty uninitialized SchemaWriter via XMLContext. + */ + public SchemaWriter() { + super(); + _internalContext = new BackwardCompatibilityContext(); + } + + /** + * To set the InternalContext to be used for the SchemaWriter. + * @param internalContext the InternalContext to be used + */ + public void setInternalContext(final InternalContext internalContext) { + _internalContext = internalContext; + } + + /** + * To set the DocumentHandler to a Writer - which is wrapped by a serializer. + * @param writer the Writer to use for output + * @throws IOException in case the Writer cannot be used for DocumentHandler + */ + public void setDocumentHandler(final Writer writer) throws IOException { + Serializer serializer = _internalContext.getSerializer(); - public void write(Schema schema) - throws SAXException - { + if (serializer == null) { + String message = "Unable to obtain serailizer"; + LOG.warn(message); + throw new IOException(message); + } + + serializer.setOutputCharStream(writer); + + DocumentHandler handler = serializer.asDocumentHandler(); + + if (handler == null) { + String err = "The following serializer is not SAX capable: "; + err += serializer.getClass().getName(); + err += "; cannot proceed."; + LOG.warn(err); + throw new IOException(err); + } + + _handler = handler; + } + + /** + * To directly set a DocumentHandler. + * @param documentHandler set the DocumentHandler + */ + public void setDocumentHandler(final DocumentHandler documentHandler) { + if (documentHandler == null) { + String message = "DocumentHandler must not be null."; + LOG.warn(message); + throw new IllegalArgumentException(message); + } + _handler = documentHandler; + } + + public void write(final Schema schema) + throws SAXException { if (schema == null) throw new IllegalArgumentException("Schema must not be null."); Index: src/main/java/org/exolab/castor/xml/schema/util/XMLInstance2Schema.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/util/XMLInstance2Schema.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/util/XMLInstance2Schema.java (working copy) @@ -51,12 +51,12 @@ import java.io.Reader; import java.io.Writer; -import org.exolab.castor.util.Configuration; -import org.exolab.castor.util.LocalConfiguration; -import org.exolab.castor.xml.schema.*; +import org.castor.xml.BackwardCompatibilityContext; +import org.castor.xml.InternalContext; +import org.exolab.castor.util.NestedIOException; +import org.exolab.castor.xml.schema.Order; +import org.exolab.castor.xml.schema.Schema; import org.exolab.castor.xml.schema.writer.SchemaWriter; -import org.exolab.castor.util.NestedIOException; - import org.xml.sax.InputSource; import org.xml.sax.Parser; @@ -67,7 +67,9 @@ * @version $Revision$ $Date: 2006-01-16 13:22:58 -0700 (Mon, 16 Jan 2006) $ **/ public class XMLInstance2Schema { - + /** The {@link InternalContext} used to get Parser from. */ + private InternalContext _internalContext; + private Order _defaultGroup = Order.seq; /** @@ -76,6 +78,7 @@ **/ public XMLInstance2Schema() { super(); + _internalContext = new BackwardCompatibilityContext(); } //-- XMLInstance2Schema /** @@ -118,8 +121,7 @@ handler.setDefaultGroupOrder(_defaultGroup); try { - Configuration config = LocalConfiguration.getInstance(); - Parser parser = config.getParser(); + Parser parser = _internalContext.getParser(); if (parser == null) { throw new IOException("fatal error: unable to create SAX parser."); } Index: src/main/java/org/exolab/castor/xml/schema/simpletypes/factory/Type.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/simpletypes/factory/Type.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/simpletypes/factory/Type.java (working copy) @@ -148,4 +148,26 @@ } output.println(); } + + /** + * To generate a {@link String} representing this class instance. + * @see java.lang.Object#toString() + */ + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("name: ").append(name); + sb.append(" code: ").append(code); + sb.append(" base: ").append(base); + sb.append(" impl: ").append(impl); + sb.append(" derivedBy: ").append(derivedBy); + sb.append('\n'); + sb.append("Facets count: ").append(facet.size()); + sb.append('\n'); + for (int index = 0; index < facet.size(); index++) { + TypeProperty tp = (TypeProperty) (facet.elementAt(index)); + sb.append(tp.toString()); + } + sb.append('\n'); + return sb.toString(); + } } Index: src/main/java/org/exolab/castor/xml/schema/simpletypes/factory/TypeProperty.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/simpletypes/factory/TypeProperty.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/simpletypes/factory/TypeProperty.java (working copy) @@ -85,6 +85,14 @@ public void Print(PrintWriter output) { - output.println(name + " : " + value); + output.println(toString()); } + + /** + * To generate a {@link String} representing this class instance. + * @see java.lang.Object#toString() + */ + public String toString() { + return name + " : " + value; + } } Index: src/main/java/org/exolab/castor/xml/schema/simpletypes/factory/TypeList.java =================================================================== --- src/main/java/org/exolab/castor/xml/schema/simpletypes/factory/TypeList.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/schema/simpletypes/factory/TypeList.java (working copy) @@ -85,6 +85,19 @@ output.flush(); } + /** + * To generate a {@link String} representing this class instance. + * @see java.lang.Object#toString() + */ + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("Types count: ").append(types.size()); + for (int index = 0; index < types.size(); index++) { + Type t = (Type) (types.elementAt(index)); + sb.append(t.toString()); + } + return sb.toString(); + } } Index: src/main/java/org/exolab/castor/xml/Validator.java =================================================================== --- src/main/java/org/exolab/castor/xml/Validator.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/Validator.java (working copy) @@ -49,11 +49,13 @@ */ package org.exolab.castor.xml; -import org.castor.mapping.BindingType; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.castor.xml.BackwardCompatibilityContext; +import org.castor.xml.InternalContext; import org.exolab.castor.mapping.FieldDescriptor; import org.exolab.castor.xml.location.XPathLocation; import org.exolab.castor.xml.validators.ClassValidator; -import org.exolab.castor.xml.TypeValidator; /** * A class which can perform Validation on an Object model. This class uses the @@ -63,6 +65,7 @@ * @version $Revision$ $Date: 2005-02-28 17:43:25 -0700 (Mon, 28 Feb 2005) $ */ public class Validator implements ClassValidator { + private static final Log LOG = LogFactory.getLog(Validator.class); /** * Creates a new Validator. @@ -95,20 +98,25 @@ } if (context == null) { - validate(object, new ValidationContext()); + ValidationContext v2 = new ValidationContext(); + InternalContext ic = new BackwardCompatibilityContext(); + ic.setClassLoader(object.getClass().getClassLoader()); + v2.setInternalContext(ic); + validate(object, v2); return; } - if (context.getResolver() == null) { - context.setResolver((XMLClassDescriptorResolver) - ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML)); + if (context.getClassDescriptorResolver() == null) { + String message = "ClassDescriptorResolver from context must not be null!"; + LOG.warn(message); + throw new IllegalStateException(message); } XMLClassDescriptor classDesc = null; - if (! MarshalFramework.isPrimitive(object.getClass())) { + if (!MarshalFramework.isPrimitive(object.getClass())) { try { - classDesc = (XMLClassDescriptor) context.getResolver().resolve(object.getClass()); + classDesc = (XMLClassDescriptor) context.getClassDescriptorResolver().resolve(object.getClass()); } catch (ResolverException rx) { throw new ValidationException(rx); } @@ -130,7 +138,7 @@ FieldDescriptor[] fields = classDesc.getFields(); if (fields != null) { for (int i = 0; i < fields.length; i++) { - fieldDesc = (XMLFieldDescriptor)fields[i]; + fieldDesc = (XMLFieldDescriptor) fields[i]; if (fieldDesc == null) { continue; } @@ -143,7 +151,7 @@ } } catch (ValidationException vx) { //-- add location information - XPathLocation loc = (XPathLocation)vx.getLocation(); + XPathLocation loc = (XPathLocation) vx.getLocation(); if (loc == null) { loc = new XPathLocation(); vx.setLocation(loc); Index: src/main/java/org/exolab/castor/xml/validators/IdRefValidator.java =================================================================== --- src/main/java/org/exolab/castor/xml/validators/IdRefValidator.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/validators/IdRefValidator.java (working copy) @@ -56,7 +56,7 @@ // get the id of the target object String id = null; try { - ClassDescriptorResolver classDescriptorResolver = context.getResolver(); + ClassDescriptorResolver classDescriptorResolver = context.getClassDescriptorResolver(); ClassDescriptor classDescriptor = classDescriptorResolver.resolve(object.getClass()); FieldDescriptor fieldDescriptor = classDescriptor.getIdentity(); FieldHandler fieldHandler = fieldDescriptor.getHandler(); Index: src/main/java/org/exolab/castor/xml/validators/PatternValidator.java =================================================================== --- src/main/java/org/exolab/castor/xml/validators/PatternValidator.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/validators/PatternValidator.java (working copy) @@ -259,7 +259,7 @@ * the ValidationContext */ private void initEvaluator(final ValidationContext context) { - _regex = context.getConfiguration().getRegExpEvaluator(); + _regex = context.getInternalContext().getRegExpEvaluator(); if (_regex == null) { _regex = new DefaultRegExpEvaluator(); } Index: src/main/java/org/exolab/castor/xml/FieldValidator.java =================================================================== --- src/main/java/org/exolab/castor/xml/FieldValidator.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/FieldValidator.java (working copy) @@ -198,7 +198,7 @@ if (_descriptor.isRequired() && _descriptor.getSchemaType() != null && _descriptor.getSchemaType().equals("IDREF") - && context.getConfiguration().getLenientIdValidation()) { + && context.getInternalContext().getLenientIdValidation()) { return; } StringBuffer buff = new StringBuffer(); Index: src/main/java/org/exolab/castor/xml/Marshaller.java =================================================================== --- src/main/java/org/exolab/castor/xml/Marshaller.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/Marshaller.java (working copy) @@ -56,6 +56,9 @@ import org.castor.util.Base64Encoder; import org.castor.util.Messages; import org.castor.util.HexDecoder; +import org.castor.xml.BackwardCompatibilityContext; +import org.castor.xml.XMLConfiguration; +import org.castor.xml.InternalContext; import org.exolab.castor.mapping.CollectionHandler; import org.exolab.castor.mapping.MapItem; import org.exolab.castor.mapping.Mapping; @@ -170,11 +173,6 @@ private boolean _asDocument = true; /** - * The ClassDescriptorResolver used for resolving XMLClassDescriptors - **/ - private XMLClassDescriptorResolver _cdResolver = null; - - /** * The depth of the sub tree, 0 denotes document level **/ int depth = 0; @@ -192,11 +190,6 @@ private ContentHandler _handler = null; /** - * Castor configuration - */ - private Configuration _config = null; - - /** * flag to indicate whether or not to use xsi:type **/ private boolean _marshalExtendedType = true; @@ -214,16 +207,6 @@ private Namespaces _namespaces = null; /** - * The XMLNaming instance being used. - **/ - private XMLNaming _naming = null; - - /** - * Insert NameSpace prefix declarations at the root node - */ - //private boolean _nsPrefixAtRoot = false; - - /** * current java packages being used during marshalling **/ private List _packages = null; @@ -332,6 +315,17 @@ } /** + * Creates a new Marshaller with the given writer. + * @param out the Writer to serialize to + **/ + public Marshaller( Writer out ) + throws IOException + { + initialize(); + setWriter(out); + } //-- Marshaller + + /** * Sets the java.io.Writer to be used during marshalling. * @param out The writer to use for marshalling * @throws IOException If there's a problem accessing the java.io.Writer provided @@ -343,21 +337,10 @@ configureSerializer(out); } - /** - * Creates a new Marshaller with the given writer. - * @param out the Writer to serialize to - **/ - public Marshaller( Writer out ) - throws IOException - { - initialize(); - setWriter(out); - } //-- Marshaller - private void configureSerializer(Writer out) throws IOException { - _serializer = _config.getSerializer(); + _serializer = getInternalContext().getSerializer(); if (_serializer == null) throw new RuntimeException("Unable to obtain serializer"); @@ -396,29 +379,25 @@ * the Constructors **/ private void initialize() { - _config = LocalConfiguration.getInstance(); + setInternalContext(new BackwardCompatibilityContext()); _namespaces = new Namespaces(); _packages = new ArrayList(3); - _cdResolver = (XMLClassDescriptorResolver) - ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML); _parents = new SafeStack(); - _validate = _config.marshallingValidation(); - _naming = XMLNaming.getInstance(); + _validate = getInternalContext().marshallingValidation(); +// _naming = XMLNaming.getInstance(); _processingInstructions = new ArrayList(3); _attributes = new AttributesImpl(); _topLevelAtts = new AttributeSetImpl(); - - //-- saveMapKeys - String val = _config.getProperty(Configuration.Property.SaveMapKeys, "true"); - if ("false".equalsIgnoreCase(val) || "off".equalsIgnoreCase(val)) { - _saveMapKeys = false; - } + _saveMapKeys = + getInternalContext().getBooleanProperty(XMLConfiguration.SAVE_MAP_KEYS).booleanValue(); - //-- proxy interfaces to search for if defined - String prop = _config.getProperty(Configuration.Property.ProxyInterfaces, ""); - StringTokenizer tokenizer = new StringTokenizer(prop, ", "); - while (tokenizer.hasMoreTokens()) { - _proxyInterfaces.add(tokenizer.nextToken()); + String prop = + getInternalContext().getStringProperty(XMLConfiguration.PROXY_INTERFACES); + if (prop != null) { + StringTokenizer tokenizer = new StringTokenizer(prop, ", "); + while (tokenizer.hasMoreTokens()) { + _proxyInterfaces.add(tokenizer.nextToken()); + } } } //-- initialize(); @@ -454,7 +433,7 @@ if (_serializer != null) { if (_format == null) { - _format = _config.getOutputFormat(); + _format = getInternalContext().getOutputFormat(); } _format.setDoctype(publicId, systemId); //-- reset output format, this needs to be done @@ -528,7 +507,7 @@ if (_serializer != null) { if (_format == null) { - _format = _config.getOutputFormat(); + _format = getInternalContext().getOutputFormat(); } _format.setOmitXMLDeclaration( ! asDocument ); _format.setOmitDocumentType( ! asDocument ); @@ -563,14 +542,21 @@ * @param mapping Mapping to using during marshalling. */ public void setMapping(final Mapping mapping) throws MappingException { - if (_cdResolver == null) { - _cdResolver = (XMLClassDescriptorResolver) ClassDescriptorResolverFactory - .createClassDescriptorResolver(BindingType.XML); +// if (_cdResolver == null) { +// _cdResolver = (XMLClassDescriptorResolver) ClassDescriptorResolverFactory +// .createClassDescriptorResolver(BindingType.XML); +// } + if ((getInternalContext() == null) + || (getInternalContext().getXMLClassDescriptorResolver() == null)) { + String message = "No internal context or no class descriptor in context."; + LOG.warn(message); + throw new IllegalStateException(message); } MappingUnmarshaller mum = new MappingUnmarshaller(); + mum.setInternalContext(getInternalContext()); MappingLoader resolver = mum.getMappingLoader(mapping, BindingType.XML); - _cdResolver.setMappingLoader(resolver); + getInternalContext().getXMLClassDescriptorResolver().setMappingLoader(resolver); } /** @@ -652,18 +638,24 @@ * @return the ClassDescriptorResolver * @see #setResolver */ - public ClassDescriptorResolver getResolver() { + public XMLClassDescriptorResolver getResolver() { - if (_cdResolver == null) { - _cdResolver = (XMLClassDescriptorResolver) - ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML); +// if (_cdResolver == null) { +// _cdResolver = (XMLClassDescriptorResolver) +// ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML); +// } + if ((getInternalContext() == null) + || (getInternalContext().getXMLClassDescriptorResolver() == null)) { + String message = "No internal context or no class descriptor in context."; + LOG.warn(message); + throw new IllegalStateException(message); } - return _cdResolver; + return getInternalContext().getXMLClassDescriptorResolver(); } //-- getResolver /** - * Sets the ClassDescriptorResolver to use during marshalling + * Sets the ClassDescriptorResolver to use during marshalling. * *
* Note: This method will nullify any Mapping @@ -673,9 +665,12 @@ * @see #setMapping * @see #getResolver */ - public void setResolver(XMLClassDescriptorResolver cdr) { + public void setResolver(final XMLClassDescriptorResolver cdr) { - if (cdr != null) _cdResolver = cdr; + if (cdr != null) { + getInternalContext().setXMLClassDescriptorResolver(cdr); +// _cdResolver = cdr; + } } //-- setResolver @@ -962,7 +957,7 @@ name = name.substring(idx+1); } //-- remove capitalization - name = _naming.toXMLName(name); + name = getInternalContext().getXMLNaming().toXMLName(name); } //-- obtain the class descriptor @@ -1025,7 +1020,7 @@ String nsURI = descriptor.getNameSpaceURI(); XMLClassDescriptor tmpDesc = null; try { - tmpDesc = _cdResolver.resolveByXMLName(name, nsURI, null); + tmpDesc = getResolver().resolveByXMLName(name, nsURI, null); } catch(ResolverException rx) { //-- exception not important as we're simply @@ -1051,7 +1046,7 @@ //-- one if (atRoot) { if (_useXSITypeAtRoot) { - XMLMappingLoader ml = (XMLMappingLoader) _cdResolver.getMappingLoader(); + XMLMappingLoader ml = (XMLMappingLoader) getResolver().getMappingLoader(); if (ml != null) { containsDesc = (ml.getDescriptor(_class.getName()) != null); } @@ -1179,7 +1174,7 @@ // with the XML name of this class XMLClassDescriptor xmlElementNameClassDesc = null; try { - xmlElementNameClassDesc = _cdResolver.resolveByXMLName(xmlElementName, null, null); + xmlElementNameClassDesc = getResolver().resolveByXMLName(xmlElementName, null, null); } catch(ResolverException rx) { //-- exception not important as we're simply @@ -1194,7 +1189,7 @@ if ((xmlElementName != null) && (xmlElementNameClassDesc != null)) { // More than one class can map to a given element name try { - Iterator classDescriptorIter = _cdResolver.resolveAllByXMLName(xmlElementName, null, null); + Iterator classDescriptorIter = getResolver().resolveAllByXMLName(xmlElementName, null, null); for (; classDescriptorIter.hasNext();) { xmlElementNameClassDesc = (XMLClassDescriptor) classDescriptorIter.next(); if (_class == xmlElementNameClassDesc.getJavaClass()) @@ -1226,7 +1221,7 @@ // Try to find a field descriptor by inheritance in the parent object InheritanceMatch[] matches = - searchInheritance(xmlElementName, null, tempContaining, _cdResolver); + searchInheritance(xmlElementName, null, tempContaining); // TODO: Joachim, _cdResolver); if (matches.length == 1) { @@ -2135,7 +2130,7 @@ if (_serializer != null) { if (_format == null) { - _format = _config.getOutputFormat(); + _format = getInternalContext().getOutputFormat(); } _format.setEncoding(encoding); //-- reset output format, this needs to be done @@ -2256,7 +2251,7 @@ try { if (!isPrimitive(_class)) - classDesc = (XMLClassDescriptor) _cdResolver.resolve(_class); + classDesc = (XMLClassDescriptor) getResolver().resolve(_class); } catch(ResolverException rx) { Throwable actual = rx.getCause(); @@ -2540,8 +2535,9 @@ //-- we must have a valid element before marshalling Validator validator = new Validator(); ValidationContext context = new ValidationContext(); - context.setConfiguration(_config); - context.setResolver(_cdResolver); + context.setInternalContext(getInternalContext()); +// context.setConfiguration(_config); +// context.setResolver(_cdResolver); validator.validate(object, context); } } @@ -2553,7 +2549,7 @@ * @since 1.1.2 */ public String getProperty(final String name) { - return _config.getProperties().getProperty(name); + return getInternalContext().getStringProperty(name); } /** @@ -2563,7 +2559,7 @@ * @since 1.1.2 */ public void setProperty(final String name, final String value) { - _config.getProperties().setProperty(name, value); + getInternalContext().setProperty(name, value); } /** @@ -2668,6 +2664,13 @@ } } + /** + * To set the content handler which is used as destination at marshalling. + * @param contentHandler the content handler to use as destination at marshalling + */ + public void setContentHandler(final ContentHandler contentHandler) { + _handler = contentHandler; + } } //-- Marshaller Index: src/main/java/org/exolab/castor/xml/XMLNaming.java =================================================================== --- src/main/java/org/exolab/castor/xml/XMLNaming.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/XMLNaming.java (working copy) @@ -45,8 +45,7 @@ package org.exolab.castor.xml; -import org.exolab.castor.util.Configuration; -import org.exolab.castor.util.LocalConfiguration; +import org.castor.xml.BackwardCompatibilityContext; /** * An abstract class to handing XML naming @@ -84,12 +83,11 @@ /** - * Returns the default instance of XMLNaming + * Returns the default instance of XMLNaming. * @see org.exolab.castor.util.Configuration **/ public static final XMLNaming getInstance() { - Configuration config = LocalConfiguration.getInstance(); - return config.getXMLNaming(); + return new BackwardCompatibilityContext().getXMLNaming(); } //-- getInstance } //-- Naming Index: src/main/java/org/exolab/castor/xml/util/resolvers/CastorXMLStrategy.java =================================================================== --- src/main/java/org/exolab/castor/xml/util/resolvers/CastorXMLStrategy.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/util/resolvers/CastorXMLStrategy.java (working copy) @@ -20,6 +20,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.castor.xml.InternalContext; import org.exolab.castor.mapping.ClassDescriptor; import org.exolab.castor.xml.ResolverException; import org.exolab.castor.xml.XMLClassDescriptor; @@ -38,6 +39,7 @@ * @since 1.2 */ public class CastorXMLStrategy implements ResolverStrategy { + /** Logger to be used. */ private static final Log LOG = LogFactory.getLog(CastorXMLStrategy.class); /** The strategy configuration held as map of properties. */ @@ -47,12 +49,11 @@ * CastorXMLStrategy requires a configuration to be set. Within the constructor the * commands building the strategy are instantiated, a command configuration is created * and the descriptor cache. - * @param configuration the strategy configuration to use. */ public CastorXMLStrategy() { _properties = new HashMap(); - } //-- CastorXmlStrategy(Configuration) - + } //-- CastorXmlStrategy() + /** * {@inheritDoc} */ Index: src/main/java/org/exolab/castor/xml/util/resolvers/ByPackageMapping.java =================================================================== --- src/main/java/org/exolab/castor/xml/util/resolvers/ByPackageMapping.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/util/resolvers/ByPackageMapping.java (working copy) @@ -111,6 +111,7 @@ final Mapping mapping = this.loadMapping(packageName, classLoader); if (mapping != null) { MappingUnmarshaller unmarshaller = new MappingUnmarshaller(); + // TODO: Joachim 2007-09-07 the InternalContext should be set into the unmarshaller! MappingLoader mappingLoader = unmarshaller.getMappingLoader(mapping, BindingType.XML); Iterator descriptors = mappingLoader.descriptorIterator(); while (descriptors.hasNext()) { Index: src/main/java/org/exolab/castor/xml/util/resolvers/ByIntrospection.java =================================================================== --- src/main/java/org/exolab/castor/xml/util/resolvers/ByIntrospection.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/util/resolvers/ByIntrospection.java (working copy) @@ -36,14 +36,17 @@ * @since 1.2 */ public class ByIntrospection extends AbstractResolverClassCommand { - private static final Log LOG = LogFactory.getLog(ByIntrospection.class); + /** + * Logger to be used. + */ + private static final Log LOG = LogFactory.getLog(ByIntrospection.class); /** * No specific stuff needed. */ - public ByIntrospection() { + public ByIntrospection() { super(); - } + } /** * Creates an XMLClassDescriptor for the given type by using introspection. @@ -59,7 +62,8 @@ protected Map internalResolve(final String className, final ClassLoader classLoader, final Map properties) throws ResolverException { - Boolean useIntrospector = (Boolean)properties.get(ResolverStrategy.PROPERTY_USE_INTROSPECTION); + Boolean useIntrospector = + (Boolean) properties.get(ResolverStrategy.PROPERTY_USE_INTROSPECTION); HashMap results = new HashMap(); if (classLoader == null) { LOG.debug("No class loader available."); @@ -67,12 +71,19 @@ } if ((useIntrospector != null) && (!useIntrospector.booleanValue())) { - // I know the logic is a bit weired... either introspection is explicitly disabled or it is ok! + // I know the logic is a bit weired... either introspection is explicitly + // disabled or it is ok! LOG.debug("Introspection is disabled!"); return results; } - Introspector introspector = new Introspector(); + Introspector introspector = + (Introspector) properties.get(ResolverStrategy.PROPERTY_INTROSPECTOR); + if (introspector == null) { + String message = "No Introspector defined in properties!"; + LOG.warn(message); + throw new IllegalStateException(message); + } Class clazz = ResolveHelpers.loadClass(classLoader, className); if (clazz != null) { try { @@ -84,7 +95,8 @@ results.put(clazz.getName(), descriptor); } } catch (MarshalException e) { - String message = "Failed to generate class descriptor for: " + clazz + " with exception: " + e; + String message = "Failed to generate class descriptor for: " + + clazz + " with exception: " + e; LOG.warn(message); throw new ResolverException(message); } Index: src/main/java/org/exolab/castor/xml/util/XMLClassDescriptorImpl.java =================================================================== --- src/main/java/org/exolab/castor/xml/util/XMLClassDescriptorImpl.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/util/XMLClassDescriptorImpl.java (working copy) @@ -868,14 +868,17 @@ * @param context the ValidationContext */ public void validate(Object object, ValidationContext context) - throws ValidationException - { + throws ValidationException { if (object == null) { throw new ValidationException("Cannot validate a null object."); } + Class a = getJavaClass(); + ClassLoader acl = a.getClassLoader(); + Class b = object.getClass(); + ClassLoader bcl = b.getClassLoader(); if (!getJavaClass().isAssignableFrom(object.getClass())) { - String err = "The given object is not an instance of the class"+ - " described by this ClassDecriptor."; + String err = "The given object is not an instance of the class" + + " described by this ClassDecriptor."; throw new ValidationException(err); } Index: src/main/java/org/exolab/castor/xml/util/ResolverStrategy.java =================================================================== --- src/main/java/org/exolab/castor/xml/util/ResolverStrategy.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/util/ResolverStrategy.java (working copy) @@ -17,6 +17,7 @@ import java.util.Map; +import org.castor.xml.InternalContext; import org.exolab.castor.mapping.ClassDescriptor; import org.exolab.castor.xml.ResolverException; import org.exolab.castor.xml.XMLClassDescriptor; @@ -31,24 +32,24 @@ * @since 1.2 */ public interface ResolverStrategy { - /** To set the class loader property for resolving */ - public final static String PROPERTY_CLASS_LOADER = + /** To set the class loader property for resolving. */ + String PROPERTY_CLASS_LOADER = "org.exolab.castor.xml.util.ResolverStrategy.ClassLoader"; - /** To set the use introspection property for resolving */ - public final static String PROPERTY_USE_INTROSPECTION = + /** To set the use introspection property for resolving. */ + String PROPERTY_USE_INTROSPECTION = "org.exolab.castor.xml.util.ResolverStrategy.useIntrospection"; - /** To set the introspector property for resolving */ - public final static String PROPERTY_INTROSPECTOR = + /** To set the introspector property for resolving. */ + String PROPERTY_INTROSPECTOR = "org.exolab.castor.xml.util.ResolverStrategy.Introspector"; - /** To set the LoadPackageMappings property for resolving */ - public final static String PROPERTY_LOAD_PACKAGE_MAPPINGS = + /** To set the LoadPackageMappings property for resolving. */ + String PROPERTY_LOAD_PACKAGE_MAPPINGS = "org.exolab.castor.xml.util.ResolverStrategy.LoadPackageMappings"; - /** To set the mapping loader property for resolving */ - public final static String PROPERTY_MAPPING_LOADER = + /** To set the mapping loader property for resolving. */ + String PROPERTY_MAPPING_LOADER = "org.exolab.castor.xml.util.ResolverStrategy.MappingLoader"; /** @@ -57,24 +58,27 @@ * @param key name of the property * @param value value the property is set to */ - public void setProperty(String key, Object value); + void setProperty(final String key, final Object value); /** * Implementes a strategy how a class is resolved into a list of class descriptors. * + * @param resolverResults to put the resolver reszlts into * @param className the class to resolve * @return the ClassDescriptor for the class or null if the class couldn't be resolved + * @throws ResolverException in case that resolving fails fatally */ - public ClassDescriptor resolveClass(ResolverResults resolverResults, String className) + ClassDescriptor resolveClass(final ResolverResults resolverResults, final String className) throws ResolverException; /** * Implementes a strategy how a package is resolved into a list of class descriptors. * + * @param resolverResults to put the resolver reszlts into * @param packageName the package to resolve - * @return the ClassDescriptor for the class or null if the class couldn't be resolved + * @throws ResolverException in case that resolving fails fatally */ - public void resolvePackage(ResolverResults resolverResults, String packageName) + void resolvePackage(ResolverResults resolverResults, String packageName) throws ResolverException; /** @@ -103,14 +107,14 @@ * * @see #INTERNAL_CONTAINER_NAME */ - public void addDescriptor(String className, XMLClassDescriptor descriptor); + void addDescriptor(String className, XMLClassDescriptor descriptor); /** * To add not only a single descriptor but a map of descriptors at once. * - * @param descriptor a Map of className (String) and XMLClassDescriptor pairs + * @param descriptors a Map of className (String) and XMLClassDescriptor pairs */ - public void addAllDescriptors(Map descriptors); + void addAllDescriptors(Map descriptors); /** * Gets the descriptor that is mapped to the given class name. @@ -119,6 +123,6 @@ * @return The descriptor mapped to the given name or null * if no descriptor is stored in this cache. */ - public XMLClassDescriptor getDescriptor(String className); + XMLClassDescriptor getDescriptor(String className); } } Index: src/main/java/org/exolab/castor/xml/util/XMLClassDescriptorAdapter.java =================================================================== --- src/main/java/org/exolab/castor/xml/util/XMLClassDescriptorAdapter.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/util/XMLClassDescriptorAdapter.java (working copy) @@ -44,11 +44,11 @@ */ package org.exolab.castor.xml.util; +import org.castor.xml.BackwardCompatibilityContext; import org.exolab.castor.mapping.ClassDescriptor; import org.exolab.castor.mapping.FieldDescriptor; import org.exolab.castor.mapping.MappingException; import org.exolab.castor.mapping.loader.ClassDescriptorImpl; -import org.exolab.castor.util.LocalConfiguration; import org.exolab.castor.xml.NodeType; import org.exolab.castor.xml.XMLClassDescriptor; import org.exolab.castor.xml.XMLFieldDescriptor; @@ -96,7 +96,7 @@ } if (primitiveNodeType == null) { - primitiveNodeType = LocalConfiguration.getInstance().getPrimitiveNodeType(); + primitiveNodeType = new BackwardCompatibilityContext().getPrimitiveNodeType(); } if (primitiveNodeType == null) { Index: src/main/java/org/exolab/castor/xml/util/XMLClassDescriptorResolverImpl.java =================================================================== --- src/main/java/org/exolab/castor/xml/util/XMLClassDescriptorResolverImpl.java (revision 7270) +++ src/main/java/org/exolab/castor/xml/util/XMLClassDescriptorResolverImpl.java (working copy) @@ -58,15 +58,13 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.castor.xml.InternalContext; import org.exolab.castor.mapping.ClassDescriptor; import org.exolab.castor.mapping.MappingLoader; -import org.exolab.castor.util.Configuration; -import org.exolab.castor.util.LocalConfiguration; -import org.exolab.castor.util.Configuration.Property; +import org.exolab.castor.xml.Introspector; import org.exolab.castor.xml.ResolverException; import org.exolab.castor.xml.XMLClassDescriptor; import org.exolab.castor.xml.XMLClassDescriptorResolver; -import org.exolab.castor.xml.util.resolvers.CastorXMLStrategy; import org.exolab.castor.xml.util.resolvers.ResolveHelpers; /** @@ -76,54 +74,112 @@ * @version $Revision$ $Date: 2006-04-25 15:08:23 -0600 (Tue, 25 Apr 2006) $ */ public class XMLClassDescriptorResolverImpl implements XMLClassDescriptorResolver { + /** The Logger instance to use. */ private static final Log LOG = LogFactory.getLog(XMLClassDescriptorResolverImpl.class); /** - * The strategy to use for all resolve actions. + * XMLContext provides the information required. */ - private ResolverStrategy _strategy; + private InternalContext _internalContext; /** - * The place where all rsolving strategies and their commands put the results into + * The place where all resolving strategies and their commands put the results into * and can be read from. */ private DescriptorCacheImpl _descriptorCache; /** - * The mapping loader is read from the XMLClassDescriptorResolver and used in the - * strategy - so we need to keep it. + * Creates a new ClassDescriptorResolverImpl. + * It is left empty to avoid cycles at construction. To guarantee + * backward compatibility the backwardInit method will do all + * required initialization if it hadn't happend before. */ - private MappingLoader _mappingLoader; + public XMLClassDescriptorResolverImpl() { + super(); + _descriptorCache = new DescriptorCacheImpl(); + } //-- ClassDescriptorResolverImpl /** - * The class loader which is used when no other class loader was specified in - * the resolve call. If this loader is also not set the context loader of the - * current thread is used. + * {@inheritDoc} */ - private ClassLoader _loader; + public void setInternalContext(final InternalContext internalContext) { + _internalContext = internalContext; + } + + /** + * {@inheritDoc} + */ + public MappingLoader getMappingLoader() { + return _internalContext.getMappingLoader(); // _mappingLoader; + } //-- getXMLMappingLoader /** - * Creates a new ClassDescriptorResolverImpl. + * {@inheritDoc} */ - public XMLClassDescriptorResolverImpl() { - Configuration config = LocalConfiguration.getInstance(); - boolean loadPackageMappings = config.getBoolean( - Property.LOAD_PACKAGE_MAPPING, - Property.DEFAULT_LOAD_PACKAGE_MAPPING); - - _strategy = new CastorXMLStrategy(); - _strategy.setProperty( - ResolverStrategy.PROPERTY_LOAD_PACKAGE_MAPPINGS, - Boolean.valueOf(loadPackageMappings)); + public void setClassLoader(final ClassLoader loader) { + _internalContext.setClassLoader(loader); +// _loader = loader; + } //-- setClassLoader - _descriptorCache = new DescriptorCacheImpl(); - _mappingLoader = null; - _loader = null; - } //-- ClassDescriptorResolverImpl + /** + * {@inheritDoc} + */ + public void setUseIntrospection(final boolean enable) { + // used by XMLMappingLoader.createResolver() + _internalContext.setUseIntrospector(Boolean.valueOf(enable)); + } //-- setIntrospection /** * {@inheritDoc} */ + public void setLoadPackageMappings(final boolean loadPackageMappings) { + _internalContext.setLoadPackageMapping(Boolean.valueOf(loadPackageMappings)); + } //-- setLoadPackageMappings + + /** + * {@inheritDoc} + */ + public void setMappingLoader(final MappingLoader mappingLoader) { + _internalContext.setMappingLoader(mappingLoader); + if (mappingLoader != null) { + Iterator descriptors = mappingLoader.descriptorIterator(); + while (descriptors.hasNext()) { + XMLClassDescriptor descriptor = (XMLClassDescriptor) descriptors.next(); + _descriptorCache.addDescriptor(descriptor.getJavaClass().getName(), descriptor); + } + } + } //-- setMappingLoader + + /** + * {@inheritDoc} + */ + public void setIntrospector(final Introspector introspector) { + _internalContext.setIntrospector(introspector); + } + + /** + * {@inheritDoc} + */ + public void setResolverStrategy(final ResolverStrategy resolverStrategy) { + _internalContext.setResolverStrategy(resolverStrategy); + } + + /** + * XMLClassDescriptorResolver was originally build to collect all required + * information by itself... now with introduction of XMLContext and a more + * IoC like concepts that all information is injected into a class... things + * are different but this methods is there to guarantee backward + * compatibility. + * @return the {@link ResolverStrategy} to use + */ + private ResolverStrategy getResolverStrategy() { + setAttributesIntoStrategy(); + return _internalContext.getResolverStrategy(); + } + + /** + * {@inheritDoc} + */ public ClassDescriptor resolve(final Class type) throws ResolverException { if (type == null) { String message = "Type argument must not be null for resolve"; @@ -135,7 +191,7 @@ return _descriptorCache.getDescriptor(type.getName()); } - ClassLoader l = _loader; + ClassLoader l = _internalContext.getClassLoader(); if (l == null) { l = type.getClassLoader(); } if (l == null) { l = Thread.currentThread().getContextClassLoader(); } @@ -156,7 +212,7 @@ return _descriptorCache.getDescriptor(className); } - ClassLoader l = _loader; + ClassLoader l = _internalContext.getClassLoader(); if (l == null) { l = Thread.currentThread().getContextClassLoader(); } return this.resolve(className, l); @@ -178,11 +234,11 @@ } ClassLoader l = loader; - if (l == null) { l = _loader; } + if (l == null) { l = _internalContext.getClassLoader(); } if (l == null) { l = Thread.currentThread().getContextClassLoader(); } - _strategy.setProperty(ResolverStrategy.PROPERTY_CLASS_LOADER, l); - return (XMLClassDescriptor) _strategy.resolveClass(_descriptorCache, className); + getResolverStrategy().setProperty(ResolverStrategy.PROPERTY_CLASS_LOADER, l); + return (XMLClassDescriptor) getResolverStrategy().resolveClass(_descriptorCache, className); } //-- resolve(String, ClassLoader) /** @@ -212,7 +268,7 @@ } // we have more than one result - only an exact match can be the result - for (Iterator i = possibleMatches.iterator(); i.hasNext();) { + for (Iterator i = possibleMatches.iterator(); i.hasNext(); ) { XMLClassDescriptor descriptor = (XMLClassDescriptor) i.next(); if (ResolveHelpers.namespaceEquals(namespaceURI, descriptor.getNameSpaceURI())) { @@ -243,57 +299,6 @@ /** * {@inheritDoc} */ - public MappingLoader getMappingLoader() { - return _mappingLoader; - } //-- getXMLMappingLoader - - /** - * {@inheritDoc} - */ - public void setClassLoader(ClassLoader loader) { - _loader = loader; - } //-- setClassLoader - - /** - * Enables or disables introspection. Introspection is enabled by default. - * - * @param enable a flag to indicate whether or not introspection is allowed. - */ - public void setIntrospection(boolean enable) { - // used by XMLMappingLoader.createResolver() - _strategy.setProperty(ResolverStrategy.PROPERTY_USE_INTROSPECTION, new Boolean(enable)); - } //-- setIntrospection - - /** - * Sets whether or not to look for and load package specific mapping files (".castor.xml"). - * - * @param loadPackageMappings a boolean that enables or disables the loading of package - * specific mapping files - */ - public void setLoadPackageMappings(boolean loadPackageMappings) { - _strategy.setProperty( - ResolverStrategy.PROPERTY_LOAD_PACKAGE_MAPPINGS, - Boolean.valueOf(loadPackageMappings)); - } //-- setLoadPackageMappings - - /** - * {@inheritDoc} - */ - public void setMappingLoader(MappingLoader mappingLoader) { - _mappingLoader = mappingLoader; - if (_mappingLoader != null) { - Iterator descriptors = _mappingLoader.descriptorIterator(); - while (descriptors.hasNext()) { - XMLClassDescriptor descriptor = (XMLClassDescriptor) descriptors.next(); - _descriptorCache.addDescriptor(descriptor.getClass().getName(), descriptor); - } - _strategy.setProperty(ResolverStrategy.PROPERTY_MAPPING_LOADER, _mappingLoader); - } - } //-- setMappingLoader - - /** - * {@inheritDoc} - */ public void addClass(final String className) throws ResolverException { this.resolve(className); } @@ -329,7 +334,13 @@ * {@inheritDoc} */ public void addPackage(final String packageName) throws ResolverException { - _strategy.resolvePackage(_descriptorCache, packageName); + if (packageName == null || packageName.length() == 0) { + String message = "Cannot resolve a null or zero-length package name."; + LOG.warn(message); + throw new IllegalArgumentException(message); + } + + getResolverStrategy().resolvePackage(_descriptorCache, packageName); } /** @@ -350,6 +361,23 @@ LOG.warn(message); throw new UnsupportedOperationException(); } + + /** + * To set all strategy properties to the values of the attributes of this instance. + * Only exception is the class loader property which is always set in the resolve method. + */ + private void setAttributesIntoStrategy() { + ResolverStrategy strategy = _internalContext.getResolverStrategy(); + strategy.setProperty( + ResolverStrategy.PROPERTY_LOAD_PACKAGE_MAPPINGS, + _internalContext.getLoadPackageMapping()); + strategy.setProperty( + ResolverStrategy.PROPERTY_USE_INTROSPECTION, _internalContext.getUseIntrospector()); + strategy.setProperty( + ResolverStrategy.PROPERTY_MAPPING_LOADER, _internalContext.getMappingLoader()); + strategy.setProperty( + ResolverStrategy.PROPERTY_INTROSPECTOR, _internalContext.getIntrospector()); + } /** * Internal cache for XMLClassDescriptors.
@@ -366,9 +394,9 @@ * @author Steven Dolg */ private static class DescriptorCacheImpl implements ResolverStrategy.ResolverResults { - + /** Logger to be used by DescriptorCache. */ private static final Log LOG2 = LogFactory.getLog(DescriptorCacheImpl.class); - + /** Some fixed text to detect errors... */ private static final String INTERNAL_CONTAINER_NAME = "-error-if-this-is-used-"; /** List of class names a descriptor is not available for. */ @@ -428,7 +456,8 @@ } if (LOG2.isDebugEnabled()) { - LOG2.debug("Adding descriptor class for: " + className + " descriptor: " + descriptor); + LOG2.debug("Adding descriptor class for: " + + className + " descriptor: " + descriptor); } _typeMap.put(className, descriptor); @@ -447,6 +476,7 @@ if (!descriptorList.contains(descriptor)) { descriptorList.add(descriptor); } + _missingTypes.remove(className); } //-- addDescriptor /** @@ -457,7 +487,9 @@ * if no descriptor is stored in this cache. */ public XMLClassDescriptor getDescriptor(final String className) { - if ((className == null) || ("".equals(className)) || (_missingTypes.contains(className))) { + if ((className == null) + || ("".equals(className)) + || (_missingTypes.contains(className))) { return null; } @@ -539,7 +571,7 @@ /** * To add not only a single descriptor but a map of descriptors at once. * - * @param descriptor a Map of className (String) and XMLClassDescriptor pairs + * @param descriptors a Map of className (String) and XMLClassDescriptor pairs */ public void addAllDescriptors(final Map descriptors) { if ((descriptors == null) || (descriptors.isEmpty())) { @@ -547,10 +579,18 @@ return; } - for (Iterator iter = descriptors.keySet().iterator(); iter.hasNext();) { + for (Iterator iter = descriptors.keySet().iterator(); iter.hasNext(); ) { String clsName = (String) iter.next(); - this.addDescriptor(clsName, (XMLClassDescriptor)descriptors.get(clsName)); + this.addDescriptor(clsName, (XMLClassDescriptor) descriptors.get(clsName)); } } //-- addAllDescriptors } // -- DescriptorCacheImpl + + /** + * Cleans the descriptor cache. + * @see org.exolab.castor.xml.XMLClassDescriptorResolver#cleanDescriptorCache() + */ + public void cleanDescriptorCache() { + _descriptorCache = new DescriptorCacheImpl(); + } } // -- ClassDescriptorResolverImpl Index: src/main/java/org/exolab/castor/types/AnyNode.java =================================================================== --- src/main/java/org/exolab/castor/types/AnyNode.java (revision 7270) +++ src/main/java/org/exolab/castor/types/AnyNode.java (working copy) @@ -51,7 +51,7 @@ import java.io.StringWriter; import java.util.Stack; -import org.exolab.castor.util.LocalConfiguration; +import org.castor.xml.InternalContext; import org.exolab.castor.xml.Serializer; import org.exolab.castor.xml.util.AnyNode2SAX; @@ -530,17 +530,17 @@ * @return the String representation of this AnyNode. */ public String toString() { - Serializer serializer = LocalConfiguration.getInstance().getSerializer(); + Serializer serializer = new InternalContext().getSerializer(); if (serializer == null) { throw new RuntimeException("Unable to obtain serializer"); } StringWriter writer = new StringWriter(); - serializer.setOutputCharStream( writer ); + serializer.setOutputCharStream(writer); try { - AnyNode2SAX.fireEvents(this,serializer.asDocumentHandler()); + AnyNode2SAX.fireEvents(this, serializer.asDocumentHandler()); } catch (java.io.IOException ioe) { return privateToString(); } catch (org.xml.sax.SAXException saxe) { Index: src/main/java/org/exolab/castor/mapping/loader/AbstractMappingLoader.java =================================================================== --- src/main/java/org/exolab/castor/mapping/loader/AbstractMappingLoader.java (revision 7270) +++ src/main/java/org/exolab/castor/mapping/loader/AbstractMappingLoader.java (working copy) @@ -61,6 +61,8 @@ import java.util.Map; import java.util.Properties; + +import org.castor.xml.InternalContext; import org.castor.util.Messages; import org.exolab.castor.mapping.ClassDescriptor; import org.exolab.castor.mapping.CollectionHandler; @@ -130,8 +132,15 @@ /** Factory method name for type-safe enumerations. */ protected static final String VALUE_OF = "valueOf"; + /** + * The {@link InternalContext} is the centerpiece providing runtime configuration + * and state information. + */ + private InternalContext _internalContext; + /** Map of field handlers associated by their name. */ private final Map _fieldHandlers = new HashMap(); + //-------------------------------------------------------------------------- /** @@ -1202,4 +1211,12 @@ public TypeInfo typeInfo = null; } + public void setInternalContext(final InternalContext internalContext) { + _internalContext = internalContext; + } + + public InternalContext getInternalContext() { + return _internalContext; + } + } Index: src/main/java/org/exolab/castor/mapping/loader/AbstractMappingLoader2.java =================================================================== --- src/main/java/org/exolab/castor/mapping/loader/AbstractMappingLoader2.java (revision 7270) +++ src/main/java/org/exolab/castor/mapping/loader/AbstractMappingLoader2.java (working copy) @@ -97,6 +97,13 @@ if (!isAllowRedefinition()) { throw new MappingException("mapping.duplicateDescriptors", classname); } + for (Iterator iterator = _descriptors.iterator(); iterator.hasNext(); ) { + ClassDescriptor d = (ClassDescriptor) iterator.next(); + if (classname.equals(d.getJavaClass().getName())) { + _descriptors.remove(d); + } + } + _descriptors.add(descriptor); } else { _descriptors.add(descriptor); } Index: src/main/java/org/exolab/castor/mapping/loader/CollectionHandlers.java =================================================================== --- src/main/java/org/exolab/castor/mapping/loader/CollectionHandlers.java (revision 7270) +++ src/main/java/org/exolab/castor/mapping/loader/CollectionHandlers.java (working copy) @@ -53,6 +53,9 @@ import java.util.StringTokenizer; import java.io.Serializable; import java.lang.reflect.Method; + +import org.castor.core.util.Configuration; +import org.castor.xml.XMLConfiguration; import org.exolab.castor.mapping.MappingException; import org.exolab.castor.mapping.CollectionHandler; import org.exolab.castor.util.LocalConfiguration; @@ -249,8 +252,11 @@ Method method; allInfo = new Vector(); - LocalConfiguration config = LocalConfiguration.getInstance(); - tokenizer = new StringTokenizer( config.getProperty( "org.exolab.castor.mapping.collections", "" ), ", " ); + Configuration configuration = XMLConfiguration.newInstance(); + tokenizer = new StringTokenizer(configuration.getString(XMLConfiguration.COLLECTION_HANDLERS_FOR_JAVA_11_OR_12, ""), ", "); +// Joachim 2007-09-01 old local configuration is dead! +// LocalConfiguration config = LocalConfiguration.getInstance(); +// tokenizer = new StringTokenizer( config.getProperty( "org.exolab.castor.mapping.collections", "" ), ", " ); while ( tokenizer.hasMoreTokens() ) { try { if ( CollectionHandlers.class.getClassLoader() != null ) Index: src/main/java/org/exolab/castor/util/ChangeLog2XML.java =================================================================== --- src/main/java/org/exolab/castor/util/ChangeLog2XML.java (revision 7270) +++ src/main/java/org/exolab/castor/util/ChangeLog2XML.java (working copy) @@ -13,7 +13,10 @@ */ package org.exolab.castor.util; +import org.castor.xml.XMLConfiguration; +import org.castor.xml.InternalContext; import org.exolab.castor.xml.Marshaller; +import org.exolab.castor.xml.XMLContext; import org.exolab.castor.util.Configuration; import org.exolab.castor.util.LocalConfiguration; @@ -52,8 +55,13 @@ private static final String VERSION_SEPARATOR = "---"; private static final String VERSION_TOKEN = "Version"; - /** + * The {@link InternalContext} holding global state and configuration + * information. + */ + private InternalContext _internalContext; + + /** * Creates a new instance of ChangeLog2XML * */ @@ -62,6 +70,14 @@ } /** + * To set the {@link InternalContext} into the ChangeLog2XML instance. + * @param internalContext the context to set + */ + public void setInternalContext(final InternalContext internalContext) { + _internalContext = internalContext; + } + + /** * The method which does the parsing of the CHANGELOG file * * @param file @@ -200,18 +216,20 @@ // 2. mapping file for customization // 3. output file name + XMLContext xmlContext = new XMLContext(); + ChangeLog2XML parser = xmlContext.createChangeLog2XML(); - ChangeLog2XML parser = new ChangeLog2XML(); - try { File file = new File(DEFAULT_FILE); Changelog changelog = parser.parse(file); file = new File(DEFAULT_OUTPUT); FileWriter writer = new FileWriter(file); - LocalConfiguration config = LocalConfiguration.getInstance(); - config.getProperties().setProperty(Configuration.Property.Indent, "true"); - Marshaller marshaller = new Marshaller(writer); + + xmlContext.setProperty(XMLConfiguration.USE_INDENTATION, true); + Marshaller marshaller = xmlContext.createMarshaller(); + marshaller.setWriter(writer); + marshaller.setRootElement("changelog"); marshaller.setSuppressXSIType(true); marshaller.marshal(changelog); Index: src/main/java/org/castor/xml/InternalContext.java =================================================================== --- src/main/java/org/castor/xml/InternalContext.java (revision 0) +++ src/main/java/org/castor/xml/InternalContext.java (revision 0) @@ -0,0 +1,840 @@ +/* + * Copyright 2007 Joachim Grueneis + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.castor.xml; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.castor.core.util.Configuration; +import org.castor.mapping.BindingType; +import org.castor.mapping.MappingUnmarshaller; +import org.castor.util.Messages; +import org.exolab.castor.mapping.Mapping; +import org.exolab.castor.mapping.MappingException; +import org.exolab.castor.mapping.MappingLoader; +import org.exolab.castor.util.RegExpEvaluator; +import org.exolab.castor.xml.Introspector; +import org.exolab.castor.xml.NodeType; +import org.exolab.castor.xml.OutputFormat; +import org.exolab.castor.xml.ResolverException; +import org.exolab.castor.xml.Serializer; +import org.exolab.castor.xml.XMLClassDescriptorResolver; +import org.exolab.castor.xml.XMLNaming; +import org.exolab.castor.xml.XMLSerializerFactory; +import org.exolab.castor.xml.schema.Resolver; +import org.exolab.castor.xml.util.DefaultNaming; +import org.exolab.castor.xml.util.ResolverStrategy; +import org.xml.sax.DocumentHandler; +import org.xml.sax.Parser; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; + +/** + * The internal context is meant as center piece providing (and keeping) all + * information that is required by Marshaller, Unmarshaller, SourceGenerator, + * MappingTool, SchemaReader and SchemaWriter. It is created, filled with + * initial data and put into all other parts of Castor by {@link XMLContext}. + * It is NOT meant to be directly instantiated by user implementations! + * For all other objects it provides access to Castor state information + * (e.g. known descriptors) and configuration values. + * + * @author Joachim Grueneis + * @since 1.1.2 + */ +public class InternalContext { + /** Logger to be used. */ + private static final Log LOG = LogFactory.getFactory().getInstance(InternalContext.class); + + /** The configuration to use internally to provide parser, serializer, ... */ + private org.castor.core.util.Configuration _configuration; + + /** + * {@link XMLClassDescriptorResolver} instance used for caching XML-related + * class descriptors. + */ + private XMLClassDescriptorResolver _xmlClassDescriptorResolver; + + /** + * The XMLContext knows the one Introspector to be used. + */ + private Introspector _introspector; + + /** + * The {@link Resolver} to be used by Schema* stuff. + */ + private Resolver _schemaResolver; + + /** + * The XMLClassDescriptor resolver strategy to use. + */ + private ResolverStrategy _resolverStrategy; + + /** + * The {@link MappingLoader} to use. + */ + private MappingLoader _mappingLoader; + + /** + * The {@link XMLNaming} to be used. + */ + private XMLNaming _xmlNaming; + + /** + * The {@link JavaNaming} to be used. + */ + private JavaNaming _javaNaming; + + /** + * The class loader to use. + */ + private ClassLoader _classLoader; + + /** + * The {@link NodeType} to use for primitives. + */ + private NodeType _primitiveNodeType; + + /** + * The {@link RegExpevaluator} to use. + */ + private RegExpEvaluator _regExpEvaluator; + + /** + * Creates an instance of {@link InternalContext}. The internal context is meant to + * hold the configuration and state informations, but not necessarily retrieving + * those values... + */ + public InternalContext() { + _configuration = XMLConfiguration.newInstance(); + _javaNaming = new JavaNamingImpl(); + } + + /** + * Instructs Castor to load class descriptors from the mapping given. + * @param mapping Castor XML mapping (file), from which the required class + * descriptors will be derived. + * @throws MappingException If the {@link Mapping} cannot be loaded and analyzed successfully. + */ + public void addMapping(final Mapping mapping) throws MappingException { + MappingUnmarshaller mappingUnmarshaller = new MappingUnmarshaller(); + mappingUnmarshaller.setInternalContext(this); + MappingLoader mappingLoader = + mappingUnmarshaller.getMappingLoader(mapping, BindingType.XML); + _xmlClassDescriptorResolver.setMappingLoader(mappingLoader); + } + + /** + * Loads the class descriptor for the class instance specified. The use of this method is useful + * when no mapping is used, as happens when the domain classes has been generated + * using the XML code generator (in which case instead of a mapping file class + * descriptor files will be generated). + * + * @param clazz the class for which the associated descriptor should be loaded. + * @throws ResolverException in case that resolving the Class fails fatally + */ + public void addClass(final Class clazz) throws ResolverException { + _xmlClassDescriptorResolver.addClass(clazz); + } + + /** + * Loads the class descriptor for the class instance specified. The use of this method is useful + * when no mapping is used, as happens when the domain classes hase been generated + * using the XML code generator (in which case instead of a mapping file class + * descriptor files will be generated). + * + * @param clazzes the classes for which the associated descriptor should be loaded. + * @throws ResolverException in case that resolving the Class fails fatally + */ + public void addClasses(final Class[] clazzes) throws ResolverException { + _xmlClassDescriptorResolver.addClasses(clazzes); + } + + /** + * Loads class descriptors from the package specified. The use of this method is useful + * when no mapping is used, as happens when the domain classes hase been generated + * using the XML code generator (in which case instead of a mapping file class + * descriptor files will be generated). + *

+ * Please note that this functionality will work only if you provide the .castor.cdr + * file with your generated classes (as generated by the XML code generator). + *

+ * @param packageName The package name for the (descriptor) classes + * @throws ResolverException + * If there's a problem loading class descriptors for the given package. + */ + public void addPackage(final String packageName) throws ResolverException { + _xmlClassDescriptorResolver.addPackage(packageName); + } + + /** + * Loads class descriptors from the packages specified. The use of this method is useful + * when no mapping is used, as happens when the domain classes hase been generated + * using the XML code generator (in which case instead of a mapping file class + * descriptor files will be generated). + *

+ * Please note that this functionality will work only if you provide the .castor.cdr + * files with your generated classes (as generated by the XML code generator). + *

+ * @param packageNames The package names for the (descriptor) classes + * @throws ResolverException + * If there's a problem loading class descriptors for the given package. + */ + public void addPackages(final String[] packageNames) throws ResolverException { + _xmlClassDescriptorResolver.addPackages(packageNames); + } + + /** + * Sets an application-specific {@link XMLClassDescriptorResolver} instance. + * @param xmlClassDescriptorResolver the resolver to use + */ + public void setResolver(final XMLClassDescriptorResolver xmlClassDescriptorResolver) { + this._xmlClassDescriptorResolver = xmlClassDescriptorResolver; + } + + /** + * To set properties for marshalling and unmarshalling behavior. + * @param propertyName name of the property to set + * @param value the value to set to + */ + public void setProperty(final String propertyName, final Object value) { + _configuration.put(propertyName, value); + } + + /** + * To get the value of a specific property. + * @param propertyName name of the Property + * @return the value (Object) of the property + */ + public Object getProperty(final String propertyName) { + return _configuration.getObject(propertyName); + } + + /** + * Returns the naming conventions to use for the XML framework. + * + * @return the naming conventions to use for the XML framework + */ + public XMLNaming getXMLNaming() { + return getXMLNaming(null); + } + + /** + * Returns the naming conventions to use for the XML framework. + * @param classLoader the class loader to be used when instantiating a new naming instance + * @return the naming conventions to use for the XML framework + * @TODO: Joachim should be synchronized, shouldn't it be?? + */ + public XMLNaming getXMLNaming(final ClassLoader classLoader) { + + if (_xmlNaming != null) { + return _xmlNaming; + } + + String prop = _configuration.getString(XMLConfiguration.XML_NAMING, null); + if ((prop == null) || (prop.equalsIgnoreCase("lower"))) { + _xmlNaming = new DefaultNaming(); + } else if (prop.equalsIgnoreCase("mixed")) { + DefaultNaming dn = new DefaultNaming(); + dn.setStyle(DefaultNaming.MIXED_CASE_STYLE); + _xmlNaming = dn; + } else { + try { + Class cls = null; + if (classLoader != null) { + cls = classLoader.loadClass(prop); + } else { + cls = Class.forName(prop); + } + _xmlNaming = (XMLNaming) cls.newInstance(); + } catch (Exception e) { + throw new RuntimeException("Failed to load XMLNaming: " + e); + } + } + return _xmlNaming; + } //-- getXMLNaming + + /** + * The {@link JavaNaming} instance to be used. + * @return {@link JavaNaming} instance to be used. + */ + public JavaNaming getJavaNaming() { + return _javaNaming; + } + + /** + * Return an XML document parser implementing the feature list + * specified in the configuration file. + * + * @return A suitable XML parser + */ + public Parser getParser() { + return getParser(null); + } + + /** + * Returns an XML document parser implementing the requested + * set of features. The feature list is a comma separated list + * of features that parser may or may not support. No errors are + * generated for unsupported features. If the feature list is not + * null, it overrides the default feature list specified in the + * configuration file, including validation and Namespaces. + * + * @param features The requested feature list, null for the + * defaults + * @return A suitable XML parser + */ + public Parser getParser(final String features) { + Parser parser = null; + Boolean validation = _configuration.getBoolean(XMLConfiguration.PARSER_VALIDATION); + Boolean namespaces = _configuration.getBoolean(XMLConfiguration.NAMESPACES); + String parserClassName = _configuration.getString(XMLConfiguration.PARSER); + if ((parserClassName == null) || (parserClassName.length() == 0)) { + SAXParser saxParser = getSAXParser(validation, namespaces); + if (saxParser != null) { + try { + parser = saxParser.getParser(); + } catch (SAXException e) { + LOG.error(Messages.format("conf.configurationError", e)); + } + } + } + + if (parser == null) { + if ((parserClassName == null) + || (parserClassName.length() == 0) + || (parserClassName.equalsIgnoreCase("xerces"))) { + parserClassName = "org.apache.xerces.parsers.SAXParser"; + } + // If a parser class was specified, we try to create it and + // complain about creation error. + try { + Class cls; + cls = Class.forName(parserClassName); + parser = (Parser) cls.newInstance(); + } catch (Exception except) { + throw new RuntimeException(Messages + .format("conf.failedInstantiateParser", parserClassName, except)); + } + + if (parser instanceof XMLReader) { + XMLReader xmlReader = (XMLReader) parser; + new XMLReaderService().setFeaturesOnXmlReader( + _configuration.getString(XMLConfiguration.PARSER_FEATURES, features), + _configuration.getString(XMLConfiguration.PARSER_FEATURES_DISABLED, ""), + validation.booleanValue(), + namespaces.booleanValue(), + xmlReader); + } + } + return parser; + } + + /** + * Returns an XML document parser implementing the requested set of + * features. The feature list is a comma separated list of features that + * parser may or may not support. No errors are generated for unsupported + * features. If the feature list is not null, it overrides the default + * feature list specified in the configuration file, including validation + * and Namespaces. + * + * @return A suitable XML parser + */ + public XMLReader getXMLReader() { + return getXMLReader(null); + } //-- getXMLReader + + /** + * Returns an XML document parser implementing the requested + * set of features. The feature list is a comma separated list + * of features that parser may or may not support. No errors are + * generated for unsupported features. If the feature list is not + * null, it overrides the default feature list specified in the + * configuration file, including validation and Namespaces. + * + * @param features the name of feature to set + * @return A suitable XML parser + */ + public XMLReader getXMLReader(final String features) { + XMLReader reader = null; + Boolean validation = _configuration.getBoolean(XMLConfiguration.PARSER_VALIDATION); + Boolean namespaces = _configuration.getBoolean(XMLConfiguration.NAMESPACES); + String readerClassName = _configuration.getString(XMLConfiguration.PARSER); + if ((readerClassName == null) || (readerClassName.length() == 0)) { + SAXParser saxParser = getSAXParser(validation, namespaces); + if (saxParser != null) { + try { + reader = saxParser.getXMLReader(); + } catch (SAXException e) { + LOG.error(Messages.format("conf.configurationError", e)); + } + } + } + + if (reader == null) { + if ((readerClassName == null) + || (readerClassName.length() == 0) + || (readerClassName.equalsIgnoreCase("xerces"))) { + readerClassName = "org.apache.xerces.parsers.SAXParser"; + } + + + // If a parser class was specified, we try to create it and + // complain about creation error. + try { + Class cls; + + cls = Class.forName(readerClassName); + reader = (XMLReader) cls.newInstance(); + } catch (Exception e) { + throw new RuntimeException( + Messages.format("conf.failedInstantiateParser", readerClassName, e)); + } + } + + new XMLReaderService().setFeaturesOnXmlReader( + _configuration.getString(XMLConfiguration.PARSER_FEATURES, features), + _configuration.getString(XMLConfiguration.PARSER_FEATURES_DISABLED, ""), + validation.booleanValue(), + namespaces.booleanValue(), + reader); + + return reader; + + } //-- getXMLReader + + /** + * To get a SAXParser instance which is then used to get either + * parser or XMLReader. + * @param validation validation flag to set into parser factory + * @param namespaces namespace flag to set into parser factory + * @return the SAXParser for further use + */ + private SAXParser getSAXParser(final Boolean validation, final Boolean namespaces) { + SAXParser saxParser = null; + + // If no parser class was specified, check for JAXP + // otherwise we default to Xerces. + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setNamespaceAware(namespaces.booleanValue()); + factory.setValidating(validation.booleanValue()); + try { + saxParser = factory.newSAXParser(); + } catch (ParserConfigurationException pcx) { + LOG.error(Messages.format("conf.configurationError", pcx)); + } catch (org.xml.sax.SAXException sx) { + LOG.error(Messages.format("conf.configurationError", sx)); + } + return saxParser; + } + + /** + * Returns the NodeType to use for Java primitives. + * A null value will be returned if no NodeType was specified, + * indicating the default NodeType should be used. + * + * @return the NodeType assigned to Java primitives, or null + * if no NodeType was specified. + **/ + public NodeType getPrimitiveNodeType() { + + if (_primitiveNodeType != null) { + return _primitiveNodeType; + } + + String prop = _configuration.getString(XMLConfiguration.PRIMITIVE_NODE_TYPE, null); + if (prop == null) { + return null; + } + _primitiveNodeType = NodeType.getNodeType(prop); + return _primitiveNodeType; + } //-- getPrimitiveNodeType + + /** + * Returns a new instance of the specified Regular Expression + * Evaluator, or null if no validator was specified. + * + * @return the regular expression evaluator, + * + **/ + public RegExpEvaluator getRegExpEvaluator() { + if (_regExpEvaluator != null) { + return _regExpEvaluator; + } + + String regExpEvalClassName = _configuration.getString(XMLConfiguration.REG_EXP_CLASS_NAME); + if ((regExpEvalClassName == null) || (regExpEvalClassName.length() == 0)) { + _regExpEvaluator = null; + } else { + try { + Class regExpEvalClass = Class.forName(regExpEvalClassName); + _regExpEvaluator = (RegExpEvaluator) regExpEvalClass.newInstance(); + } catch (ClassNotFoundException e) { + throw new RuntimeException( + Messages.format("conf.failedInstantiateRegExp", regExpEvalClassName, e)); + } catch (InstantiationException e) { + throw new RuntimeException( + Messages.format("conf.failedInstantiateRegExp", regExpEvalClassName, e)); + } catch (IllegalAccessException e) { + throw new RuntimeException( + Messages.format("conf.failedInstantiateRegExp", regExpEvalClassName, e)); + } + } + return _regExpEvaluator; + } // -- getRegExpEvaluator + + /** + * Returns a default serializer for producing an XML document. The caller + * can specify an alternative output format, may reuse this serializer + * across several streams, and may serialize both DOM and SAX events. If + * such control is not required, it is recommended to call one of the other + * two methods. + * + * @return A suitable serializer + */ + public Serializer getSerializer() { + Serializer serializer = getSerializerFactory( + _configuration.getString( + XMLConfiguration.SERIALIZER_FACTORY)).getSerializer(); + serializer.setOutputFormat(getOutputFormat()); + return serializer; + } + /** + * Returns the default OutputFormat for use with a Serializer. + * + * @return the default OutputFormat + **/ + public OutputFormat getOutputFormat() { + + boolean indent = _configuration.getBoolean(XMLConfiguration.USE_INDENTATION, false); + + OutputFormat format = getSerializerFactory( + _configuration.getString( + XMLConfiguration.SERIALIZER_FACTORY)) + .getOutputFormat(); + format.setMethod(OutputFormat.XML); + format.setIndenting(indent); + + // There is a bad interaction between the indentation and the + // setPreserveSpace option. The indentated output is strangely indented. + if (!indent) { + format.setPreserveSpace(true); + } + + return format; + } //-- getOutputFormat + + /** + * Returns the currently configured XMLSerializerFactory instance. + * @param serializerFactoryName the class name of the serializer factory + * @return XMLSerializerFactory to use by Castor + */ + protected XMLSerializerFactory getSerializerFactory(final String serializerFactoryName) { + XMLSerializerFactory serializerFactory; + + try { + serializerFactory = (XMLSerializerFactory) + Class.forName(serializerFactoryName).newInstance(); + } catch (Exception except) { + throw new RuntimeException( + Messages.format("conf.failedInstantiateSerializerFactory", + serializerFactoryName, except)); + } + return serializerFactory; + } + + /** + * Returns a default serializer for producing an XML document to + * the designated output stream using the default serialization + * format. + * + * @param output The output stream + * @return A suitable serializer + * @throws IOException if instantiation of the serializer fails + */ + public DocumentHandler getSerializer(final OutputStream output) throws IOException { + Serializer serializer; + DocumentHandler docHandler; + + serializer = getSerializer(); + serializer.setOutputByteStream(output); + docHandler = serializer.asDocumentHandler(); + if (docHandler == null) { + throw new RuntimeException(Messages.format("conf.serializerNotSaxCapable", serializer + .getClass().getName())); + } + return docHandler; + } + + + /** + * Returns a default serializer for producing an XML document to the + * designated output stream using the default serialization format. + * + * @param output + * The output stream + * @return A suitable serializer + * @throws IOException if instantiation of serializer fails + */ + public DocumentHandler getSerializer(final Writer output) throws IOException { + Serializer serializer; + DocumentHandler docHandler; + + serializer = getSerializer(); + serializer.setOutputCharStream(output); + docHandler = serializer.asDocumentHandler(); + if (docHandler == null) { + throw new RuntimeException(Messages.format("conf.serializerNotSaxCapable", serializer + .getClass().getName())); + } + return docHandler; + } + + /** + * To get the XMLClassdescriptorResolver instance hold in the context. + * @return the XMLClassdescriptorResolver instance hold in the context + */ + public XMLClassDescriptorResolver getXMLClassDescriptorResolver() { + return _xmlClassDescriptorResolver; + } + + /** + * To get the Introspector assigned to this XMLContext. + * @return the Introspector assigned to this XMLContext + */ + public Introspector getIntrospector() { + return _introspector; + } + + /** + * To set the {@link Resolver} for Schema*. + * @param schemaResolver the {@link Resolver} for Schema* + */ + public void setSchemaResolver(final Resolver schemaResolver) { + _schemaResolver = schemaResolver; + } + + /** + * To get the {@link Resolver} to use in Schema*. + * @return get the {@link Resolver} to use in Schema* + */ + public Resolver getSchemaResolver() { + return _schemaResolver; + } + + /** + * To get the XMLClassDescriptor resolver strategy to be used when + * resolving classes into class descriptors. + * @return the ResolverStrategy to use + */ + public ResolverStrategy getResolverStrategy() { + return _resolverStrategy; + } + + /** + * To set the XMLClassDescriptor resolver strategy to be used. + * @param resolverStrategy the ResolverStrategy to use + */ + public void setResolverStrategy(final ResolverStrategy resolverStrategy) { + _resolverStrategy = resolverStrategy; + } + + /** + * To set the {@link MappingLoader} to be used in this Castor session. + * @param mappingLoader the {@link MappingLoader} to use + */ + public void setMappingLoader(final MappingLoader mappingLoader) { + _mappingLoader = mappingLoader; + } + + /** + * To get the {@link MappingLoader} specified to be used in this Castor session. + * @return the {@link MappingLoader} to use + */ + public MappingLoader getMappingLoader() { + return _mappingLoader; + } + + /** + * To set the {@link JavaNaming} property. + * @param javaNaming the {@link JavaNaming} to use + */ + public void setJavaNaming(final JavaNaming javaNaming) { + _javaNaming = javaNaming; + } + + /** + * To set any boolean property. + * @param propertyName name of the property to set + * @param value boolean value to set + */ + public void setProperty(final String propertyName, final boolean value) { + _configuration.put(propertyName, new Boolean(value)); + } + + /** + * Providing access to Boolean properties of the configuration. + * @param propertyName name of the property + * @return null if property is not set or whichever value is set + */ + public Boolean getBooleanProperty(final String propertyName) { + return _configuration.getBoolean(propertyName); + } + + /** + * Providing access to String properties of the configuration. + * @param propertyName name of the property + * @return null if the property is not set or whichever value is set + */ + public String getStringProperty(final String propertyName) { + return _configuration.getString(propertyName); + } + + /** + * To set the class loader to be used in all further marshalling, unmarshalling + * and other actions. + * @param classLoader the ClassLoader instance to use + */ + public void setClassLoader(final ClassLoader classLoader) { + _classLoader = classLoader; + } + + /** + * To set the {@link XMLClassDescriptorResolver} to be used. Be aware, that the + * XMLClassDescriptorResolver instance holds a descriptor cache!! Maybe change it + * to have the descriptor cache as part of the context? + * @param xmlClassDescriptorResolver the {@link XMLClassDescriptorResolver} to use + */ + public void setXMLClassDescriptorResolver( + final XMLClassDescriptorResolver xmlClassDescriptorResolver) { + _xmlClassDescriptorResolver = xmlClassDescriptorResolver; + } + + /** + * To specify which {@link Introspector} is to be used. + * @param introspector {@link Introspector} to be used + */ + public void setIntrospector(final Introspector introspector) { + _introspector = introspector; + } + + /** + * To get the ClassLoader to use for loading resources. + * @return the ClassLoader to use + */ + public ClassLoader getClassLoader() { + return _classLoader; + } + + /** + * Get lenient id validation flag. + * @return lenient id validation flag + */ + public boolean getLenientIdValidation() { + Boolean lenientIdValidation = + _configuration.getBoolean(XMLConfiguration.LENIENT_ID_VALIDATION); + if (lenientIdValidation == null) { + String message = "Property lenientIdValidation must not be null"; + LOG.warn(message); + throw new IllegalStateException(message); + } + return lenientIdValidation.booleanValue(); + } + + /** + * Get lenient sequence order flag. + * @return lenient sequence order flag + */ + public boolean getLenientSequenceOrder() { + Boolean lenientSequenceOrder = + _configuration.getBoolean(XMLConfiguration.LENIENT_SEQUENCE_ORDER); + if (lenientSequenceOrder == null) { + String message = "Property lenientSequenceOrder must not be null"; + LOG.warn(message); + throw new IllegalStateException(message); + } + return lenientSequenceOrder.booleanValue(); + } + + /** + * Get load package mapping flag. + * @return load package mapping flag + */ + public Boolean getLoadPackageMapping() { + return _configuration.getBoolean(XMLConfiguration.LOAD_PACKAGE_MAPPING); + } + + /** + * To set the load package mapping flag. + * @param loadPackageMapping the load package mapping flag + */ + public void setLoadPackageMapping(final Boolean loadPackageMapping) { + _configuration.put(XMLConfiguration.LOAD_PACKAGE_MAPPING, loadPackageMapping); + } + + /** + * To get use-introspection flag. + * @return use-introspection flag + */ + public Boolean getUseIntrospector() { + return _configuration.getBoolean(XMLConfiguration.USE_INTROSPECTION); + } + + /** + * To set use-introspection flag. + * @param useIntrospector use-introspection flag + */ + public void setUseIntrospector(final Boolean useIntrospector) { + _configuration.put(XMLConfiguration.USE_INTROSPECTION, useIntrospector); + } + + /** + * To get marshalling-validation flag. + * @return marshalling-validation flag + */ + public boolean marshallingValidation() { + Boolean marshallingValidation = + _configuration.getBoolean(XMLConfiguration.MARSHALLING_VALIDATION); + if (marshallingValidation == null) { + String message = "Property marshallingValidation must not be null"; + LOG.warn(message); + throw new IllegalStateException(message); + } + return marshallingValidation.booleanValue(); + } + + /** + * To get strict-element flag. + * @return strict-element flag + */ + public boolean strictElements() { + Boolean strictElements = + _configuration.getBoolean(XMLConfiguration.STRICT_ELEMENTS); + if (strictElements == null) { + String message = "Property strictElements must not be null"; + LOG.warn(message); + throw new IllegalStateException(message); + } + return strictElements.booleanValue(); + } + +} Index: src/main/java/org/castor/xml/XMLReaderService.java =================================================================== --- src/main/java/org/castor/xml/XMLReaderService.java (revision 0) +++ src/main/java/org/castor/xml/XMLReaderService.java (revision 0) @@ -0,0 +1,87 @@ +package org.castor.xml; + +import java.util.StringTokenizer; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.castor.util.Messages; +import org.xml.sax.SAXException; +import org.xml.sax.SAXNotRecognizedException; +import org.xml.sax.SAXNotSupportedException; +import org.xml.sax.XMLReader; + +/** + * A couple of routines to manipulate XMLReader instances. Mostly extracted + * from 'old' LocalConfiguration class. + * + * @author Joachim Grueneis, jgrueneis_at_gmail_dot_com + * @version $Id$ + */ +public class XMLReaderService { + /** Logger to be used. */ + static final Log LOG = LogFactory.getFactory().getInstance(XMLReaderService.class); + /** To set validation feature of XMLReader. */ + private static final String VALIDATION = "http://xml.org/sax/features/validation"; + /** To set namespaces feature of XMLReader. */ + private static final String NAMESPACES = "http://xml.org/sax/features/namespaces"; + + /** + * Sets features on XML reader instance. + * @param properties the Properties to read parser features from + * @param defaultFeatures any default features to use + * @param validation Whether to enable validation or not. + * @param namespaces Whether to enable namespace support for not. + * @param xmlReader The XMLReader instance to configure. + */ + protected void setFeaturesOnXmlReader( + final String parserFeatures, + final String parserFeaturesToDisable, + final boolean validation, + final boolean namespaces, + final XMLReader xmlReader) { + try { + xmlReader.setFeature(VALIDATION, validation); + xmlReader.setFeature(NAMESPACES, namespaces); + enableFeatures(parserFeatures, xmlReader); + disableFeatures(parserFeaturesToDisable, xmlReader); + } catch (SAXException except) { + LOG.error(Messages.format("conf.configurationError", except)); + } + } + + /** + * Enables selected features on the XMLReader instance. + * @param features Features to enable + * @param xmlReader XMLReader instance to be configured. + * @throws SAXNotRecognizedException If the feature is not recognized by the XMLReader. + * @throws SAXNotSupportedException If the feature is not supported by the XMLReader. + */ + private void enableFeatures(final String features, final XMLReader xmlReader) + throws SAXNotRecognizedException, SAXNotSupportedException { + StringTokenizer token; + if (features != null) { + token = new StringTokenizer(features, ", "); + while (token.hasMoreTokens()) { + xmlReader.setFeature(token.nextToken(), true); + } + } + } + + /** + * Disables selected features on the XMLReader instance. + * @param features Features to disable + * @param xmlReader XMLReader instance to be configured. + * @throws SAXNotRecognizedException If the feature is not recognized by the XMLReader. + * @throws SAXNotSupportedException If the feature is not supported by the XMLReader. + */ + private void disableFeatures(final String features, final XMLReader xmlReader) + throws SAXNotRecognizedException, SAXNotSupportedException { + StringTokenizer token; + if (features != null) { + token = new StringTokenizer(features, ", "); + while (token.hasMoreTokens()) { + xmlReader.setFeature(token.nextToken(), false); + } + } + } +} \ No newline at end of file Index: src/main/java/org/castor/xml/XMLConfiguration.java =================================================================== --- src/main/java/org/castor/xml/XMLConfiguration.java (revision 7270) +++ src/main/java/org/castor/xml/XMLConfiguration.java (working copy) @@ -17,13 +17,9 @@ */ package org.castor.xml; -import java.util.Hashtable; -import java.util.Map; - import org.castor.core.CoreConfiguration; import org.castor.core.util.CastorConfiguration; import org.castor.core.util.Configuration; -import org.xml.sax.SAXException; /** * Castor configuration of XML modul. @@ -176,7 +172,7 @@ "org.exolab.castor.parser.namespaces"; /** - * Property specifying XML namespace to Java package mappings + * Property specifying XML namespace to Java package mappings. * *

      * org.exolab.castor.xml.nspackages
@@ -313,7 +309,7 @@
       * 
*/ public static final String STRICT_ELEMENTS = "org.exolab.castor.xml.strictelements"; - + /** * Property specifying whether or not to save the "keys" of a {@link Hashtable} or * {@link Map} during marshalling. By default this is true. @@ -410,11 +406,11 @@ /** * Property specifying whether element strictness for introspected classes/elements - * should be lenient (aka allowed); defaults to true + * should be lenient (aka allowed); defaults to true. * * Possible values: * - false - * - tre (default) + * - true (default) * *
       * org.exolab.castor.xml.lenient.introspected.element.strictness=true
@@ -425,5 +421,56 @@
      public static final String LENIENT_INTROSPECTED_ELEMENT_STRICTNESS = 
          "org.exolab.castor.xml.lenient.introspected.element.strictness";
 
+     /**
+      * Property specifying which collections handlers should be used for
+      * Java 1.1 and Java 1.2 run-times.
+      * 
+      * 
+      * org.exolab.castor.mapping.collections
+      * 
+ */ + public static final String COLLECTION_HANDLERS_FOR_JAVA_11_OR_12 = + "org.exolab.castor.mapping.collections"; + /** + * Property specifying if introspection should be used at class resolving. + * + *
+     * org.castor.xml.class-resolver.use-introspection
+     * 
+ */ + public static final String USE_INTROSPECTION + = "org.castor.xml.class-resolver.use-introspection"; + + /** + * The property name for enabling collection wrapping. + * The property controls whether or not collections + * (arrays, vectors, etc) should be wrapped in a container element. + * For example: + * + *
+     *    <foos>
+     *       <foo>foo1</foo>
+     *       <foo>foo2</foo>
+     *    </foos>
+     *
+     *   instead of the default:
+     *
+     *    <foos>foo1<foos>
+     *    <foos>foo2</foos>
+     *
+     * 
+ * + * Use this property with a value of true or false in the + * castor.properties file + * + * org.exolab.castor.xml.introspector.wrapCollections=true + * -or- + * org.exolab.castor.xml.introspector.wrapCollections=false + * + * This property is false by default. + */ + public static final String WRAP_COLLECTIONS_PROPERTY = + "org.exolab.castor.xml.introspector.wrapCollections"; + } Index: src/main/java/org/castor/xml/BackwardCompatibilityContext.java =================================================================== --- src/main/java/org/castor/xml/BackwardCompatibilityContext.java (revision 0) +++ src/main/java/org/castor/xml/BackwardCompatibilityContext.java (revision 0) @@ -0,0 +1,59 @@ +/* + * Copyright 2007 Joachim Grueneis + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.castor.xml; + +import org.castor.mapping.BindingType; +import org.exolab.castor.xml.ClassDescriptorResolverFactory; +import org.exolab.castor.xml.Introspector; +import org.exolab.castor.xml.XMLClassDescriptorResolver; +import org.exolab.castor.xml.schema.Resolver; +import org.exolab.castor.xml.schema.ScopableResolver; +import org.exolab.castor.xml.util.ResolverStrategy; +import org.exolab.castor.xml.util.resolvers.CastorXMLStrategy; + +/** + * As the name already expresses: this class is there for backward compatibility + * and should be removed from Castor with release 1.4 or such. Normally the + * internal context is created by XMLContext exclusivly and then handed down + * the call chain... this class is used in all cases which fail to be on a call + * chain started with XMLContext. + * + * @author Joachim Grueneis, jgrueneis_at_gmail_dot_com + * @version $Id$ + */ +public class BackwardCompatibilityContext extends InternalContext { + /** + * Initializes InternalContext with default values. + */ + public BackwardCompatibilityContext() { + setClassLoader(getClass().getClassLoader()); + + XMLClassDescriptorResolver cdr = (XMLClassDescriptorResolver) ClassDescriptorResolverFactory + .createClassDescriptorResolver(BindingType.XML); + cdr.setInternalContext(this); + setXMLClassDescriptorResolver(cdr); + + Introspector introspector = new Introspector(); + introspector.setInternalContext(this); + setIntrospector(introspector); + + ResolverStrategy resolverStrategy = new CastorXMLStrategy(); + setResolverStrategy(resolverStrategy); + + Resolver schemaResolver = new ScopableResolver(); + setSchemaResolver(schemaResolver); + } +} Index: src/main/java/org/castor/core/util/Configuration.java =================================================================== --- src/main/java/org/castor/core/util/Configuration.java (revision 7270) +++ src/main/java/org/castor/core/util/Configuration.java (working copy) @@ -66,10 +66,7 @@ * used to load the Configuration class. No parent configuration will be set. */ protected Configuration() { - _applicationClassLoader = getClass().getClassLoader(); - _domainClassLoader = getClass().getClassLoader(); - - _parent = null; + this(null, null); } /** @@ -80,8 +77,8 @@ * @param domain Classloader to be used for all domain objects. */ protected Configuration(final ClassLoader app, final ClassLoader domain) { - _applicationClassLoader = app; - _domainClassLoader = domain; + _applicationClassLoader = (app != null) ? app : getClass().getClassLoader(); + _domainClassLoader = (domain != null) ? domain : getClass().getClassLoader(); _parent = null; } Index: src/main/java/org/castor/mapping/MappingUnmarshaller.java =================================================================== --- src/main/java/org/castor/mapping/MappingUnmarshaller.java (revision 7270) +++ src/main/java/org/castor/mapping/MappingUnmarshaller.java (working copy) @@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.castor.core.CoreConfiguration; import org.castor.util.Messages; +import org.castor.xml.InternalContext; import org.exolab.castor.mapping.Mapping; import org.exolab.castor.mapping.MappingException; import org.exolab.castor.mapping.MappingLoader; @@ -57,6 +58,12 @@ /** A flag that indicates of whether or not to allow redefinitions of class * mappings. */ private boolean _allowRedefinitions = false; + + /** + * The {@link InternalContext} holds all 'global' Castor states and access to + * configuration. + */ + private InternalContext _internalContext; //-------------------------------------------------------------------------- @@ -129,6 +136,7 @@ "CastorXmlMapping", bindingType); loader.setClassLoader(mapping.getClassLoader()); loader.setAllowRedefinitions(_allowRedefinitions); + loader.setInternalContext(_internalContext); loader.loadMapping(mapping.getRoot(), param); return loader; } @@ -251,5 +259,13 @@ } } + /** + * To set the internal context. + * @param internalContext the {@link InternalContext} to use + */ + public void setInternalContext(final InternalContext internalContext) { + _internalContext = internalContext; + } + //-------------------------------------------------------------------------- } Index: src/main/resources/org/castor/xml/castor.xml.properties =================================================================== --- src/main/resources/org/castor/xml/castor.xml.properties (revision 7270) +++ src/main/resources/org/castor/xml/castor.xml.properties (working copy) @@ -71,6 +71,18 @@ # org.exolab.castor.marshalling.validation=true +# Property specifying whether XML documents (as generated at marshalling) +# should use indentation or not. +# +# Possible values: +# - false (default) +# - true +# +#
+# org.exolab.castor.indent
+# 
+org.exolab.castor.indent=false + # Comma separated list of SAX 2 features that should be enabled for the # default parser. # @@ -119,7 +131,7 @@ # unmarshalling. Default is true which means that elements appearing in the # XML document, which cannot be mapped to a class, cause a {@link SAXException} # to be thrown. If set to false, these 'unknown' elements are ignored. -# org.exolab.castor.xml.strictelements=false +org.exolab.castor.xml.strictelements=false # Property specifying whether element strictness for introspected # classes/elements should be lenient (aka allowed); defaults to true @@ -128,10 +140,56 @@ # ****************************************************** # This section defines backwards compatibility switches. # ****************************************************** - + +# Property specifying whether or not to save the "keys" of a {@link Hashtable} or +# {@link Map} during marshalling. By default this is true. # -# Hashtable/Map default mapping (0.9.5.2 and earlier). -# Default: true; to switch back to pre-0.9.5.2 behavior, set to 'false' +# Possible values: +# - false +# - true (default) # +#
+# org.exolab.castor.xml.saveMapKeys
+# 
+# +# @since 0.9.5.3 +# org.exolab.castor.xml.saveMapKeys=true +# Property specifying if introspection should be used at class resolving. +# +#
+# org.castor.xml.class-resolver.use-introspection
+# 
+# +org.castor.xml.class-resolver.use-introspection=true + +# The property name for enabling collection wrapping. +# The property controls whether or not collections +# (arrays, vectors, etc) should be wrapped in a container element. +# For example: +# +#
+#    <foos>
+#       <foo>foo1</foo>
+#       <foo>foo2</foo>
+#    </foos>
+#
+#   instead of the default:
+#
+#    <foos>foo1<foos>
+#    <foos>foo2</foos>
+#
+# 
+# +# Use this property with a value of true or false in the +# castor.properties file +# +# org.exolab.castor.xml.introspector.wrapCollections=true +# -or- +# org.exolab.castor.xml.introspector.wrapCollections=false +# +# This property is false by default. +# +org.exolab.castor.xml.introspector.wrapCollections=false + Index: src/doc/release-notes.xml =================================================================== --- src/doc/release-notes.xml (revision 7270) +++ src/doc/release-notes.xml (working copy) @@ -181,7 +181,43 @@ Having said that this should not change anything for the user of Castor as he still specifies his properties in a single castor.properties file for all moduls.

- + +

Refactored JavaNaming

+ +

New JavaNaming is an exchangeable service instantiated trough XMLContext + and accessed in a non-static way. +

+ +

Refactored XMLClassDescriptorResolver

+ +

New XMLClassDescriptorResolver internally works with strategy and command + pattern to have the possibility to enhance class resolving for future + implementations (e.g. JAXB support). +

+ +

Refactored XMLContext

+ +

New XMLContext is the information centerpiece and point to start for Castor + XML stuff. It provides: +

    +
  • Factory methods for: +
      +
    1. Marshaller
    2. +
    3. Unmarshaller
    4. +
    5. SchemaReader
    6. +
    7. SchemaWriter
    8. +
    9. MappingTool
    10. +
    11. SourceGenerator
    12. +
    +
  • +
  • Methods which are used by different XML classes, have (keep) central + information or services and had been kreeping into LocalConfiguration but + have nothing to do with Configuration itself.
  • +
+ We head to remove static usages and to a Castor being more loosely linked then + today. +

+

Fixed support for 'strict elements'

When instructing Castor XML during unmarshalling to handle elements 'strict', Index: xmlctf-framework/src/main/java/org/castor/xmlctf/TestWithRandomObject.java =================================================================== --- xmlctf-framework/src/main/java/org/castor/xmlctf/TestWithRandomObject.java (revision 7270) +++ xmlctf-framework/src/main/java/org/castor/xmlctf/TestWithRandomObject.java (working copy) @@ -24,6 +24,7 @@ import org.exolab.castor.tests.framework.testDescriptor.FailureType; import org.exolab.castor.tests.framework.testDescriptor.types.FailureStepType; +import org.exolab.castor.xml.XMLContext; /** * Implements a test case that tests code written by the XML source generator. @@ -84,11 +85,13 @@ * @throws Exception if anything goes wrong during setup */ protected void setUp() throws Exception { - if (_delegate instanceof MarshallingFrameworkTestCase) { - ((MarshallingFrameworkTestCase)_delegate).setUp(); - } else if (_delegate instanceof SourceGeneratorTestCase) { - ((SourceGeneratorTestCase)_delegate).setUp(); - } + _delegate.setXMLContext(new XMLContext()); + _delegate.setUp(); +// if (_delegate instanceof MarshallingFrameworkTestCase) { +// ((MarshallingFrameworkTestCase)_delegate).setUp(); +// } else if (_delegate instanceof SourceGeneratorTestCase) { +// ((SourceGeneratorTestCase)_delegate).setUp(); +// } } /** @@ -97,11 +100,12 @@ * @throws Exception if anything goes wrong during teardown */ protected void tearDown() throws Exception { - if (_delegate instanceof MarshallingFrameworkTestCase) { - ((MarshallingFrameworkTestCase)_delegate).tearDown(); - } else if (_delegate instanceof SourceGeneratorTestCase) { - ((SourceGeneratorTestCase)_delegate).tearDown(); - } + _delegate.setUp(); +// if (_delegate instanceof MarshallingFrameworkTestCase) { +// ((MarshallingFrameworkTestCase)_delegate).tearDown(); +// } else if (_delegate instanceof SourceGeneratorTestCase) { +// ((SourceGeneratorTestCase)_delegate).tearDown(); +// } } /** Index: xmlctf-framework/src/main/java/org/castor/xmlctf/SourceGeneratorTestCase.java =================================================================== --- xmlctf-framework/src/main/java/org/castor/xmlctf/SourceGeneratorTestCase.java (revision 7270) +++ xmlctf-framework/src/main/java/org/castor/xmlctf/SourceGeneratorTestCase.java (working copy) @@ -153,6 +153,7 @@ verbose("================================================\n"); // Set up and run the source generator so we can test using the generated source + _sourceGenerator.setXMLContext(getXMLContext()); _sourceGenerator.setUp(); _sourceGenerator.runTest(); Index: xmlctf-framework/src/main/java/org/castor/xmlctf/TestWithCustomTest.java =================================================================== --- xmlctf-framework/src/main/java/org/castor/xmlctf/TestWithCustomTest.java (revision 7270) +++ xmlctf-framework/src/main/java/org/castor/xmlctf/TestWithCustomTest.java (working copy) @@ -26,6 +26,7 @@ import org.exolab.castor.tests.framework.testDescriptor.CustomTest; import org.exolab.castor.tests.framework.testDescriptor.FailureType; import org.exolab.castor.tests.framework.testDescriptor.types.FailureStepType; +import org.exolab.castor.xml.XMLContext; /** * Implements a test case that tests code written by the XML source generator. @@ -94,6 +95,8 @@ * @throws Exception if anything goes wrong during setup */ protected void setUp() throws Exception { + _delegate.setXMLContext(new XMLContext()); + if (_delegate instanceof MarshallingFrameworkTestCase) { ((MarshallingFrameworkTestCase)_delegate).setUp(); } else if (_delegate instanceof SourceGeneratorTestCase) { Index: xmlctf-framework/src/main/java/org/castor/xmlctf/TestSourceGenerator.java =================================================================== --- xmlctf-framework/src/main/java/org/castor/xmlctf/TestSourceGenerator.java (revision 7270) +++ xmlctf-framework/src/main/java/org/castor/xmlctf/TestSourceGenerator.java (working copy) @@ -176,6 +176,7 @@ URL[] urlList = {_test.getTestFile().toURL(), _outputRootFile.toURL()}; ClassLoader loader = new URLClassLoader(urlList, _test.getClass().getClassLoader()); _test.setClassLoader(loader); + getXMLContext().getInternalContext().setClassLoader(loader); } catch (Exception e) { if (!checkExceptionWasExpected(e, FailureStepType.LOAD_GENERATED_CLASSES)) { fail("Unable to process the test case:" + e); Index: xmlctf-framework/src/main/java/org/castor/xmlctf/OnlySourceGenerationTestCase.java =================================================================== --- xmlctf-framework/src/main/java/org/castor/xmlctf/OnlySourceGenerationTestCase.java (revision 7270) +++ xmlctf-framework/src/main/java/org/castor/xmlctf/OnlySourceGenerationTestCase.java (working copy) @@ -22,6 +22,7 @@ import org.exolab.castor.tests.framework.testDescriptor.OnlySourceGenerationTest; import org.exolab.castor.tests.framework.testDescriptor.UnitTestCase; +import org.exolab.castor.xml.XMLContext; /** * This class encapsulate all the logic to run the tests patterns for the source @@ -89,6 +90,11 @@ verbose("\n================================================"); verbose("Test suite '"+_test.getName()+"': setting up test '" + _name+"'"); verbose("================================================\n"); + if (getXMLContext() == null) { + // not wrapped inside a TestWithXy test! + setXMLContext(new XMLContext()); + } + _sourceGenerator.setXMLContext(getXMLContext()); _sourceGenerator.setUp(); } Index: xmlctf-framework/src/main/java/org/castor/xmlctf/MarshallingFrameworkTestCase.java =================================================================== --- xmlctf-framework/src/main/java/org/castor/xmlctf/MarshallingFrameworkTestCase.java (revision 7270) +++ xmlctf-framework/src/main/java/org/castor/xmlctf/MarshallingFrameworkTestCase.java (working copy) @@ -183,6 +183,7 @@ ClassLoader loader = _test.getClassLoader(); loader = new URLClassLoader(new URL[] {_outputRootFile.toURL()}, loader); _test.setClassLoader(loader); + getXMLContext().getInternalContext().setClassLoader(loader); verbose("Root class specified in TestDescriptor..."); verbose("Loading class: " + _rootClassName); Index: xmlctf-framework/src/main/java/org/castor/xmlctf/TestWithReferenceDocument.java =================================================================== --- xmlctf-framework/src/main/java/org/castor/xmlctf/TestWithReferenceDocument.java (revision 7270) +++ xmlctf-framework/src/main/java/org/castor/xmlctf/TestWithReferenceDocument.java (working copy) @@ -27,6 +27,7 @@ import org.castor.xmlctf.util.CTFUtils; import org.exolab.castor.tests.framework.testDescriptor.FailureType; import org.exolab.castor.tests.framework.testDescriptor.types.FailureStepType; +import org.exolab.castor.xml.XMLContext; /** * Implements a test case that tests code written by the XML source generator. @@ -113,11 +114,13 @@ throw new IllegalStateException("No test specified to set up."); } - if (_delegate instanceof MarshallingFrameworkTestCase) { - ((MarshallingFrameworkTestCase)_delegate).setUp(); - } else if (_delegate instanceof SourceGeneratorTestCase) { - ((SourceGeneratorTestCase)_delegate).setUp(); - } + _delegate.setXMLContext(new XMLContext()); + _delegate.setUp(); +// if (_delegate instanceof MarshallingFrameworkTestCase) { +// ((MarshallingFrameworkTestCase)_delegate).setUp(); +// } else if (_delegate instanceof SourceGeneratorTestCase) { +// ((SourceGeneratorTestCase)_delegate).setUp(); +// } } /** @@ -129,12 +132,12 @@ if (_delegate == null) { throw new IllegalStateException("No test specified to tear down."); } - - if (_delegate instanceof MarshallingFrameworkTestCase) { - ((MarshallingFrameworkTestCase)_delegate).tearDown(); - } else if (_delegate instanceof SourceGeneratorTestCase) { - ((SourceGeneratorTestCase)_delegate).tearDown(); - } + _delegate.tearDown(); +// if (_delegate instanceof MarshallingFrameworkTestCase) { +// ((MarshallingFrameworkTestCase)_delegate).tearDown(); +// } else if (_delegate instanceof SourceGeneratorTestCase) { +// ((SourceGeneratorTestCase)_delegate).tearDown(); +// } } /** Index: xmlctf-framework/src/main/java/org/castor/xmlctf/SchemaTestCase.java =================================================================== --- xmlctf-framework/src/main/java/org/castor/xmlctf/SchemaTestCase.java (revision 7270) +++ xmlctf-framework/src/main/java/org/castor/xmlctf/SchemaTestCase.java (working copy) @@ -66,9 +66,11 @@ import org.exolab.castor.tests.framework.testDescriptor.SchemaDifferences; import org.exolab.castor.tests.framework.testDescriptor.UnitTestCase; import org.exolab.castor.tests.framework.testDescriptor.types.FailureStepType; +import org.exolab.castor.xml.XMLContext; import org.exolab.castor.xml.schema.Schema; import org.exolab.castor.xml.schema.reader.SchemaReader; import org.exolab.castor.xml.schema.writer.SchemaWriter; +import org.xml.sax.InputSource; /** * A JUnit test case for testing the Castor Schema Object Model. @@ -146,6 +148,10 @@ } catch (IOException e) { fail("IOException copying support files " + e); } + if (getXMLContext() == null) { + // not wrapped inside a TestWithXy test! + setXMLContext(new XMLContext()); + } } /** @@ -217,7 +223,8 @@ private Schema testReadingSchema(final String url) { verbose("--> Reading XML Schema: " + url); try { - SchemaReader reader = new SchemaReader(url); + SchemaReader reader = getXMLContext().createSchemaReader(new InputSource(url)); +// #JG SchemaReader reader = new SchemaReader(url); Schema returnValue = reader.read(); if (_failure != null && _failure.getContent() && _failure.getFailureStep() != null && _failure.getFailureStep().equals(FailureStepType.PARSE_SCHEMA)) { @@ -248,7 +255,8 @@ File output = new File(_outputRootFile, fileName); FileWriter writer = new FileWriter(output); - SchemaWriter sw = new SchemaWriter(new PrintWriter(writer, true)); + SchemaWriter sw = getXMLContext().createSchemaWriter(new PrintWriter(writer, true)); +// #JG SchemaWriter sw = new SchemaWriter(new PrintWriter(writer, true)); sw.write(schema); writer.close(); } catch (Exception e) { Index: xmlctf-framework/src/main/java/org/castor/xmlctf/XMLTestCase.java =================================================================== --- xmlctf-framework/src/main/java/org/castor/xmlctf/XMLTestCase.java (revision 7270) +++ xmlctf-framework/src/main/java/org/castor/xmlctf/XMLTestCase.java (working copy) @@ -74,6 +74,7 @@ import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.UnmarshalListener; import org.exolab.castor.xml.Unmarshaller; +import org.exolab.castor.xml.XMLContext; import org.xml.sax.InputSource; /** @@ -135,6 +136,8 @@ protected final FailureType _failure; /** Used only to retrieve the classloader. */ protected final CastorTestCase _test; + /** The internal Castor XML context. */ + private XMLContext _xmlContext; /** * Instantiate a new XMLTestCase with the given name. @@ -161,6 +164,7 @@ _failure = unit.getFailure(); _test = test; _outputRootFile = test.getOutputRootFile(); + _xmlContext = null; } /** @@ -178,8 +182,21 @@ _skip = tc._skip; _failure = tc._failure; _test = tc._test; + _xmlContext = null; } + + protected abstract void setUp() throws Exception; + + protected abstract void tearDown() throws Exception; + public void setXMLContext(XMLContext xmlContext) { + _xmlContext = xmlContext; + } + + public XMLContext getXMLContext() { + return _xmlContext; + } + /** * Returns a version of the input name that is suitable for JUnit test case * or test suite use. Apparently, JUnit truncates test case names after @@ -321,7 +338,9 @@ } private Marshaller createMarshaler(final File marshalOutput) throws Exception { - Marshaller marshaller = new Marshaller(new FileWriter(marshalOutput)); + getXMLContext().getInternalContext().getXMLClassDescriptorResolver().cleanDescriptorCache(); + Marshaller marshaller = getXMLContext().createMarshaller(); + marshaller.setWriter(new FileWriter(marshalOutput)); //-- Configuration for marshaler? Use config from unit test case if available Configuration config = _unitTest.getConfiguration(); @@ -389,12 +408,19 @@ final Unmarshaller unmar; if (_mapping != null) { - unmar = new Unmarshaller(_mapping); +//J unmar = new Unmarshaller(_mapping); + unmar = getXMLContext().createUnmarshaller(); + unmar.setMapping(_mapping); } else { if (_test.getClassLoader() != null) { - unmar = new Unmarshaller(_rootClass, _test.getClassLoader()); +//J unmar = new Unmarshaller(_rootClass, _test.getClassLoader()); + unmar = getXMLContext().createUnmarshaller(); + unmar.setClassLoader(_test.getClassLoader()); + unmar.setClass(_rootClass); } else { - unmar = new Unmarshaller(_rootClass); +//J unmar = new Unmarshaller(_rootClass); + unmar = getXMLContext().createUnmarshaller(); + unmar.setClass(_rootClass); } } Index: ddlgen/src/test/java/org/castor/ddlgen/test/framework/AbstractGeneratorTest.java =================================================================== --- ddlgen/src/test/java/org/castor/ddlgen/test/framework/AbstractGeneratorTest.java (revision 7270) +++ ddlgen/src/test/java/org/castor/ddlgen/test/framework/AbstractGeneratorTest.java (working copy) @@ -154,6 +154,7 @@ Mapping mapping = new Mapping(); mapping.loadMapping(mappingURL); new MappingUnmarshaller().loadMappingOnly(mapping); + // TODO: Joachim 2007-09-07 the InternalContext should be set into the unmarshaller! _generator.setMapping(mapping); _generator.createSchema(); Index: ddlgen/src/main/java/org/castor/ddlgen/Main.java =================================================================== --- ddlgen/src/main/java/org/castor/ddlgen/Main.java (revision 7270) +++ ddlgen/src/main/java/org/castor/ddlgen/Main.java (working copy) @@ -96,6 +96,7 @@ Mapping mapping = new Mapping(); mapping.loadMapping(mappingName); new MappingUnmarshaller().loadMappingOnly(mapping); + // TODO: Joachim 2007-09-07 the InternalContext should be set into the unmarshaller! generator.setMapping(mapping); generator.generateDDL(new FileOutputStream(ddlName)); Index: xmlctf/tests/MasterTestSuite/sourcegenerator/Facets/UnwrappedNumbers/TestClassByte.java =================================================================== --- xmlctf/tests/MasterTestSuite/sourcegenerator/Facets/UnwrappedNumbers/TestClassByte.java (revision 7270) +++ xmlctf/tests/MasterTestSuite/sourcegenerator/Facets/UnwrappedNumbers/TestClassByte.java (working copy) @@ -47,6 +47,8 @@ NumberTests instance = new NumberTests(); for (int i = 0; i < badValues.length; i++) { try { + System.out.println("instance under test: " + instance + " of class: " + instance.getClass()); + System.out.println("bad value: " + badValues[i] + " as byte: " + Byte.parseByte(badValues[i].trim())); instance.setMybyte(Byte.parseByte(badValues[i].trim())); instance.validate(); } catch (org.exolab.castor.xml.ValidationException e) { @@ -71,7 +73,7 @@ // Good, we caught the exception continue; } - LOG.error("Bad value " + badValuesMinMax[i] + " did not fail the test"); + LOG.error("Bad min/max value " + badValuesMinMax[i] + " did not fail the test"); return false; } Index: codegen/src/main/java/org/exolab/castor/builder/SourceGenerator.java =================================================================== --- codegen/src/main/java/org/exolab/castor/builder/SourceGenerator.java (revision 7270) +++ codegen/src/main/java/org/exolab/castor/builder/SourceGenerator.java (working copy) @@ -62,8 +62,12 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.castor.core.exceptions.CastorRuntimeException; +import org.castor.core.util.Configuration; +import org.castor.xml.BackwardCompatibilityContext; import org.castor.xml.JavaNaming; import org.castor.xml.JavaNamingImpl; +import org.castor.xml.InternalContext; +import org.castor.xml.XMLConfiguration; import org.exolab.castor.builder.binding.BindingException; import org.exolab.castor.builder.binding.BindingLoader; import org.exolab.castor.builder.binding.ExtendedBinding; @@ -80,8 +84,6 @@ import org.exolab.castor.builder.factory.SourceFactory; import org.exolab.castor.builder.info.ClassInfo; import org.exolab.castor.mapping.xml.MappingRoot; -import org.exolab.castor.util.Configuration; -import org.exolab.castor.util.LocalConfiguration; import org.exolab.castor.util.NestedIOException; import org.exolab.castor.util.Version; import org.exolab.castor.util.dialog.ConsoleDialog; @@ -141,8 +143,8 @@ //- Instance Variables -/ //----------------------/ - /** Castor configuration. */ - private final Configuration _config; + /** Castor internal context - mother of all. */ + private final InternalContext _internalContext; /** The XMLBindingComponent used to create Java classes from an XML Schema. */ private final XMLBindingComponent _bindingComponent; /** Our object used to generate source for a single source file. */ @@ -223,8 +225,9 @@ public SourceGenerator(final FieldInfoFactory infoFactory, final ExtendedBinding binding) { super(); - _config = LocalConfiguration.getInstance(); - setJavaNaming(new JavaNamingImpl()); + _internalContext = new BackwardCompatibilityContext(); + + setJavaNaming(_internalContext.getJavaNaming()); _dialog = new ConsoleDialog(); _infoFactory = (infoFactory == null) ? new FieldInfoFactory() : infoFactory; @@ -577,7 +580,7 @@ // -- get default parser from Configuration Parser parser = null; try { - parser = _config.getParser(); + parser = _internalContext.getParser(); } catch (RuntimeException rte) { // ignore } @@ -589,7 +592,7 @@ SchemaUnmarshaller schemaUnmarshaller = null; try { - schemaUnmarshaller = new SchemaUnmarshaller(); + schemaUnmarshaller = new SchemaUnmarshaller(_internalContext); } catch (XMLException e) { //--The default constructor cannot throw exception so this should never happen //--just log the exception Index: codegen/src/main/java/org/exolab/castor/builder/BuilderConfiguration.java =================================================================== --- codegen/src/main/java/org/exolab/castor/builder/BuilderConfiguration.java (revision 7270) +++ codegen/src/main/java/org/exolab/castor/builder/BuilderConfiguration.java (working copy) @@ -56,10 +56,10 @@ import java.util.Properties; import java.util.StringTokenizer; +import org.castor.core.util.Configuration; import org.castor.xml.JavaNaming; import org.castor.xml.JavaNamingImpl; -import org.exolab.castor.util.Configuration; -import org.exolab.castor.util.LocalConfiguration; +import org.castor.xml.XMLConfiguration; /** * The configuration for the SourceGenerator. @@ -581,7 +581,7 @@ protected final synchronized void load() { if (_defaultProps == null) { //-- load defaults from JAR - _defaultProps = Configuration.loadProperties( + _defaultProps = org.exolab.castor.util.Configuration.loadProperties( Property.RESOURCE_NAME, Property.CONFIG_FILENAME_PROPERTY); //-- load local defaults @@ -618,12 +618,12 @@ } } - Configuration rtconf = LocalConfiguration.getInstance(); + Configuration rtconf = XMLConfiguration.newInstance(); // Parse XML namespace and package list from both castor.properties and // castorbuilder.properties - processNamespacePackageMappings(rtconf.getProperty(Property.NAMESPACE_PACKAGES_OLD, "")); - processNamespacePackageMappings(rtconf.getProperty(Property.NAMESPACE_PACKAGES, "")); + processNamespacePackageMappings(rtconf.getString(Property.NAMESPACE_PACKAGES_OLD, "")); + processNamespacePackageMappings(rtconf.getString(Property.NAMESPACE_PACKAGES, "")); processNamespacePackageMappings(_defaultProps.getProperty( Property.NAMESPACE_PACKAGES_OLD, "")); processNamespacePackageMappings(_defaultProps.getProperty( Index: anttask/src/main/java/org/castor/anttask/CastorCodeGenTask.java =================================================================== --- anttask/src/main/java/org/castor/anttask/CastorCodeGenTask.java (revision 7270) +++ anttask/src/main/java/org/castor/anttask/CastorCodeGenTask.java (working copy) @@ -55,6 +55,8 @@ import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.FileSet; +import org.castor.xml.BackwardCompatibilityContext; +import org.castor.xml.InternalContext; import org.exolab.castor.builder.SourceGenerator; import org.exolab.castor.builder.binding.ExtendedBinding; import org.exolab.castor.builder.factory.FieldInfoFactory; @@ -101,6 +103,9 @@ //-------------------------------------------------------------------------- + /** Castor XML context - the mother of all. */ + private InternalContext _internalContext; + /** If processing one schema file, this lists the file. */ private File _schemaFile = null; @@ -169,7 +174,8 @@ * No-arg constructor. */ public CastorCodeGenTask() { - // Nothing needed + super(); + _internalContext = new BackwardCompatibilityContext(); } //-------------------------------------------------------------------------- @@ -552,7 +558,7 @@ public void generateSource(final InputSource source, final String packageName) { Parser parser = null; try { - parser = LocalConfiguration.getInstance().getParser(); + parser = _internalContext.getParser(); } catch (RuntimeException e) { throw new BuildException("Unable to create SAX parser.", e); } @@ -562,7 +568,7 @@ SchemaUnmarshaller schemaUnmarshaller = null; try { - schemaUnmarshaller = new SchemaUnmarshaller(); + schemaUnmarshaller = new SchemaUnmarshaller(_internalContext); } catch (XMLException e) { throw new BuildException("Unable to create schema unmarshaller.", e); } Index: anttask/src/main/java/org/castor/anttask/CastorDDLGenTask.java =================================================================== --- anttask/src/main/java/org/castor/anttask/CastorDDLGenTask.java (revision 7270) +++ anttask/src/main/java/org/castor/anttask/CastorDDLGenTask.java (working copy) @@ -173,6 +173,7 @@ Mapping mapping = new Mapping(); mapping.loadMapping(filePath); new MappingUnmarshaller().loadMappingOnly(mapping); + // TODO: Joachim 2007-09-07 the InternalContext should be set into the unmarshaller! ddlgen.setMapping(mapping); ddlgen.generateDDL(_outputStream); Index: examples/src/main/java/tools/CastorMapper.java =================================================================== --- examples/src/main/java/tools/CastorMapper.java (revision 7270) +++ examples/src/main/java/tools/CastorMapper.java (working copy) @@ -6,14 +6,19 @@ */ package tools; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; + +import myapp.Product; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.castor.xml.JavaNamingImpl; -import org.exolab.castor.tools.MappingTool; +import org.exolab.castor.tools.MappingTool; +import org.exolab.castor.xml.XMLContext; -import myapp.Product; -import java.io.*; - /** * generate a Castor mapping file ready for editing */ @@ -27,7 +32,7 @@ public CastorMapper() { try { - tool = new MappingTool(new JavaNamingImpl()); + tool = new XMLContext().createMappingTool(); } catch (Exception e) { log.error (e.getClass().getName(), e);