merge of commit 643011 from 1.1 branch

git-svn-id: https://svn.apache.org/repos/asf/tuscany/java/sdo@680370 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/distribution/src/main/assembly/src.xml b/distribution/src/main/assembly/src.xml
index 4043e74..37a0d02 100644
--- a/distribution/src/main/assembly/src.xml
+++ b/distribution/src/main/assembly/src.xml
@@ -50,6 +50,7 @@
                 <exclude>**/var/journal</exclude>
                 <exclude>**/build.out*</exclude>
                 <exclude>impl/.felix</exclude>
+                <exclude>impl/.felix/**/*</exclude>
             </excludes>
         </fileSet>
     </fileSets>
diff --git a/distribution/src/main/release/bin/README b/distribution/src/main/release/bin/README
index fc82c39..adf9ee9 100644
--- a/distribution/src/main/release/bin/README
+++ b/distribution/src/main/release/bin/README
@@ -1,23 +1,23 @@
-Tuscany SDO for ${sdo.version} Binary Distribution Readme File

-

-See the LICENSE, DISCLAIMER and NOTICE files for legal information concerning this distribution. 

-

-See the RELEASE_NOTES file for a summary of what's new with this release.

-

-See the INSTALL file for instructions on how to use Tuscany SDO Java provided in this binary distribution.

-

-See the docs/javadoc/sdo-samples/index.html file for instructions on how to run the sample programs.

-

-Documentation

-

-For general documentation about the Tuscany project and the SDO for Java, see the Tuscany website

-http://incubator.apache.org/tuscany

-

-This distribution contains javadoc for the SDO 2.1 API, the Tuscany SDO extensions API,  and the Tuscany SDO samples.

-

-Samples

-

-Sample source code is included with this binary distribution. 

-

-

-

+Tuscany SDO for ${sdo.version} Binary Distribution Readme File
+
+See the LICENSE, DISCLAIMER and NOTICE files for legal information concerning this distribution. 
+
+See the RELEASE_NOTES file for a summary of what's new with this release.
+
+See the INSTALL file for instructions on how to use Tuscany SDO Java provided in this binary distribution.
+
+See the docs/javadoc/sdo-samples/index.html file for instructions on how to run the sample programs.
+
+Documentation
+
+For general documentation about the Tuscany project and the SDO for Java, see the Tuscany website
+http://incubator.apache.org/tuscany
+
+This distribution contains javadoc for the SDO 2.1 API, the Tuscany SDO extensions API,  and the Tuscany SDO samples.
+
+Samples
+
+Sample source code is included with this binary distribution. 
+
+
+
diff --git a/distribution/src/main/release/bin/samples/README b/distribution/src/main/release/bin/samples/README
index d669e0b..a19704c 100644
--- a/distribution/src/main/release/bin/samples/README
+++ b/distribution/src/main/release/bin/samples/README
@@ -1,11 +1,11 @@
-Apache Tuscany SDO Java Sample Programs

-

-Documentation for these samples may be found in the docs/javadoc/sdo-samples directory

-of this distribution.

-

-The runsamples.sh and runsamples.bat scripts in their unedited form

-provide a way to run all of the samples sequentially.  If you run these scripts

-from within the directory they are found in, they will run correctly.

-If you run them from elsewhere you will need to edit the scripts and set the

-BINARY_BASE variable to the path in your filesystem where you unpacked the

-SDO distribution.

+Apache Tuscany SDO Java Sample Programs
+
+Documentation for these samples may be found in the docs/javadoc/sdo-samples directory
+of this distribution.
+
+The runsamples.sh and runsamples.bat scripts in their unedited form
+provide a way to run all of the samples sequentially.  If you run these scripts
+from within the directory they are found in, they will run correctly.
+If you run them from elsewhere you will need to edit the scripts and set the
+BINARY_BASE variable to the path in your filesystem where you unpacked the
+SDO distribution.
diff --git a/impl/pom.xml b/impl/pom.xml
index 2d28966..ba0549c 100644
--- a/impl/pom.xml
+++ b/impl/pom.xml
@@ -122,6 +122,19 @@
     <build>
         <plugins>
             <plugin>
+               <artifactId>maven-jar-plugin</artifactId>
+               <configuration>
+                  <archive>
+                     <manifestEntries>
+                        <Implementation-Vendor-Id>org.apache</Implementation-Vendor-Id>
+                        <Implementation-Version>1.1-incubating</Implementation-Version>
+                        <X-Compile-Source-JDK>1.4</X-Compile-Source-JDK>
+                        <X-Compile-Target-JDK>1.4</X-Compile-Target-JDK>
+                     </manifestEntries>
+                  </archive>
+               </configuration>
+            </plugin>
+            <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-jar-plugin</artifactId>
                 <version>2.1</version>
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/helper/BaseSDOExtendedMetaDataImpl.java b/impl/src/main/java/org/apache/tuscany/sdo/helper/BaseSDOExtendedMetaDataImpl.java
index 422f534..88c714f 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/helper/BaseSDOExtendedMetaDataImpl.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/helper/BaseSDOExtendedMetaDataImpl.java
@@ -1,167 +1,167 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.helper;

-

-import org.eclipse.emf.ecore.EAttribute;

-import org.eclipse.emf.ecore.EClass;

-import org.eclipse.emf.ecore.EClassifier;

-import org.eclipse.emf.ecore.EPackage;

-import org.eclipse.emf.ecore.EReference;

-import org.eclipse.emf.ecore.EStructuralFeature;

-import org.eclipse.emf.ecore.ETypedElement;

-import org.eclipse.emf.ecore.EcoreFactory;

-import org.eclipse.emf.ecore.EcorePackage;

-import org.eclipse.emf.ecore.util.BasicExtendedMetaData;

-import org.eclipse.emf.ecore.util.ExtendedMetaData;

-import org.eclipse.emf.ecore.xml.type.XMLTypePackage;

-

-/**

- * A BasicExtendedMetaData that uses a supplied (SDO) ecore factory to create properties and types.

- */

-public class BaseSDOExtendedMetaDataImpl extends BasicExtendedMetaData

-{

-  protected EcoreFactory ecoreFactory = EcoreFactory.eINSTANCE;

-  protected DemandMetaData demandMetaData = new DemandMetaData();

-  

-  public static class DemandMetaData {

-    EClassifier getEObject() { return EcorePackage.eINSTANCE.getEObject(); }

-    EClassifier getAnyType() { return XMLTypePackage.eINSTANCE.getAnyType(); }

-    EClassifier getAnySimpleType() { return XMLTypePackage.eINSTANCE.getAnySimpleType(); }

-    EClassifier getXMLTypeDocumentRoot() { return XMLTypePackage.eINSTANCE.getXMLTypeDocumentRoot(); }

-  }

-

-  public BaseSDOExtendedMetaDataImpl(EPackage.Registry registry)

-  {

-    super(registry);

-  }

-

-  public EPackage demandPackage(String namespace)

-  {

-    EPackage ePackage = demandRegistry.getEPackage(namespace);

-    if (ePackage == null)

-    {

-      ePackage = ecoreFactory.createEPackage();

-      ePackage.setNsURI(namespace);

-      setQualified(ePackage, namespace != null);

-      if (namespace != null)

-      {

-        ePackage.setNsPrefix

-          (namespace.equals(ExtendedMetaData.XMLNS_URI) ? 

-             namespace.equals(ExtendedMetaData.XML_URI) ?

-               "xml" : 

-               "xmlns" : 

-             computePrefix(namespace));

-      }

-      demandRegistry.put(namespace, ePackage);

-

-      // demandDocumentRoot(ePackage);

-

-      EClass documentRootEClass = ecoreFactory.createEClass();

-      documentRootEClass.getESuperTypes().add(demandMetaData.getXMLTypeDocumentRoot());

-      documentRootEClass.setName("DocumentRoot");

-      ePackage.getEClassifiers().add(documentRootEClass);

-      setDocumentRoot(documentRootEClass);

-    }

-    return ePackage;

-  }

-  

-  public EClassifier demandType(String namespace, String name)

-  {

-    EPackage ePackage = demandPackage(namespace);

-    EClassifier eClassifier = getType(ePackage, name);

-    if (eClassifier != null)

-    {

-      return eClassifier;

-    }

-    else

-    {

-      EClass eClass = ecoreFactory.createEClass();

-      eClass.setName(name);

-      eClass.getESuperTypes().add(demandMetaData.getAnyType());

-      setContentKind(eClass, MIXED_CONTENT);

-      ePackage.getEClassifiers().add(eClass);

-      return eClass;

-    }

-  }

-

-  public EStructuralFeature demandFeature(String namespace, String name, boolean isElement, boolean isReference)

-  {

-    EPackage ePackage = demandPackage(namespace);

-    EClass documentRootEClass = getDocumentRoot(ePackage);

-    EStructuralFeature eStructuralFeature = 

-      isElement ? 

-        getLocalElement(documentRootEClass, namespace, name) : 

-        getLocalAttribute(documentRootEClass, namespace, name);

-    if (eStructuralFeature != null)

-    {

-      return eStructuralFeature;

-    }

-    else

-    {

-      if (isReference)

-      {

-        EReference eReference = ecoreFactory.createEReference();

-        eReference.setContainment(isElement);

-        eReference.setEType(demandMetaData.getEObject());

-        eReference.setName(name);

-        eReference.setDerived(true);

-        eReference.setTransient(true);

-        eReference.setVolatile(true);

-        documentRootEClass.getEStructuralFeatures().add(eReference);

-

-        setFeatureKind(eReference, isElement ? ELEMENT_FEATURE : ATTRIBUTE_FEATURE);

-        setNamespace(eReference, namespace);

-

-        // Mark the bound as unspecified so that it won't be considered many

-        // but can nevertheless be recognized as being unspecified and perhaps still be treat as many.

-        //

-        if (isElement)

-        {

-          eReference.setUpperBound(ETypedElement.UNSPECIFIED_MULTIPLICITY);

-        }

-

-        return eReference;

-      }

-      else

-      {

-        EAttribute eAttribute = ecoreFactory.createEAttribute();

-        eAttribute.setName(name);

-        eAttribute.setEType(demandMetaData.getAnySimpleType());

-        eAttribute.setDerived(true);

-        eAttribute.setTransient(true);

-        eAttribute.setVolatile(true);

-        documentRootEClass.getEStructuralFeatures().add(eAttribute);

-

-        setFeatureKind(eAttribute, isElement ? ELEMENT_FEATURE : ATTRIBUTE_FEATURE);

-        setNamespace(eAttribute, namespace);

-

-        // Mark the bound as unspecified so that it won't be considered many

-        // but can nevertheless be recognized as being unspecified and perhaps still be treat as many.

-        //

-        if (isElement)

-        {

-          eAttribute.setUpperBound(ETypedElement.UNSPECIFIED_MULTIPLICITY);

-        }

-

-        return eAttribute;

-      }

-    }

-  }

-}

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.helper;
+
+import org.eclipse.emf.ecore.EAttribute;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EClassifier;
+import org.eclipse.emf.ecore.EPackage;
+import org.eclipse.emf.ecore.EReference;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.ETypedElement;
+import org.eclipse.emf.ecore.EcoreFactory;
+import org.eclipse.emf.ecore.EcorePackage;
+import org.eclipse.emf.ecore.util.BasicExtendedMetaData;
+import org.eclipse.emf.ecore.util.ExtendedMetaData;
+import org.eclipse.emf.ecore.xml.type.XMLTypePackage;
+
+/**
+ * A BasicExtendedMetaData that uses a supplied (SDO) ecore factory to create properties and types.
+ */
+public class BaseSDOExtendedMetaDataImpl extends BasicExtendedMetaData
+{
+  protected EcoreFactory ecoreFactory = EcoreFactory.eINSTANCE;
+  protected DemandMetaData demandMetaData = new DemandMetaData();
+  
+  public static class DemandMetaData {
+    EClassifier getEObject() { return EcorePackage.eINSTANCE.getEObject(); }
+    EClassifier getAnyType() { return XMLTypePackage.eINSTANCE.getAnyType(); }
+    EClassifier getAnySimpleType() { return XMLTypePackage.eINSTANCE.getAnySimpleType(); }
+    EClassifier getXMLTypeDocumentRoot() { return XMLTypePackage.eINSTANCE.getXMLTypeDocumentRoot(); }
+  }
+
+  public BaseSDOExtendedMetaDataImpl(EPackage.Registry registry)
+  {
+    super(registry);
+  }
+
+  public EPackage demandPackage(String namespace)
+  {
+    EPackage ePackage = demandRegistry.getEPackage(namespace);
+    if (ePackage == null)
+    {
+      ePackage = ecoreFactory.createEPackage();
+      ePackage.setNsURI(namespace);
+      setQualified(ePackage, namespace != null);
+      if (namespace != null)
+      {
+        ePackage.setNsPrefix
+          (namespace.equals(ExtendedMetaData.XMLNS_URI) ? 
+             namespace.equals(ExtendedMetaData.XML_URI) ?
+               "xml" : 
+               "xmlns" : 
+             computePrefix(namespace));
+      }
+      demandRegistry.put(namespace, ePackage);
+
+      // demandDocumentRoot(ePackage);
+
+      EClass documentRootEClass = ecoreFactory.createEClass();
+      documentRootEClass.getESuperTypes().add(demandMetaData.getXMLTypeDocumentRoot());
+      documentRootEClass.setName("DocumentRoot");
+      ePackage.getEClassifiers().add(documentRootEClass);
+      setDocumentRoot(documentRootEClass);
+    }
+    return ePackage;
+  }
+  
+  public EClassifier demandType(String namespace, String name)
+  {
+    EPackage ePackage = demandPackage(namespace);
+    EClassifier eClassifier = getType(ePackage, name);
+    if (eClassifier != null)
+    {
+      return eClassifier;
+    }
+    else
+    {
+      EClass eClass = ecoreFactory.createEClass();
+      eClass.setName(name);
+      eClass.getESuperTypes().add(demandMetaData.getAnyType());
+      setContentKind(eClass, MIXED_CONTENT);
+      ePackage.getEClassifiers().add(eClass);
+      return eClass;
+    }
+  }
+
+  public EStructuralFeature demandFeature(String namespace, String name, boolean isElement, boolean isReference)
+  {
+    EPackage ePackage = demandPackage(namespace);
+    EClass documentRootEClass = getDocumentRoot(ePackage);
+    EStructuralFeature eStructuralFeature = 
+      isElement ? 
+        getLocalElement(documentRootEClass, namespace, name) : 
+        getLocalAttribute(documentRootEClass, namespace, name);
+    if (eStructuralFeature != null)
+    {
+      return eStructuralFeature;
+    }
+    else
+    {
+      if (isReference)
+      {
+        EReference eReference = ecoreFactory.createEReference();
+        eReference.setContainment(isElement);
+        eReference.setEType(demandMetaData.getEObject());
+        eReference.setName(name);
+        eReference.setDerived(true);
+        eReference.setTransient(true);
+        eReference.setVolatile(true);
+        documentRootEClass.getEStructuralFeatures().add(eReference);
+
+        setFeatureKind(eReference, isElement ? ELEMENT_FEATURE : ATTRIBUTE_FEATURE);
+        setNamespace(eReference, namespace);
+
+        // Mark the bound as unspecified so that it won't be considered many
+        // but can nevertheless be recognized as being unspecified and perhaps still be treat as many.
+        //
+        if (isElement)
+        {
+          eReference.setUpperBound(ETypedElement.UNSPECIFIED_MULTIPLICITY);
+        }
+
+        return eReference;
+      }
+      else
+      {
+        EAttribute eAttribute = ecoreFactory.createEAttribute();
+        eAttribute.setName(name);
+        eAttribute.setEType(demandMetaData.getAnySimpleType());
+        eAttribute.setDerived(true);
+        eAttribute.setTransient(true);
+        eAttribute.setVolatile(true);
+        documentRootEClass.getEStructuralFeatures().add(eAttribute);
+
+        setFeatureKind(eAttribute, isElement ? ELEMENT_FEATURE : ATTRIBUTE_FEATURE);
+        setNamespace(eAttribute, namespace);
+
+        // Mark the bound as unspecified so that it won't be considered many
+        // but can nevertheless be recognized as being unspecified and perhaps still be treat as many.
+        //
+        if (isElement)
+        {
+          eAttribute.setUpperBound(ETypedElement.UNSPECIFIED_MULTIPLICITY);
+        }
+
+        return eAttribute;
+      }
+    }
+  }
+}
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/helper/BaseSDOXSDEcoreBuilder.java b/impl/src/main/java/org/apache/tuscany/sdo/helper/BaseSDOXSDEcoreBuilder.java
index f21a339..3d297fa 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/helper/BaseSDOXSDEcoreBuilder.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/helper/BaseSDOXSDEcoreBuilder.java
@@ -1,1771 +1,1771 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.helper;

-

-import java.util.ArrayList;

-import java.util.Collection;

-import java.util.Collections;

-import java.util.HashMap;

-import java.util.Iterator;

-import java.util.List;

-import java.util.Map;

-

-import org.eclipse.emf.ecore.EAttribute;

-import org.eclipse.emf.ecore.EClass;

-import org.eclipse.emf.ecore.EClassifier;

-import org.eclipse.emf.ecore.EDataType;

-import org.eclipse.emf.ecore.EEnum;

-import org.eclipse.emf.ecore.EOperation;

-import org.eclipse.emf.ecore.EPackage;

-import org.eclipse.emf.ecore.EParameter;

-import org.eclipse.emf.ecore.EReference;

-import org.eclipse.emf.ecore.EStructuralFeature;

-import org.eclipse.emf.ecore.ETypedElement;

-import org.eclipse.emf.ecore.EcoreFactory;

-import org.eclipse.emf.ecore.EcorePackage;

-import org.eclipse.emf.ecore.util.EcoreUtil;

-import org.eclipse.emf.ecore.util.ExtendedMetaData;

-import org.eclipse.emf.ecore.xml.type.XMLTypePackage;

-import org.eclipse.xsd.XSDAnnotation;

-import org.eclipse.xsd.XSDAttributeDeclaration;

-import org.eclipse.xsd.XSDAttributeUse;

-import org.eclipse.xsd.XSDComplexTypeContent;

-import org.eclipse.xsd.XSDComplexTypeDefinition;

-import org.eclipse.xsd.XSDComponent;

-import org.eclipse.xsd.XSDContentTypeCategory;

-import org.eclipse.xsd.XSDDerivationMethod;

-import org.eclipse.xsd.XSDElementDeclaration;

-import org.eclipse.xsd.XSDFeature;

-import org.eclipse.xsd.XSDLengthFacet;

-import org.eclipse.xsd.XSDMaxLengthFacet;

-import org.eclipse.xsd.XSDMinLengthFacet;

-import org.eclipse.xsd.XSDModelGroup;

-import org.eclipse.xsd.XSDModelGroupDefinition;

-import org.eclipse.xsd.XSDNamedComponent;

-import org.eclipse.xsd.XSDParticle;

-import org.eclipse.xsd.XSDSchema;

-import org.eclipse.xsd.XSDSimpleTypeDefinition;

-import org.eclipse.xsd.XSDTerm;

-import org.eclipse.xsd.XSDTypeDefinition;

-import org.eclipse.xsd.XSDVariety;

-import org.eclipse.xsd.XSDWildcard;

-import org.eclipse.xsd.ecore.XSDEcoreBuilder;

-import org.eclipse.xsd.util.XSDConstants;

-import org.w3c.dom.Element;

-import org.w3c.dom.Node;

-

-/**

- * An XSDEcoreBuilder that uses a supplied (SDO) ecore factory to create properties and types.

- */

-public class BaseSDOXSDEcoreBuilder extends XSDEcoreBuilder

-{

-  protected EcorePackage ecorePackage = EcorePackage.eINSTANCE;

-  protected EcoreFactory ecoreFactory = EcoreFactory.eINSTANCE;

-

-  public BaseSDOXSDEcoreBuilder(ExtendedMetaData extendedMetaData)

-  {

-    super(extendedMetaData);

-  }

-  

-  private void createDocumentRoot(XSDSchema xsdSchema, EPackage ePackage) {

-      EClass documentEClass = ecoreFactory.createEClass();

-      String name = getEcoreAttribute(xsdSchema, "documentRoot");

-      if (name == null)

-      {

-        name = "DocumentRoot";

-      }

-      documentEClass.setName(name);

-

-      extendedMetaData.setDocumentRoot(documentEClass);

-

-      ePackage.getEClassifiers().add(documentEClass);

-

-      createFeature

-        (documentEClass,

-         "mixed",

-         ecorePackage.getEFeatureMapEntry(),

-         null,

-         0,

-         -1);

-

-      EStructuralFeature xmlnsPrefixMapFeature =

-        createFeature

-          (documentEClass,

-           "xMLNSPrefixMap",

-           ecorePackage.getEStringToStringMapEntry(),

-           null,

-           0,

-           -1);

-      extendedMetaData.setName(xmlnsPrefixMapFeature, "xmlns:prefix");

-

-      EStructuralFeature xsiSchemaLocationMapFeature =

-        createFeature

-          (documentEClass,

-           "xSISchemaLocation",

-           ecorePackage.getEStringToStringMapEntry(),

-           null,

-           0,

-           -1);

-      extendedMetaData.setName(xsiSchemaLocationMapFeature, "xsi:schemaLocation");

-  }

-

-  public EPackage getEPackage(XSDNamedComponent xsdNamedComponent)

-  {

-    XSDSchema containingXSDSchema = xsdNamedComponent.getSchema();

-    if (containingXSDSchema != null && !xsdSchemas.contains(containingXSDSchema))

-    {

-      xsdSchemas.add(containingXSDSchema);

-      addInput(containingXSDSchema);

-      validate(containingXSDSchema);

-    }

-

-    String targetNamespace = 

-      containingXSDSchema == null ? 

-        xsdNamedComponent.getTargetNamespace() : 

-        containingXSDSchema.getTargetNamespace();

-    EPackage ePackage = (EPackage)targetNamespaceToEPackageMap.get(targetNamespace);

-    if (ePackage == null)

-    {

-      ePackage = ecoreFactory.createEPackage();

-      setAnnotations(ePackage, containingXSDSchema);

-      addOutput(ePackage);

-      if (targetNamespace == null)

-      {

-        if (containingXSDSchema == null)

-        {

-          containingXSDSchema = rootSchema;

-        }

-        ePackage.setName(validName(containingXSDSchema.eResource().getURI().trimFileExtension().lastSegment(), true));

-        ePackage.setNsURI(containingXSDSchema.eResource().getURI().toString());

-

-        // Also register against the nsURI for the case that the target namespace is null.

-        //

-        // extendedMetaData.putPackage(ePackage.getNsURI(), ePackage);

-      }

-      else

-      {

-        String qualifiedPackageName = qualifiedPackageName(targetNamespace);

-        ePackage.setName(qualifiedPackageName);

-        ePackage.setNsURI(targetNamespace);

-      }

-

-      String nsPrefix = ePackage.getName();

-      int index = nsPrefix.lastIndexOf('.');

-      nsPrefix = index == -1 ? nsPrefix : nsPrefix.substring(index + 1);

-

-      // http://www.w3.org/TR/REC-xml-names/#xmlReserved

-      // Namespace Constraint: Leading "XML"

-      // Prefixes beginning with the three-letter sequence x, m, l, in any case combination, 

-      // are reserved for use by XML and XML-related specifications.

-      //

-      if (nsPrefix.toLowerCase().startsWith("xml"))

-      {

-        nsPrefix = "_" + nsPrefix;

-      }

-      ePackage.setNsPrefix(nsPrefix);

-

-      extendedMetaData.setQualified(ePackage, targetNamespace != null);

-      extendedMetaData.putPackage(targetNamespace, ePackage);

-

-      targetNamespaceToEPackageMap.put(targetNamespace, ePackage);

-      

-      createDocumentRoot(xsdNamedComponent.getSchema(), ePackage);

-    }

-

-    return ePackage;

-  }

-

-  protected EClassifier computeEClassifier(XSDTypeDefinition xsdTypeDefinition)

-  {

-    if (xsdTypeDefinition == null)

-    {

-      return getBuiltInEClassifier(rootSchema.getSchemaForSchemaNamespace(), "anySimpleType");

-    }

-    else if (xsdTypeDefinition instanceof XSDSimpleTypeDefinition)

-    {

-      return computeEDataType((XSDSimpleTypeDefinition)xsdTypeDefinition);

-    }

-    else

-    {

-      return computeEClass((XSDComplexTypeDefinition)xsdTypeDefinition);

-    }

-  }

-

-  protected EDataType computeEDataType(XSDSimpleTypeDefinition xsdSimpleTypeDefinition)

-  {

-    if (xsdSimpleTypeDefinition == null)

-    {

-      return (EDataType)getBuiltInEClassifier(rootSchema.getSchemaForSchemaNamespace(), "anySimpleType");

-    }

-    else if (XSDConstants.isSchemaForSchemaNamespace(xsdSimpleTypeDefinition.getTargetNamespace()))

-    {

-      String name = xsdSimpleTypeDefinition.getName();

-      if (name != null)

-      {

-        EDataType result = (EDataType)getBuiltInEClassifier(xsdSimpleTypeDefinition.getTargetNamespace(), "anyType".equals(name) ? "anySimpleType" : name);

-        if (result != null)

-        {

-          return result;

-        }

-      }

-    }

-    else if (xsdSimpleTypeDefinition.getContainer() == null)

-    {

-      return (EDataType)getBuiltInEClassifier(rootSchema.getSchemaForSchemaNamespace(), "anySimpleType");

-    }

-

-    String explicitInstanceClassName = getEcoreAttribute(xsdSimpleTypeDefinition, "instanceClass");

-    if (explicitInstanceClassName != null)

-    {

-      EDataType eDataType = ecoreFactory.createEDataType();

-      setAnnotations(eDataType, xsdSimpleTypeDefinition);

-

-      String aliasName = getEcoreAttribute(xsdSimpleTypeDefinition, "name");

-      if (aliasName == null)

-      {

-        aliasName = validAliasName(xsdSimpleTypeDefinition, true);

-      }

-      eDataType.setName(aliasName);

-      extendedMetaData.setName(eDataType, xsdSimpleTypeDefinition.getAliasName());

-

-      eDataType.setInstanceClassName(explicitInstanceClassName);

-

-      EPackage ePackage = getEPackage(xsdSimpleTypeDefinition);

-      addToSortedList(ePackage.getEClassifiers(), eDataType);

-

-      checkForPrimitive(xsdSimpleTypeDefinition, eDataType);

-

-      handleFacets(xsdSimpleTypeDefinition, eDataType);

-

-      String constraints = getEcoreAttribute(xsdSimpleTypeDefinition, "constraints");

-      if (constraints != null)

-      {

-        EcoreUtil.setAnnotation(eDataType, EcorePackage.eNS_URI, "constraints", constraints);

-      }

-

-      if ("false".equals(getEcoreAttribute(xsdSimpleTypeDefinition, "serializable")))

-      {

-        eDataType.setSerializable(false);

-      }

-      return eDataType;

-    }

-    else

-    {

-      EEnum eEnum = computeEEnum(xsdSimpleTypeDefinition);

-      if (eEnum != null)

-      {

-        return eEnum;

-      }

-      else

-      {

-        XSDSimpleTypeDefinition baseTypeDefinition = xsdSimpleTypeDefinition.getBaseTypeDefinition();

-        if (baseTypeDefinition != null)

-        {

-          EDataType eDataType = ecoreFactory.createEDataType();

-          setAnnotations(eDataType, xsdSimpleTypeDefinition);

-

-          String name = getEcoreAttribute(xsdSimpleTypeDefinition, "name");

-          if (name == null)

-          {

-            name = validAliasName(xsdSimpleTypeDefinition, true);

-          }

-

-          eDataType.setName(name);

-          extendedMetaData.setName(eDataType, xsdSimpleTypeDefinition.getAliasName());

-

-          EPackage ePackage = getEPackage(xsdSimpleTypeDefinition);

-          addToSortedList(ePackage.getEClassifiers(), eDataType);

-

-          if (baseTypeDefinition.getVariety() != xsdSimpleTypeDefinition.getVariety())

-          {

-            if (xsdSimpleTypeDefinition.getVariety() == XSDVariety.LIST_LITERAL)

-            {

-              EDataType itemEDataType = getEDataType(xsdSimpleTypeDefinition.getItemTypeDefinition());

-              extendedMetaData.setItemType(eDataType, itemEDataType);

-              eDataType.setInstanceClassName("java.util.List");

-            }

-            else

-            {

-              String instanceClassName = null;

-              List memberTypes = new ArrayList();

-              for (Iterator i = xsdSimpleTypeDefinition.getMemberTypeDefinitions().iterator(); i.hasNext(); )

-              {

-                XSDSimpleTypeDefinition memberTypeDefinition = (XSDSimpleTypeDefinition)i.next();

-                EDataType memberEDataType = getEDataType(memberTypeDefinition);

-                memberTypes.add(memberEDataType);

-                String memberInstanceClassName = memberEDataType.getInstanceClassName();

-                if (memberInstanceClassName == null && memberEDataType instanceof EEnum)

-                {

-                  memberInstanceClassName = "org.eclipse.emf.common.util.Enumerator";

-                }

-                if (instanceClassName == null)

-                {

-                  instanceClassName = memberInstanceClassName;

-                }

-                else if (instanceClassName != memberInstanceClassName)

-                {

-                  instanceClassName = "java.lang.Object";

-                }

-              }

-              extendedMetaData.setMemberTypes(eDataType, memberTypes);

-              eDataType.setInstanceClassName(instanceClassName);

-            }

-          }

-          else

-          {

-            EDataType baseEDataType = getEDataType(baseTypeDefinition);

-            extendedMetaData.setBaseType(eDataType, baseEDataType);

-            String instanceClassName = getInstanceClassName(xsdSimpleTypeDefinition, baseEDataType);

-            eDataType.setInstanceClassName

-              (instanceClassName == null ? 

-                 "org.eclipse.emf.common.util.Enumerator" : 

-                 instanceClassName);

-          }

-

-          checkForPrimitive(xsdSimpleTypeDefinition, eDataType);

-          handleFacets(xsdSimpleTypeDefinition, eDataType);

-

-          String constraints = getEcoreAttribute(xsdSimpleTypeDefinition, "constraints");

-          if (constraints != null)

-          {

-            EcoreUtil.setAnnotation(eDataType, EcorePackage.eNS_URI, "constraints", constraints);

-          }

-

-          if ("false".equals(getEcoreAttribute(xsdSimpleTypeDefinition, "serializable")))

-          {

-            eDataType.setSerializable(false);

-          }

-

-          return eDataType;

-        }

-      }

-      return (EDataType)getBuiltInEClassifier(rootSchema.getSchemaForSchemaNamespace(), "anySimpleType");

-    }

-  }

-

-  protected void checkForPrimitive(EDataType eDataType)

-  {

-    int index = PRIMITIVES.indexOf(eDataType.getInstanceClassName());

-    if (index != -1 || eDataType instanceof EEnum)

-    {

-      EDataType eDataTypeObject = ecoreFactory.createEDataType();

-      eDataTypeObject.setName(eDataType.getName() + "Object");

-      if (index != -1)

-      {

-        eDataTypeObject.setInstanceClassName(PRIMITIVE_WRAPPERS[index]);

-      }

-      else

-      {

-        eDataTypeObject.setInstanceClassName("org.eclipse.emf.common.util.Enumerator");

-      }

-      extendedMetaData.setName(eDataTypeObject, extendedMetaData.getName(eDataType) + ":Object");

-      addToSortedList(eDataType.getEPackage().getEClassifiers(), eDataTypeObject);

-      extendedMetaData.setBaseType(eDataTypeObject, eDataType);

-

-      typeToTypeObjectMap.put(eDataType, eDataTypeObject);

-    }

-  }

-

-  public EClass computeEClass(XSDComplexTypeDefinition xsdComplexTypeDefinition)

-  {

-    if (xsdComplexTypeDefinition == null)

-    {

-      return (EClass)getBuiltInEClassifier(rootSchema.getSchemaForSchemaNamespace(), "anyType");

-    }

-    else if (XSDConstants.isSchemaForSchemaNamespace(xsdComplexTypeDefinition.getTargetNamespace()))

-    {

-      String name = xsdComplexTypeDefinition.getName();

-      if (name != null)

-      {

-        EClass result = (EClass)getBuiltInEClassifier(xsdComplexTypeDefinition.getTargetNamespace(), name);

-        if (result != null)

-        {

-          return result;

-        }

-      }

-    }

-    else if (xsdComplexTypeDefinition.getContainer() == null)

-    {

-      return (EClass)getBuiltInEClassifier(rootSchema.getSchemaForSchemaNamespace(), "anyType");

-    }

-

-    EClass eClass = ecoreFactory.createEClass();

-    setAnnotations(eClass, xsdComplexTypeDefinition);

-    // Do this early to prevent recursive loop.

-    xsdComponentToEModelElementMap.put(xsdComplexTypeDefinition, eClass);

-

-    if ("true".equals(getEcoreAttribute(xsdComplexTypeDefinition, "interface")))

-    {

-      eClass.setInterface(true);

-    }

-

-    String instanceClassName = getEcoreAttribute(xsdComplexTypeDefinition, "instanceClass");

-    if (instanceClassName != null)

-    {

-      eClass.setInstanceClassName(instanceClassName);

-    }

-

-    String aliasName = getEcoreAttribute(xsdComplexTypeDefinition, "name");

-    if (aliasName == null)

-    {

-      aliasName = validAliasName(xsdComplexTypeDefinition, true);

-    }

-    eClass.setName(aliasName);

-    extendedMetaData.setName(eClass, xsdComplexTypeDefinition.getAliasName());

-

-    String constraints = getEcoreAttribute(xsdComplexTypeDefinition, "constraints");

-    if (constraints != null)

-    {

-      EcoreUtil.setAnnotation(eClass, EcorePackage.eNS_URI, "constraints", constraints);

-    }

-

-    EPackage ePackage = getEPackage(xsdComplexTypeDefinition);

-    addToSortedList(ePackage.getEClassifiers(), eClass);

-

-    if (xsdComplexTypeDefinition.isAbstract())

-    {

-      eClass.setAbstract(true);

-    }

-

-    EClass baseClass = null;

-    XSDTypeDefinition baseTypeDefinition = xsdComplexTypeDefinition.getBaseTypeDefinition();

-    if (!baseTypeDefinition.isCircular())

-    {

-      EClassifier baseType = getEClassifier(baseTypeDefinition);

-      if (baseType instanceof EClass && baseType != ecorePackage.getEObject())

-      {

-        eClass.getESuperTypes().add(baseClass = (EClass)baseType);

-      }

-    }

-

-    boolean isRestriction = 

-      !eClass.getESuperTypes().isEmpty() && 

-        xsdComplexTypeDefinition.getDerivationMethod() == XSDDerivationMethod.RESTRICTION_LITERAL;

-

-    for (Iterator i = getEcoreTypeQNamesAttribute(xsdComplexTypeDefinition, "implements").iterator(); i.hasNext(); )

-    {

-      XSDTypeDefinition mixin = (XSDTypeDefinition)i.next();

-      if (!XSDConstants.isURType(mixin))

-      {

-        EClassifier mixinType = getEClassifier(mixin);

-        if (mixinType instanceof EClass && mixinType != ecorePackage.getEObject())

-        {

-          eClass.getESuperTypes().add(mixinType);

-        }

-      }

-    }

-

-    // 51210

-    // EAnnotation contentParticle = null;

-

-    if (xsdComplexTypeDefinition.getContentTypeCategory() == XSDContentTypeCategory.SIMPLE_LITERAL)

-    {

-      extendedMetaData.setContentKind(eClass, ExtendedMetaData.SIMPLE_CONTENT);

-      if (!"SimpleAnyType".equals(eClass.getName()) || !XMLTypePackage.eNS_URI.equals(eClass.getEPackage().getNsURI()))

-      {

-        if (eClass.getEAllStructuralFeatures().isEmpty())

-        {

-          XSDComplexTypeContent xsdComplexTypeContent = xsdComplexTypeDefinition.getContent();

-          String name = getEcoreAttribute(xsdComplexTypeContent, "name");

-          if (name == null)

-          {

-            name = "value";

-          }

-          createFeature

-            (eClass,

-             null,

-             name,

-             xsdComplexTypeContent,

-             false);

-        }

-        else

-        {

-          XSDSimpleTypeDefinition xsdSimpleTypeDefinition = xsdComplexTypeDefinition.getSimpleType();

-          getEClassifier(xsdSimpleTypeDefinition);

-        }

-      }

-    }

-    else 

-    {

-      EStructuralFeature globalGroup = null;

-      boolean isMixed = xsdComplexTypeDefinition.getContentTypeCategory() == XSDContentTypeCategory.MIXED_LITERAL;

-      String featureMapName = getEcoreAttribute(xsdComplexTypeDefinition, "featureMap");

-      if (eClass.getESuperTypes().isEmpty() ?

-            "true".equals(getEcoreAttribute(xsdComplexTypeDefinition, "mixed")) :

-            extendedMetaData.getMixedFeature((EClass)eClass.getESuperTypes().get(0)) != null)

-      {

-        isMixed = true;

-      }

-      extendedMetaData.setContentKind

-        (eClass, 

-         isMixed ? 

-           ExtendedMetaData.MIXED_CONTENT : 

-           xsdComplexTypeDefinition.getContentTypeCategory() == XSDContentTypeCategory.EMPTY_LITERAL ?

-             ExtendedMetaData.EMPTY_CONTENT :

-             ExtendedMetaData.ELEMENT_ONLY_CONTENT);

-      if (isMixed)

-      {

-        EStructuralFeature mixedFeature = extendedMetaData.getMixedFeature(eClass);

-        if (mixedFeature == null)

-        {

-          if (featureMapName == null)

-          {

-            featureMapName = "mixed";

-          }

-          mixedFeature =

-            createFeature

-              (eClass,

-               featureMapName,

-               ecorePackage.getEFeatureMapEntry(),

-               null,

-               0,

-               -1);

-          extendedMetaData.setName(mixedFeature, ":mixed");

-        }

-      }

-      else 

-      {

-        globalGroup = extendedMetaData.getElement(eClass, null, ":group");

-        if (globalGroup == null && featureMapName != null && eClass.getESuperTypes().isEmpty())

-        {

-          globalGroup =

-            createFeature

-              (eClass,

-               featureMapName,

-               ecorePackage.getEFeatureMapEntry(),

-               null,

-               0,

-               -1);

-          extendedMetaData.setName(globalGroup, ":group");

-          extendedMetaData.setFeatureKind(globalGroup, ExtendedMetaData.GROUP_FEATURE);

-        }

-      }

-

-      if (xsdComplexTypeDefinition.getContent() != null)

-      {

-        // 51210

-        // Map particleMap = new HashMap();

-        Map groups = new HashMap();

-        List particleInformation = collectParticles((XSDParticle)xsdComplexTypeDefinition.getContent());

-        for (Iterator i = particleInformation.iterator(); i.hasNext(); )

-        {

-          EffectiveOccurrence effectiveOccurrence = (EffectiveOccurrence)i.next();

-          XSDParticle xsdParticle = effectiveOccurrence.xsdParticle;

-          EStructuralFeature group = (EStructuralFeature)groups.get(effectiveOccurrence.xsdModelGroup);

-          XSDTerm xsdTerm = xsdParticle.getTerm();

-          EStructuralFeature eStructuralFeature = null;

-          String name = getEcoreAttribute(xsdParticle, "name");

-          if (xsdTerm instanceof XSDModelGroup)

-          {

-            if (!isRestriction) 

-            {

-              XSDModelGroup xsdModelGroup = (XSDModelGroup)xsdTerm;

-              if (name == null)

-              {

-                name = getEcoreAttribute(xsdParticle, "featureMap");

-                if (name == null)

-                {

-                  name = getEcoreAttribute(xsdModelGroup, "name");

-                  if (name == null)

-                  {

-                    name = getEcoreAttribute(xsdModelGroup, "featureMap");

-                    if (name == null)

-                    {

-                      if (xsdModelGroup.getContainer() instanceof XSDModelGroupDefinition)

-                      {

-                        XSDModelGroupDefinition xsdModelGroupDefinition = (XSDModelGroupDefinition)xsdModelGroup.getContainer();

-                        name =  getEcoreAttribute(xsdModelGroupDefinition, "name");

-                        if (name == null)

-                        {

-                          name = validName(xsdModelGroupDefinition.getName(), true);

-                        }

-                      }

-                      else

-                      {

-                        name = "group";

-                      }

-                    }

-                  }

-                }

-              }

-

-              eStructuralFeature =

-                createFeature

-                  (eClass,

-                   name,

-                   ecorePackage.getEFeatureMapEntry(),

-                   xsdParticle,

-                   0,

-                   -1);

-              groups.put(xsdTerm, eStructuralFeature);

-              extendedMetaData.setName(eStructuralFeature, name + ":" + eClass.getEAllStructuralFeatures().indexOf(eStructuralFeature));

-            }

-          }

-          else if (xsdTerm instanceof XSDWildcard)

-          {

-            if (!isRestriction) 

-            {

-              if (name == null)

-              {

-                name = getEcoreAttribute(xsdTerm, "name");

-                if (name == null)

-                {

-                  name = "any";

-                }

-              }

-              eStructuralFeature =

-                createFeature

-                  (eClass,

-                   name,

-                   ecorePackage.getEFeatureMapEntry(),

-                   xsdParticle,

-                   effectiveOccurrence.minOccurs,

-                   effectiveOccurrence.maxOccurs);

-              // 51210

-              // particleMap.put(xsdParticle, eStructuralFeature);

-            }

-          }

-          else

-          {

-            XSDElementDeclaration xsdElementDeclaration = (XSDElementDeclaration)xsdTerm;

-

-            boolean isRedundant = false;

-            if (isRestriction)

-            {

-              isRedundant = 

-                extendedMetaData.getElement

-                  (baseClass, xsdElementDeclaration.getTargetNamespace(), xsdElementDeclaration.getName()) != null;

-              

-              if (!isRedundant)

-              {

-                group = 

-                  extendedMetaData.getElementWildcardAffiliation

-                    (baseClass, xsdElementDeclaration.getTargetNamespace(), xsdElementDeclaration.getName());

-              }  

-            }

-

-            if (!isRedundant) 

-            {

-              if (name == null)

-              {

-                name = getEcoreAttribute(xsdElementDeclaration, "name");

-                if (name == null)

-                {

-                  name = validName(xsdElementDeclaration.getName(), true);

-                }

-              }

-

-              String groupName = getEcoreAttribute(xsdParticle, "featureMap");

-              if (groupName == null)

-              {

-                groupName = getEcoreAttribute(xsdElementDeclaration, "featureMap");

-              }

-

-              if (!"".equals(groupName) &&

-                   (groupName != null  ||

-                      xsdElementDeclaration.isAbstract() || 

-                      xsdElementDeclaration.getSubstitutionGroup().size() > 1))

-              {

-                if (groupName == null)

-                {

-                  groupName = name + "Group";

-                }

-                eStructuralFeature = 

-                  createFeature

-                    (eClass,

-                     groupName,

-                     ecorePackage.getEFeatureMapEntry(),

-                     xsdParticle,

-                     effectiveOccurrence.minOccurs,

-                     effectiveOccurrence.maxOccurs);

-

-                eStructuralFeature.setChangeable(true);

-

-                extendedMetaData.setFeatureKind(eStructuralFeature, ExtendedMetaData.GROUP_FEATURE);

-                extendedMetaData.setName(eStructuralFeature, xsdElementDeclaration.getName() + ":group");

-

-                if (group != null)

-                {

-                  extendedMetaData.setGroup(eStructuralFeature, group);

-                  eStructuralFeature.setDerived(true);

-                  eStructuralFeature.setTransient(true);

-                  eStructuralFeature.setVolatile(true);

-                }

-                else if (isMixed)

-                {

-                  eStructuralFeature.setDerived(true);

-                  eStructuralFeature.setTransient(true);

-                  eStructuralFeature.setVolatile(true);

-                }

-                else if (globalGroup != null)

-                {

-                  extendedMetaData.setGroup(eStructuralFeature, globalGroup);

-                  eStructuralFeature.setDerived(true);

-                  eStructuralFeature.setTransient(true);

-                  eStructuralFeature.setVolatile(true);

-                }

-

-                group = eStructuralFeature;

-              }

-

-              eStructuralFeature = 

-                 createFeature(eClass, xsdElementDeclaration, name, xsdParticle, effectiveOccurrence.minOccurs, effectiveOccurrence.maxOccurs);

-              // 51210

-              // particleMap.put(xsdParticle, eStructuralFeature);

-

-              // If the group is turned off, we better make the feature changeable.

-              //

-              if (!eStructuralFeature.isChangeable() && group == null && getEcoreAttribute(xsdParticle, xsdElementDeclaration, "changeable") == null)

-              {

-                eStructuralFeature.setChangeable(true);

-              }

-            }

-          }

-

-          if (eStructuralFeature != null) 

-          {

-            if (group != null)

-            {

-              extendedMetaData.setGroup(eStructuralFeature, group);

-              eStructuralFeature.setDerived(true);

-              eStructuralFeature.setTransient(true);

-              eStructuralFeature.setVolatile(true);

-            }

-            else if (isMixed)

-            {

-              eStructuralFeature.setDerived(true);

-              eStructuralFeature.setTransient(true);

-              eStructuralFeature.setVolatile(true);

-            }

-            else if (globalGroup != null)

-            {

-              extendedMetaData.setGroup(eStructuralFeature, globalGroup);

-              eStructuralFeature.setDerived(true);

-              eStructuralFeature.setTransient(true);

-              eStructuralFeature.setVolatile(true);

-            }

-          }

-        }

-

-        // 51210

-        // contentParticle = computeParticleConstraints(eClass, particleMap, (XSDParticle)xsdComplexTypeDefinition.getContent());

-      }

-    }

-

-    // 51210

-    // EAnnotation attributeParticle = null;

-    // if (isRestriction)

-    // {

-    //   attributeParticle = ecoreFactory.createEAnnotation();

-    //   attributeParticle.setSource("attributes");

-    // }

-

-    XSDWildcard baseXSDWildcard = null;

-    Collection baseAttributeUses = Collections.EMPTY_LIST;

-    Map baseAttributeURIs = new HashMap();

-    if (baseTypeDefinition instanceof XSDComplexTypeDefinition)

-    {

-      XSDComplexTypeDefinition complexBaseTypeDefinition = (XSDComplexTypeDefinition)baseTypeDefinition;

-      baseXSDWildcard = complexBaseTypeDefinition.getAttributeWildcard();

-      baseAttributeUses = complexBaseTypeDefinition.getAttributeUses();

-      for (Iterator i = baseAttributeUses.iterator(); i.hasNext(); )

-      {

-        XSDAttributeUse xsdAttributeUse = (XSDAttributeUse)i.next();

-        baseAttributeURIs.put(xsdAttributeUse.getAttributeDeclaration().getURI(), xsdAttributeUse);

-      }

-    }

-

-    for (Iterator i = getAttributeUses(xsdComplexTypeDefinition).iterator(); i.hasNext(); )

-    {

-      XSDAttributeUse xsdAttributeUse = (XSDAttributeUse)i.next();

-      XSDAttributeDeclaration xsdAttributeDeclaration = xsdAttributeUse.getAttributeDeclaration();

-      if (baseAttributeURIs.remove(xsdAttributeDeclaration.getURI()) == null)

-      {

-        String name = getEcoreAttribute(xsdAttributeUse, "name");

-        if (name == null)

-        {

-          name = getEcoreAttribute(xsdAttributeDeclaration, "name");

-        }

-        if (name == null)

-        {

-          name = validName(xsdAttributeDeclaration.getName(), true);

-        }

-

-        EStructuralFeature eStructuralFeature = 

-          createFeature(eClass, xsdAttributeDeclaration, name, xsdAttributeUse, xsdAttributeUse.isRequired());

-      

-        if (isRestriction)

-        {

-          EStructuralFeature attributeWildcardEStructuralFeature = 

-            extendedMetaData.getAttributeWildcardAffiliation

-              (baseClass, xsdAttributeDeclaration.getTargetNamespace(), xsdAttributeDeclaration.getName());

-          if (attributeWildcardEStructuralFeature != null)

-          {

-            extendedMetaData.setGroup(eStructuralFeature, attributeWildcardEStructuralFeature);

-            eStructuralFeature.setDerived(true);

-            eStructuralFeature.setTransient(true);

-            eStructuralFeature.setVolatile(true);

-          }

-        } 

-      }

-      /* 51210

-      else if (isRestriction && !baseAttributeUses.contains(xsdAttributeUse))

-      {

-        EStructuralFeature eStructuralFeature = 

-          extendedMetaData.getAttribute(eClass, xsdAttributeDeclaration.getTargetNamespace(), xsdAttributeDeclaration.getName());

-        if (eStructuralFeature != null)

-        {

-          EAnnotation attributeEAnnotation = ecoreFactory.createEAnnotation();

-          if (xsdAttributeUse.isRequired())

-          {

-            attributeEAnnotation.getDetails().put("minOccurs", "1");

-          }

-          attributeEAnnotation.getReferences().add(eStructuralFeature);

-

-          if (xsdAttributeDeclaration.getTypeDefinition() != null)

-          {

-            EClassifier type = getEClassifier(xsdAttributeDeclaration.getTypeDefinition());

-            if (type != eStructuralFeature.getEType() && type != null)

-            {

-              attributeEAnnotation.getReferences().add(type);

-            }

-          }

-

-          attributeParticle.getContents().add(attributeEAnnotation);

-        }

-      }

-      */

-    }

-

-    /* 51210

-    if (isRestriction && !baseAttributeURIs.isEmpty())

-    {

-      for (Iterator i = baseAttributeURIs.values().iterator(); i.hasNext(); )

-      {

-        XSDAttributeUse xsdAttributeUse = (XSDAttributeUse)i.next();

-        XSDAttributeDeclaration xsdAttributeDeclaration = xsdAttributeUse.getAttributeDeclaration();

-        EStructuralFeature eStructuralFeature = 

-          extendedMetaData.getAttribute(eClass, xsdAttributeDeclaration.getTargetNamespace(), xsdAttributeDeclaration.getName());

-        if (eStructuralFeature != null)

-        {

-          EAnnotation attributeEAnnotation = ecoreFactory.createEAnnotation();

-          attributeEAnnotation.getReferences().add(eStructuralFeature);

-          attributeEAnnotation.getDetails().put("maxOccurs", "0");

-          attributeParticle.getContents().add(attributeEAnnotation);

-        }

-      }

-    }

-    */

-

-    XSDWildcard xsdWildcard = xsdComplexTypeDefinition.getAttributeWildcard();

-    if (xsdWildcard != null && baseXSDWildcard != xsdWildcard || XSDConstants.isURType(xsdComplexTypeDefinition))

-    {

-      if (isRestriction && !XSDConstants.isURType(xsdComplexTypeDefinition))

-      {

-        // 51210

-        // attributeParticle.getDetails().put

-        //   ("wildcard", BasicExtendedMetaData.getEncodedWildcards(xsdComplexTypeDefinition.getTargetNamespace(), getWildcards(xsdWildcard)));

-      }

-      else

-      {

-        String name = getEcoreAttribute(xsdWildcard, "name");

-        if (name == null)

-        {

-          name = "anyAttribute";

-        }

-        createFeature

-          (eClass,

-           name,

-           ecorePackage.getEFeatureMapEntry(),

-           xsdWildcard,

-           0,

-           -1);

-      }

-    }

-

-    if (isRestriction)

-    {

-      // 51210

-      // EAnnotation restrictionParticle = ecoreFactory.createEAnnotation();

-      // restrictionParticle.setSource("restriction");

-      // if (contentParticle != null)

-      // {

-      //  restrictionParticle.getContents().add(contentParticle);

-      // }

-      // if (!attributeParticle.getContents().isEmpty() || !attributeParticle.getDetails().isEmpty())

-      // {

-      //   restrictionParticle.getContents().add(attributeParticle);

-      // }

-      // contentParticle = restrictionParticle;

-

-      int baseContentKind = extendedMetaData.getContentKind((EClass)eClass.getESuperTypes().get(0));

-      if (baseContentKind == ExtendedMetaData.MIXED_CONTENT && 

-            xsdComplexTypeDefinition.getContentTypeCategory() == XSDContentTypeCategory.SIMPLE_LITERAL)

-      {

-        extendedMetaData.setContentKind(eClass, ExtendedMetaData.SIMPLE_CONTENT);

-        EStructuralFeature eStructuralFeature =

-          createFeature

-            (eClass,

-             "rawValue",

-             getBuiltInEClassifier(xsdComplexTypeDefinition.getSchema().getSchemaForSchemaNamespace(), "string"),

-             null,

-             0,

-             1);

-        eStructuralFeature.setDerived(true);

-        eStructuralFeature.setTransient(true);

-        eStructuralFeature.setVolatile(true);

-

-        eStructuralFeature =

-          createFeature

-            (eClass,

-             "value",

-             getBuiltInEClassifier(xsdComplexTypeDefinition.getSchema().getSchemaForSchemaNamespace(), "anySimpleType"),

-             null,

-             0,

-             1);

-        eStructuralFeature.setDerived(true);

-        eStructuralFeature.setTransient(true);

-        eStructuralFeature.setVolatile(true);

-

-        if ("SimpleAnyType".equals(eClass.getName()) && XMLTypePackage.eNS_URI.equals(eClass.getEPackage().getNsURI()))

-        {

-          eStructuralFeature =

-            createFeature

-              (eClass,

-               "instanceType",

-               ecorePackage.getEDataType(),

-               null,

-               1,

-               1);

-

-          ((EReference)eStructuralFeature).setResolveProxies(false);

-        }

-      }

-      else

-      {

-        extendedMetaData.setContentKind(eClass, baseContentKind);

-      }

-    }

-

-    // 51210

-    // extendedMetaData.setContent(eClass, contentParticle);

-

-    XSDAnnotation xsdAnnotation = xsdComplexTypeDefinition.getAnnotation();

-    if (xsdAnnotation != null)

-    {

-      List applicationInformationList = xsdAnnotation.getApplicationInformation(EcorePackage.eNS_URI);

-      for (Iterator i = applicationInformationList.iterator(); i.hasNext(); )

-      {

-        Element applicationInformation = (Element)i.next();

-        if ("operations".equals(applicationInformation.getAttributeNS(EcorePackage.eNS_URI, "key")))

-        {

-          for (Iterator j =  getElements(applicationInformation, "operation").iterator(); j.hasNext(); )

-          {

-            EOperation eOperation = ecoreFactory.createEOperation();

-            Element operation = (Element)j.next();

-            String operationName = operation.getAttributeNS(null, "name");

-            eOperation.setName(operationName);

-            XSDTypeDefinition returnType = getEcoreTypeQNameAttribute(xsdComplexTypeDefinition, operation, null, "type");

-            if (returnType != null)

-            {

-              EClassifier returnEType = getEClassifier(returnType);

-              eOperation.setEType(returnEType);

-            }

-            

-            List exceptions = getEcoreTypeQNamesAttribute(xsdComplexTypeDefinition, operation, null, "exceptions");

-            for (Iterator k = exceptions.iterator(); k.hasNext(); )

-            {

-              XSDTypeDefinition exceptionTypeDefinition = (XSDTypeDefinition)k.next();

-              eOperation.getEExceptions().add(getEClassifier(exceptionTypeDefinition));

-            }

-          

-            for (Iterator k = getElements(operation, "parameter").iterator(); k.hasNext(); )

-            {

-              EParameter eParameter = ecoreFactory.createEParameter();

-              Element parameter = (Element)k.next();

-              String paramaterName = parameter.getAttributeNS(null, "name");

-              XSDTypeDefinition parameterType = getEcoreTypeQNameAttribute(xsdComplexTypeDefinition, parameter, null, "type");

-              EClassifier parameterEType = getEClassifier(parameterType);

-              eParameter.setName(paramaterName);

-              eParameter.setEType(parameterEType);

-

-              populateETypedElement(eParameter, parameter);

-              eOperation.getEParameters().add(eParameter);

-            }

-            

-            List body = getElements(operation, "body");

-            if (!body.isEmpty())

-            {

-              EcoreUtil.setAnnotation(eOperation, "http://www.eclipse.org/emf/2002/GenModel", "body", getText((Element)body.get(0)));

-            }

-

-            populateETypedElement(eOperation, operation);

-            eClass.getEOperations().add(eOperation);

-          }

-        }

-      }

-    }

-    return eClass;

-  }

-    

-  private String getText(Element element)

-  {

-    StringBuffer text = new StringBuffer();

-    for (Node node = element.getFirstChild(); node != null; node = node.getNextSibling())

-    {

-      switch (node.getNodeType())

-      {

-        case Node.TEXT_NODE:

-        case Node.CDATA_SECTION_NODE:

-        {

-          text.append(node.getNodeValue());

-        }

-      }

-    }

-    return text.toString();

-  }

-

-  private List getElements(Element element, String localName)

-  {

-    List result = new ArrayList();

-    for (Node node = element.getFirstChild(); node != null; node = node.getNextSibling())

-    {

-      if (node.getNodeType() == Node.ELEMENT_NODE)

-      {

-        Element child = (Element)node;

-        if (localName.equals(child.getLocalName()) && child.getNamespaceURI() == null)

-        {

-          result.add(child);

-        }

-      }

-    }

-    return result;

-  }

-  

-  protected EStructuralFeature createFeature

-    (EClass eClass, String name, EClassifier type, XSDComponent xsdComponent, int minOccurs, int maxOccurs)

-  {

-    if (xsdComponent != null)

-    {

-      XSDSchema containingXSDSchema = xsdComponent.getSchema();

-      if (containingXSDSchema != null && !xsdSchemas.contains(containingXSDSchema))

-      {

-        xsdSchemas.add(containingXSDSchema);

-        addInput(containingXSDSchema);

-        validate(containingXSDSchema);

-      }

-    }

-    else if (extendedMetaData.getContentKind(eClass) == ExtendedMetaData.MIXED_CONTENT)

-    {

-      if (type == ecorePackage.getEFeatureMapEntry())

-      {

-        EAttribute eAttribute = ecoreFactory.createEAttribute();

-        setAnnotations(eAttribute, xsdComponent);

-        eAttribute.setName(Character.toLowerCase(name.charAt(0)) + name.substring(1));

-        eAttribute.setUnique(false);

-        eAttribute.setEType(type);

-        eAttribute.setLowerBound(minOccurs);

-        eAttribute.setUpperBound(maxOccurs);

-        eClass.getEStructuralFeatures().add(eAttribute);

-        extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ELEMENT_WILDCARD_FEATURE);

-        extendedMetaData.setName(eAttribute, ":" + eAttribute.getName());

-        return eAttribute;

-      }

-      else

-      {

-        EReference eReference = ecoreFactory.createEReference();

-        setAnnotations(eReference, xsdComponent);

-        eReference.setName(name);

-        eReference.setEType(ecorePackage.getEStringToStringMapEntry());

-        eReference.setLowerBound(0);

-        eReference.setUpperBound(-1);

-        eReference.setContainment(true);

-        eReference.setResolveProxies(false);

-        eReference.setTransient(true);

-        eClass.getEStructuralFeatures().add(eReference);

-        extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.ATTRIBUTE_FEATURE);

-        return eReference;

-      }

-    }

-

-    if (type instanceof EClass)

-    {

-      EReference eReference = ecoreFactory.createEReference();

-      setAnnotations(eReference, xsdComponent);

-      eReference.setName(Character.toLowerCase(name.charAt(0)) + name.substring(1));

-      eReference.setEType(type);

-      eReference.setLowerBound(minOccurs);

-      eReference.setUpperBound(maxOccurs);

-

-      eClass.getEStructuralFeatures().add(eReference);

-      if (xsdComponent == null || xsdComponent instanceof XSDSimpleTypeDefinition)

-      {

-        extendedMetaData.setName(eReference, ":" + eClass.getEAllStructuralFeatures().indexOf(eReference));

-        extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.SIMPLE_FEATURE);

-        eReference.setResolveProxies(!isLocalReferenceType((XSDSimpleTypeDefinition)xsdComponent));

-      }

-      else 

-      {

-        map(xsdComponent, eReference);

-        if (xsdComponent instanceof XSDParticle)

-        {

-          eReference.setContainment(true);

-          eReference.setResolveProxies(false);

-

-          XSDParticle xsdParticle = (XSDParticle)xsdComponent;

-

-          XSDTerm xsdTerm = ((XSDParticle)xsdComponent).getTerm();

-          if (xsdTerm instanceof XSDElementDeclaration)

-          {

-            XSDElementDeclaration xsdElementDeclaration = (XSDElementDeclaration)xsdTerm;

-            extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.ELEMENT_FEATURE);

-            extendedMetaData.setName(eReference, xsdElementDeclaration.getName());

-            extendedMetaData.setNamespace(eReference, xsdElementDeclaration.getTargetNamespace());

-

-            XSDTypeDefinition xsdType = getEffectiveTypeDefinition(xsdParticle, xsdElementDeclaration);

-            if (xsdType instanceof XSDSimpleTypeDefinition)

-            {

-              eReference.setContainment(false);

-              eReference.setResolveProxies(!isLocalReferenceType((XSDSimpleTypeDefinition)xsdType));

-            }

-

-            if (maxOccurs == 1 && xsdElementDeclaration.isNillable())

-            {

-              eReference.setUnsettable(true);

-            }

-

-            if (xsdElementDeclaration.isAbstract())

-            {

-              eReference.setChangeable(false);

-            }

-

-            String opposite = getEcoreAttribute(xsdParticle, "opposite");

-            if (opposite != null)

-            {

-              eReferenceToOppositeNameMap.put(eReference, opposite);

-            }

-          }

-          else if (xsdTerm instanceof XSDWildcard)

-          {

-            // EATM shouldn't happen

-            XSDWildcard xsdWildcard = (XSDWildcard)xsdTerm;

-            extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.ELEMENT_WILDCARD_FEATURE);

-            extendedMetaData.setWildcards(eReference, getWildcards(xsdWildcard));

-            extendedMetaData.setProcessingKind(eReference, xsdWildcard.getProcessContents().getValue() + 1);

-            extendedMetaData.setName(eReference, ":" + eClass.getEAllStructuralFeatures().indexOf(eReference));

-          }

-          else

-          {

-            extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.GROUP_FEATURE);

-            extendedMetaData.setName(eReference, ":" + eClass.getEAllStructuralFeatures().indexOf(eReference));

-          }

-        }

-        else if (xsdComponent instanceof XSDElementDeclaration)

-        {

-          XSDElementDeclaration xsdElementDeclaration = (XSDElementDeclaration)xsdComponent;

-          eReference.setContainment(true);

-          eReference.setResolveProxies(false);

-          extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.ELEMENT_FEATURE);

-          extendedMetaData.setName(eReference, xsdElementDeclaration.getName());

-          extendedMetaData.setNamespace(eReference, xsdElementDeclaration.getTargetNamespace());

-

-          XSDElementDeclaration substitutionGroupAffiliation = xsdElementDeclaration.getSubstitutionGroupAffiliation();

-          if (substitutionGroupAffiliation != null)

-          {

-            EStructuralFeature affiliation = getEStructuralFeature(substitutionGroupAffiliation);

-            extendedMetaData.setAffiliation(eReference, affiliation);

-          }

-          XSDTypeDefinition xsdType = getEffectiveTypeDefinition(null, xsdElementDeclaration);

-          if (xsdType instanceof XSDSimpleTypeDefinition)

-          {

-            eReference.setResolveProxies(!isLocalReferenceType((XSDSimpleTypeDefinition)xsdType));

-          }

-

-          if (maxOccurs == 1 && xsdElementDeclaration.isNillable())

-          {

-            eReference.setUnsettable(true);

-          }

-

-          if (xsdElementDeclaration.isAbstract())

-          {

-            eReference.setChangeable(false);

-          }

-        }

-        else if (xsdComponent instanceof XSDAttributeUse)

-        {

-          String opposite = getEcoreAttribute(xsdComponent, "opposite");

-          if (opposite != null)

-          {

-            eReferenceToOppositeNameMap.put(eReference, opposite);

-          }

-          

-          XSDAttributeUse xsdAttributeUse = (XSDAttributeUse)xsdComponent;

-          XSDAttributeDeclaration xsdAttributeDeclaration = xsdAttributeUse.getAttributeDeclaration();

-          extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.ATTRIBUTE_FEATURE);

-          extendedMetaData.setName(eReference, xsdAttributeDeclaration.getName());

-          extendedMetaData.setNamespace(eReference, xsdAttributeDeclaration.getTargetNamespace());

-          eReference.setResolveProxies

-            (!isLocalReferenceType((XSDSimpleTypeDefinition)getEffectiveTypeDefinition(xsdAttributeUse, xsdAttributeDeclaration)));

-        }

-        else if (xsdComponent instanceof XSDAttributeDeclaration)

-        {

-          XSDAttributeDeclaration xsdAttributeDeclaration = (XSDAttributeDeclaration)xsdComponent;

-          extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.ATTRIBUTE_FEATURE);

-          extendedMetaData.setName(eReference, xsdAttributeDeclaration.getName());

-          extendedMetaData.setNamespace(eReference, xsdAttributeDeclaration.getTargetNamespace());

-          eReference.setResolveProxies

-            (!isLocalReferenceType((XSDSimpleTypeDefinition)getEffectiveTypeDefinition(null, xsdAttributeDeclaration)));

-        }

-      }

-

-      return eReference;

-    }

-    else

-    {

-      EAttribute eAttribute = ecoreFactory.createEAttribute();

-      setAnnotations(eAttribute, xsdComponent);

-      eAttribute.setName(Character.toLowerCase(name.charAt(0)) + name.substring(1));

-      eAttribute.setUnique(false);

-      eAttribute.setEType(type);

-      eAttribute.setLowerBound(minOccurs);

-      eAttribute.setUpperBound(maxOccurs);

-      eClass.getEStructuralFeatures().add(eAttribute);

-

-      if (xsdComponent == null || xsdComponent instanceof XSDSimpleTypeDefinition)

-      {

-        extendedMetaData.setName(eAttribute, ":" + eClass.getEAllStructuralFeatures().indexOf(eAttribute));

-        extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.SIMPLE_FEATURE);

-      }

-      else

-      {

-        map(xsdComponent, eAttribute);

-        if (xsdComponent instanceof XSDAttributeUse)

-        {

-          XSDAttributeUse xsdAttributeUse = (XSDAttributeUse)xsdComponent;

-          XSDAttributeDeclaration xsdAttributeDeclaration = xsdAttributeUse.getAttributeDeclaration();

-          extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ATTRIBUTE_FEATURE);

-          extendedMetaData.setName(eAttribute, xsdAttributeDeclaration.getName());

-          extendedMetaData.setNamespace(eAttribute, xsdAttributeDeclaration.getTargetNamespace());

-

-          String defaultValue = getEcoreAttribute(xsdComponent, "default");

-          if (defaultValue == null)

-          {

-            defaultValue = xsdAttributeUse.getLexicalValue();

-          }

-          eAttribute.setDefaultValueLiteral(defaultValue);

-          initialize(eAttribute, (XSDSimpleTypeDefinition)getEffectiveTypeDefinition(xsdAttributeUse, xsdAttributeDeclaration));

-        }

-        else if (xsdComponent instanceof XSDAttributeDeclaration)

-        {

-          XSDAttributeDeclaration xsdAttributeDeclaration = (XSDAttributeDeclaration)xsdComponent;

-          extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ATTRIBUTE_FEATURE);

-          extendedMetaData.setName(eAttribute, xsdAttributeDeclaration.getName());

-          extendedMetaData.setNamespace(eAttribute, xsdAttributeDeclaration.getTargetNamespace());

-

-          eAttribute.setDefaultValueLiteral(xsdAttributeDeclaration.getLexicalValue());

-          initialize(eAttribute, (XSDSimpleTypeDefinition)getEffectiveTypeDefinition(null, xsdAttributeDeclaration));

-        }

-        else if (xsdComponent instanceof XSDParticle)

-        {

-          XSDTerm xsdTerm = ((XSDParticle)xsdComponent).getTerm();

-          if (xsdTerm instanceof XSDElementDeclaration)

-          {

-            XSDElementDeclaration xsdElementDeclaration = (XSDElementDeclaration)xsdTerm;

-            extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ELEMENT_FEATURE);

-            extendedMetaData.setName(eAttribute, xsdElementDeclaration.getName());

-            extendedMetaData.setNamespace(eAttribute, xsdElementDeclaration.getTargetNamespace());

-

-            eAttribute.setDefaultValueLiteral(xsdElementDeclaration.getLexicalValue());

-            XSDTypeDefinition xsdType = getEffectiveTypeDefinition(xsdComponent, xsdElementDeclaration);

-            if (xsdType instanceof XSDSimpleTypeDefinition)

-            {

-              initialize(eAttribute, (XSDSimpleTypeDefinition)xsdType);

-            }

-

-            if (xsdElementDeclaration.isNillable())

-            {

-              if (!canSupportNull((EDataType)type))

-              {

-                eAttribute.setEType(type = (EDataType)typeToTypeObjectMap.get(type));

-              }

-              if (maxOccurs == 1)

-              {

-                eAttribute.setUnsettable(true);

-              }

-            }

-

-            if (xsdElementDeclaration.isAbstract())

-            {

-              eAttribute.setChangeable(false);

-            }

-          }

-          else if (xsdTerm instanceof XSDWildcard)

-          {

-            XSDWildcard xsdWildcard = (XSDWildcard)xsdTerm;

-            extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ELEMENT_WILDCARD_FEATURE);

-            extendedMetaData.setWildcards(eAttribute, getWildcards(xsdWildcard));

-            extendedMetaData.setProcessingKind(eAttribute, xsdWildcard.getProcessContents().getValue() + 1);

-            extendedMetaData.setName(eAttribute, ":" + eClass.getEAllStructuralFeatures().indexOf(eAttribute));

-          }

-          else

-          {

-            extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.GROUP_FEATURE);

-          }

-        }

-        else if (xsdComponent instanceof XSDWildcard)

-        {

-          XSDWildcard xsdWildcard = (XSDWildcard)xsdComponent;

-          extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ATTRIBUTE_WILDCARD_FEATURE);

-          extendedMetaData.setWildcards(eAttribute, getWildcards(xsdWildcard));

-          extendedMetaData.setProcessingKind(eAttribute, xsdWildcard.getProcessContents().getValue() + 1);

-          extendedMetaData.setName(eAttribute, ":" + eClass.getEAllStructuralFeatures().indexOf(eAttribute));

-        }

-        else if (xsdComponent instanceof XSDElementDeclaration)

-        {

-          XSDElementDeclaration xsdElementDeclaration = (XSDElementDeclaration)xsdComponent;

-          extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ELEMENT_FEATURE);

-          extendedMetaData.setName(eAttribute, xsdElementDeclaration.getName());

-          extendedMetaData.setNamespace(eAttribute, xsdElementDeclaration.getTargetNamespace());

-

-          eAttribute.setDefaultValueLiteral(xsdElementDeclaration.getLexicalValue());

-          XSDTypeDefinition xsdType = getEffectiveTypeDefinition(null, xsdElementDeclaration);

-          if (xsdType instanceof XSDSimpleTypeDefinition)

-          {

-            initialize(eAttribute, (XSDSimpleTypeDefinition)xsdType);

-          }

-

-          XSDElementDeclaration substitutionGroupAffiliation = xsdElementDeclaration.getSubstitutionGroupAffiliation();

-          if (substitutionGroupAffiliation != null)

-          {

-            EStructuralFeature affiliation = getEStructuralFeature(substitutionGroupAffiliation);

-            extendedMetaData.setAffiliation(eAttribute, affiliation);

-          }

-

-          if (xsdElementDeclaration.isNillable() && !canSupportNull((EDataType)type))

-          {

-              eAttribute.setEType(type = (EDataType)typeToTypeObjectMap.get(type));

-            if (maxOccurs == 1)

-            {

-              eAttribute.setUnsettable(true);

-            }

-          }

-

-          if (xsdElementDeclaration.isAbstract())

-          {

-            eAttribute.setChangeable(false);

-          }

-        }

-      }

-

-      if (maxOccurs == 1 && (type.getDefaultValue() != null || eAttribute.getDefaultValueLiteral() != null))

-      {

-        eAttribute.setUnsettable(true);

-      }

-

-      return eAttribute;

-    }

-  }

-

-  protected XSDTypeDefinition getEffectiveTypeDefinition(XSDComponent xsdComponent, XSDFeature xsdFeature) 

-  {

-    return xsdFeature == null ? 

-        ((XSDComplexTypeDefinition)xsdComponent.eContainer()).getSimpleType() : xsdFeature.getType();

-  }

-  

-  protected EStructuralFeature createFeature

-   (EClass eClass, XSDElementDeclaration xsdElementDeclaration, String name, XSDComponent xsdComponent, int minOccurs, int maxOccurs)

-  {

-    XSDTypeDefinition elementTypeDefinition = getEffectiveTypeDefinition(xsdComponent, xsdElementDeclaration);

-    EClassifier eClassifier = getEClassifier(elementTypeDefinition);

-  

-    XSDTypeDefinition referenceType = getEcoreTypeQNameAttribute(xsdComponent, "reference");

-    if (referenceType == null)

-    {

-      referenceType = getEcoreTypeQNameAttribute(xsdElementDeclaration, "reference");

-    }

-    if (referenceType != null)

-    {

-      EClassifier referenceClassifier = getEClassifier(referenceType);

-      boolean needsHolder = false;

-      if (elementTypeDefinition instanceof XSDSimpleTypeDefinition)

-      {

-        XSDSimpleTypeDefinition xsdSimpleTypeDefinition = (XSDSimpleTypeDefinition)elementTypeDefinition;

-        if (xsdSimpleTypeDefinition.getVariety() == XSDVariety.LIST_LITERAL)

-        {

-          needsHolder = true;

-          

-          EPackage holderPackage = getEPackage(xsdElementDeclaration);

-          String holderName = xsdElementDeclaration.getName() + ":holder";

-          EClass holderClass = (EClass)extendedMetaData.getType(holderPackage, holderName);

-          if (holderClass == null)

-          {

-            // Create a holder class like an anonymous complex type.

-            //

-            holderClass = ecoreFactory.createEClass();

-            setAnnotations(holderClass, xsdElementDeclaration);

-            holderClass.setName(validName(holderName, true));

-            extendedMetaData.setName(holderClass, holderName);

-            extendedMetaData.setContentKind(holderClass, ExtendedMetaData.SIMPLE_CONTENT);

-                   

-            addToSortedList(holderPackage.getEClassifiers(), holderClass);

-     

-            EReference holderReference =

-              (EReference)createFeature

-                (holderClass,

-                 "value",

-                 referenceClassifier,

-                 null,

-                 0,

-                 -1);

-     

-            holderReference.setResolveProxies(!isLocalReferenceType(xsdSimpleTypeDefinition));

-          }

-          referenceClassifier = holderClass;

-        }

-      }

-      EStructuralFeature result =

-        createFeature

-          (eClass,

-           name,

-           referenceClassifier,

-           xsdComponent,

-           minOccurs,

-           maxOccurs);

-      ((EReference)result).setContainment(needsHolder);

-      if (needsHolder)

-      {

-        ((EReference)result).setUnsettable(false);

-        ((EReference)result).setResolveProxies(false);

-      }

-      initialize(result, xsdElementDeclaration, xsdComponent);

-      return result;

-    }

-    else

-    {

-      EStructuralFeature result =

-        createFeature

-          (eClass,

-           name,

-           eClassifier,

-           xsdComponent,

-           minOccurs,

-           maxOccurs);

-      initialize(result, xsdElementDeclaration, xsdComponent);

-      return result;

-    }

-  }

-

-  protected EStructuralFeature createFeature

-    (EClass eClass, XSDAttributeDeclaration xsdAttributeDeclaration, String name, XSDComponent xsdComponent, boolean isRequired)

-  {

-    XSDSimpleTypeDefinition attributeTypeDefinition = (XSDSimpleTypeDefinition)getEffectiveTypeDefinition(xsdComponent, xsdAttributeDeclaration);

-    if (attributeTypeDefinition == null)

-    {

-      attributeTypeDefinition = xsdComponent.getSchema().getSchemaForSchema().resolveSimpleTypeDefinition("anySimpleType");

-    }

-  

-    XSDTypeDefinition referenceType = getEcoreTypeQNameAttribute(xsdComponent, "reference");

-    if (referenceType == null && xsdAttributeDeclaration != null)

-    {

-      referenceType = getEcoreTypeQNameAttribute(xsdAttributeDeclaration, "reference");

-    }

-    if (referenceType != null)

-    {

-      int lowerBound = isRequired ? 1 : 0;

-      int upperBound = 1;

-      if (attributeTypeDefinition.getVariety() == XSDVariety.LIST_LITERAL)

-      {

-        XSDLengthFacet xsdLengthFacet = attributeTypeDefinition.getEffectiveLengthFacet();

-        if (isRequired)

-        {

-          if (xsdLengthFacet != null)

-          {

-            lowerBound = xsdLengthFacet.getValue();

-          }

-          else

-          {

-            XSDMinLengthFacet xsdMinLengthFacet = attributeTypeDefinition.getEffectiveMinLengthFacet();

-            if (xsdMinLengthFacet != null)

-            {

-              lowerBound = xsdMinLengthFacet.getValue();

-            }

-          }

-        }

-        if (xsdLengthFacet != null)

-        {

-          upperBound = xsdLengthFacet.getValue();

-        }

-        else

-        {

-          XSDMaxLengthFacet xsdMaxLengthFacet = attributeTypeDefinition.getEffectiveMaxLengthFacet();

-          if (xsdMaxLengthFacet != null)

-          {

-            upperBound = xsdMaxLengthFacet.getValue();

-          }

-          else

-          {

-            upperBound = -1;

-          }

-        }

-      }

-  

-      EClassifier referenceClassifier = getEClassifier(referenceType);

-      EStructuralFeature result =

-        createFeature

-          (eClass,

-           name,

-           referenceClassifier,

-           xsdComponent,

-           lowerBound,

-           upperBound);

-      initialize(result, xsdAttributeDeclaration, xsdComponent);

-      return result;

-    }

-    else

-    {

-      boolean isMany = 

-          attributeTypeDefinition.getVariety() == XSDVariety.LIST_LITERAL &&

-          xsdComponent instanceof XSDAttributeUse && 

-          "true".equals(getEcoreAttribute(xsdComponent, "many"));

-      if (isMany)

-      {

-        EDataType eDataType = getEDataType(attributeTypeDefinition.getItemTypeDefinition());

-        XSDLengthFacet xsdLengthFacet = attributeTypeDefinition.getEffectiveLengthFacet();

-        int lowerBound = isRequired ? 1 : 0;

-        int upperBound = -1;

-        if (isRequired)

-        {

-          if (xsdLengthFacet != null)

-          {

-            lowerBound = xsdLengthFacet.getValue();

-          }

-          else

-          {

-            XSDMinLengthFacet xsdMinLengthFacet = attributeTypeDefinition.getEffectiveMinLengthFacet();

-            if (xsdMinLengthFacet != null)

-            {

-              lowerBound = xsdMinLengthFacet.getValue();

-            }

-          }

-        }

-        if (xsdLengthFacet != null)

-        {

-          upperBound = xsdLengthFacet.getValue();

-        }

-        else

-        {

-          XSDMaxLengthFacet xsdMaxLengthFacet = attributeTypeDefinition.getEffectiveMaxLengthFacet();

-          if (xsdMaxLengthFacet != null)

-          {

-            upperBound = xsdMaxLengthFacet.getValue();

-          }

-        }

-        EStructuralFeature result =

-          createFeature

-            (eClass,

-             name,

-             eDataType,

-             xsdComponent,

-             lowerBound,

-             upperBound);

-        initialize(result, xsdAttributeDeclaration, xsdComponent);

-        return result;

-      }

-      else

-      {

-        EDataType eDataType = getEDataType(attributeTypeDefinition);

-        EStructuralFeature result =

-          createFeature

-            (eClass,

-             name,

-             eDataType,

-             xsdComponent,

-             isRequired ? 1 : 0,

-             1);

-        initialize(result, xsdAttributeDeclaration, xsdComponent);

-        return result;

-      }

-    }

-  }

-  

-  public EStructuralFeature getEStructuralFeature(XSDFeature xsdFeature)

-  {

-    if ("true".equals(getEcoreAttribute(xsdFeature, "ignore"))) return null;

-    EStructuralFeature eStructuralFeature = (EStructuralFeature)xsdComponentToEModelElementMap.get(xsdFeature);

-    if (eStructuralFeature == null)

-    {

-      EPackage ePackage = getEPackage(xsdFeature);

-      EClass documentEClass = extendedMetaData.getDocumentRoot(ePackage);

-      if (documentEClass == null)

-      {

-          createDocumentRoot(xsdFeature.getSchema(), ePackage);

-      }

-

-      String name = getEcoreAttribute(xsdFeature, "name");

-      if (name == null)

-      {

-        name= validName(xsdFeature.getName(), true);       

-      }

-      

-      if (xsdFeature instanceof XSDElementDeclaration)

-      {

-        // Mark the bound as unspecified so that it won't be considered many 

-        // but can nevertheless be recognized as being unspecified and perhaps still be treat as many.

-        //

-        EStructuralFeature result = 

-          createFeature(documentEClass, (XSDElementDeclaration)xsdFeature, name, xsdFeature, 0, ETypedElement.UNSPECIFIED_MULTIPLICITY);            

-

-        result.setDerived(true);

-        result.setTransient(true);

-        result.setVolatile(true);

-        return result;

-      }

-      else

-      {

-        EStructuralFeature result = 

-          createFeature(documentEClass, (XSDAttributeDeclaration)xsdFeature, name, xsdFeature, false);

-        return result;

-      }

-    }

-

-    return eStructuralFeature;

-  }

-

-  public void generate(XSDSchema xsdSchema)

-  {

-    this.rootSchema = xsdSchema;

-    if (xsdSchemas.add(xsdSchema))

-    {

-      addInput(xsdSchema);

-      validate(xsdSchema);

-    }

-

-    Collection visitedElementDeclarations = new ArrayList();

-    Collection elementDeclarations = new ArrayList(xsdSchema.getElementDeclarations());

-

-    Collection visitedAttributeDeclarations = new ArrayList();

-    Collection attributeDeclarations = new ArrayList(xsdSchema.getAttributeDeclarations());

-

-    Collection visitedTypeDefinitions = new ArrayList();

-    Collection typeDefinitions = new ArrayList(xsdSchema.getTypeDefinitions());

-

-    while (!elementDeclarations.isEmpty() || !attributeDeclarations.isEmpty() || !typeDefinitions.isEmpty())

-    {

-      for (Iterator i = elementDeclarations.iterator(); i.hasNext(); )

-      {

-        XSDElementDeclaration xsdElementDeclaration = (XSDElementDeclaration)i.next();

-        getEStructuralFeature(xsdElementDeclaration);

-      }

-      visitedElementDeclarations.addAll(elementDeclarations);

-      elementDeclarations = new ArrayList(xsdSchema.getElementDeclarations());

-      elementDeclarations.removeAll(visitedElementDeclarations);

-

-      for (Iterator i = attributeDeclarations.iterator(); i.hasNext(); )

-      {

-        XSDAttributeDeclaration xsdAttributeDeclaration = (XSDAttributeDeclaration)i.next();

-        if (!XSDConstants.isSchemaInstanceNamespace(xsdAttributeDeclaration.getTargetNamespace()))

-        {

-          getEStructuralFeature(xsdAttributeDeclaration);

-        }

-      }

-      visitedAttributeDeclarations.addAll(attributeDeclarations);

-      attributeDeclarations = new ArrayList(xsdSchema.getAttributeDeclarations());

-      attributeDeclarations.removeAll(visitedAttributeDeclarations);

-

-      for (Iterator i = typeDefinitions.iterator(); i.hasNext(); )

-      {

-        XSDTypeDefinition xsdTypeDefinition = (XSDTypeDefinition)i.next();

-        getEClassifier(xsdTypeDefinition);

-      }

-      visitedTypeDefinitions.addAll(typeDefinitions);

-      typeDefinitions = new ArrayList(xsdSchema.getTypeDefinitions());

-      typeDefinitions.removeAll(visitedTypeDefinitions);

-    }

-

-    resolveNameConflicts();

-

-    for (Iterator i = xsdSchemas.iterator(); i.hasNext(); )

-    {

-      XSDSchema generatedXSDSchema = (XSDSchema)i.next();

-      EPackage ePackage = (EPackage)targetNamespaceToEPackageMap.get(generatedXSDSchema.getTargetNamespace());

-      if (ePackage != null)

-      {

-        String packageName= getEcoreAttribute(generatedXSDSchema, "package");

-        if (packageName != null)

-        {

-          ePackage.setName(packageName);

-        }

-        String packageNsPrefix= getEcoreAttribute(generatedXSDSchema, "nsPrefix");

-        if (packageNsPrefix != null)

-        {

-          ePackage.setNsPrefix(packageNsPrefix);

-        }

-      }

-    }

-

-    for (Iterator i = eReferenceToOppositeNameMap.entrySet().iterator(); i.hasNext(); )

-    {

-      Map.Entry entry = (Map.Entry)i.next();

-      EReference eReference = (EReference)entry.getKey();

-      String opposite = (String)entry.getValue();

-      EClass oppositeEClass = eReference.getEReferenceType();

-      if (eReference.getEOpposite() == null)

-      {

-        EStructuralFeature eOppositeFeature =  oppositeEClass.getEStructuralFeature(opposite);

-        

-        // Match by XML name if this fails.

-        if (eOppositeFeature == null)

-        {

-          for (Iterator j = oppositeEClass.getEAllStructuralFeatures().iterator(); j.hasNext(); )

-          {

-            EStructuralFeature feature = (EStructuralFeature)j.next();

-            if (opposite.equals(extendedMetaData.getName(feature)))

-            {

-              eOppositeFeature = feature;

-              break;

-            }

-          }

-        }

-        

-        if (eOppositeFeature instanceof EReference)

-        {

-          EReference eOpposite = (EReference)eOppositeFeature;

-          eOpposite.setEOpposite(eReference);

-          eReference.setEOpposite(eOpposite);

-        }

-      }

-

-      if (eReference.getEOpposite() == null && eReference.isContainment())

-      {

-        EReference eOpposite = ecoreFactory.createEReference();

-        eOpposite.setName(opposite);

-        eOpposite.setEType(eReference.getEContainingClass());

-        eOpposite.setLowerBound(0);

-        eOpposite.setEOpposite(eReference);

-        eReference.setEOpposite(eOpposite);

-        eOpposite.setTransient(true);

-        oppositeEClass.getEStructuralFeatures().add(eOpposite);

-      }

-    }

-

-    eReferenceToOppositeNameMap.clear();

-  }

-

-}

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.helper;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.emf.ecore.EAttribute;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EClassifier;
+import org.eclipse.emf.ecore.EDataType;
+import org.eclipse.emf.ecore.EEnum;
+import org.eclipse.emf.ecore.EOperation;
+import org.eclipse.emf.ecore.EPackage;
+import org.eclipse.emf.ecore.EParameter;
+import org.eclipse.emf.ecore.EReference;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.ETypedElement;
+import org.eclipse.emf.ecore.EcoreFactory;
+import org.eclipse.emf.ecore.EcorePackage;
+import org.eclipse.emf.ecore.util.EcoreUtil;
+import org.eclipse.emf.ecore.util.ExtendedMetaData;
+import org.eclipse.emf.ecore.xml.type.XMLTypePackage;
+import org.eclipse.xsd.XSDAnnotation;
+import org.eclipse.xsd.XSDAttributeDeclaration;
+import org.eclipse.xsd.XSDAttributeUse;
+import org.eclipse.xsd.XSDComplexTypeContent;
+import org.eclipse.xsd.XSDComplexTypeDefinition;
+import org.eclipse.xsd.XSDComponent;
+import org.eclipse.xsd.XSDContentTypeCategory;
+import org.eclipse.xsd.XSDDerivationMethod;
+import org.eclipse.xsd.XSDElementDeclaration;
+import org.eclipse.xsd.XSDFeature;
+import org.eclipse.xsd.XSDLengthFacet;
+import org.eclipse.xsd.XSDMaxLengthFacet;
+import org.eclipse.xsd.XSDMinLengthFacet;
+import org.eclipse.xsd.XSDModelGroup;
+import org.eclipse.xsd.XSDModelGroupDefinition;
+import org.eclipse.xsd.XSDNamedComponent;
+import org.eclipse.xsd.XSDParticle;
+import org.eclipse.xsd.XSDSchema;
+import org.eclipse.xsd.XSDSimpleTypeDefinition;
+import org.eclipse.xsd.XSDTerm;
+import org.eclipse.xsd.XSDTypeDefinition;
+import org.eclipse.xsd.XSDVariety;
+import org.eclipse.xsd.XSDWildcard;
+import org.eclipse.xsd.ecore.XSDEcoreBuilder;
+import org.eclipse.xsd.util.XSDConstants;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * An XSDEcoreBuilder that uses a supplied (SDO) ecore factory to create properties and types.
+ */
+public class BaseSDOXSDEcoreBuilder extends XSDEcoreBuilder
+{
+  protected EcorePackage ecorePackage = EcorePackage.eINSTANCE;
+  protected EcoreFactory ecoreFactory = EcoreFactory.eINSTANCE;
+
+  public BaseSDOXSDEcoreBuilder(ExtendedMetaData extendedMetaData)
+  {
+    super(extendedMetaData);
+  }
+  
+  private void createDocumentRoot(XSDSchema xsdSchema, EPackage ePackage) {
+      EClass documentEClass = ecoreFactory.createEClass();
+      String name = getEcoreAttribute(xsdSchema, "documentRoot");
+      if (name == null)
+      {
+        name = "DocumentRoot";
+      }
+      documentEClass.setName(name);
+
+      extendedMetaData.setDocumentRoot(documentEClass);
+
+      ePackage.getEClassifiers().add(documentEClass);
+
+      createFeature
+        (documentEClass,
+         "mixed",
+         ecorePackage.getEFeatureMapEntry(),
+         null,
+         0,
+         -1);
+
+      EStructuralFeature xmlnsPrefixMapFeature =
+        createFeature
+          (documentEClass,
+           "xMLNSPrefixMap",
+           ecorePackage.getEStringToStringMapEntry(),
+           null,
+           0,
+           -1);
+      extendedMetaData.setName(xmlnsPrefixMapFeature, "xmlns:prefix");
+
+      EStructuralFeature xsiSchemaLocationMapFeature =
+        createFeature
+          (documentEClass,
+           "xSISchemaLocation",
+           ecorePackage.getEStringToStringMapEntry(),
+           null,
+           0,
+           -1);
+      extendedMetaData.setName(xsiSchemaLocationMapFeature, "xsi:schemaLocation");
+  }
+
+  public EPackage getEPackage(XSDNamedComponent xsdNamedComponent)
+  {
+    XSDSchema containingXSDSchema = xsdNamedComponent.getSchema();
+    if (containingXSDSchema != null && !xsdSchemas.contains(containingXSDSchema))
+    {
+      xsdSchemas.add(containingXSDSchema);
+      addInput(containingXSDSchema);
+      validate(containingXSDSchema);
+    }
+
+    String targetNamespace = 
+      containingXSDSchema == null ? 
+        xsdNamedComponent.getTargetNamespace() : 
+        containingXSDSchema.getTargetNamespace();
+    EPackage ePackage = (EPackage)targetNamespaceToEPackageMap.get(targetNamespace);
+    if (ePackage == null)
+    {
+      ePackage = ecoreFactory.createEPackage();
+      setAnnotations(ePackage, containingXSDSchema);
+      addOutput(ePackage);
+      if (targetNamespace == null)
+      {
+        if (containingXSDSchema == null)
+        {
+          containingXSDSchema = rootSchema;
+        }
+        ePackage.setName(validName(containingXSDSchema.eResource().getURI().trimFileExtension().lastSegment(), true));
+        ePackage.setNsURI(containingXSDSchema.eResource().getURI().toString());
+
+        // Also register against the nsURI for the case that the target namespace is null.
+        //
+        // extendedMetaData.putPackage(ePackage.getNsURI(), ePackage);
+      }
+      else
+      {
+        String qualifiedPackageName = qualifiedPackageName(targetNamespace);
+        ePackage.setName(qualifiedPackageName);
+        ePackage.setNsURI(targetNamespace);
+      }
+
+      String nsPrefix = ePackage.getName();
+      int index = nsPrefix.lastIndexOf('.');
+      nsPrefix = index == -1 ? nsPrefix : nsPrefix.substring(index + 1);
+
+      // http://www.w3.org/TR/REC-xml-names/#xmlReserved
+      // Namespace Constraint: Leading "XML"
+      // Prefixes beginning with the three-letter sequence x, m, l, in any case combination, 
+      // are reserved for use by XML and XML-related specifications.
+      //
+      if (nsPrefix.toLowerCase().startsWith("xml"))
+      {
+        nsPrefix = "_" + nsPrefix;
+      }
+      ePackage.setNsPrefix(nsPrefix);
+
+      extendedMetaData.setQualified(ePackage, targetNamespace != null);
+      extendedMetaData.putPackage(targetNamespace, ePackage);
+
+      targetNamespaceToEPackageMap.put(targetNamespace, ePackage);
+      
+      createDocumentRoot(xsdNamedComponent.getSchema(), ePackage);
+    }
+
+    return ePackage;
+  }
+
+  protected EClassifier computeEClassifier(XSDTypeDefinition xsdTypeDefinition)
+  {
+    if (xsdTypeDefinition == null)
+    {
+      return getBuiltInEClassifier(rootSchema.getSchemaForSchemaNamespace(), "anySimpleType");
+    }
+    else if (xsdTypeDefinition instanceof XSDSimpleTypeDefinition)
+    {
+      return computeEDataType((XSDSimpleTypeDefinition)xsdTypeDefinition);
+    }
+    else
+    {
+      return computeEClass((XSDComplexTypeDefinition)xsdTypeDefinition);
+    }
+  }
+
+  protected EDataType computeEDataType(XSDSimpleTypeDefinition xsdSimpleTypeDefinition)
+  {
+    if (xsdSimpleTypeDefinition == null)
+    {
+      return (EDataType)getBuiltInEClassifier(rootSchema.getSchemaForSchemaNamespace(), "anySimpleType");
+    }
+    else if (XSDConstants.isSchemaForSchemaNamespace(xsdSimpleTypeDefinition.getTargetNamespace()))
+    {
+      String name = xsdSimpleTypeDefinition.getName();
+      if (name != null)
+      {
+        EDataType result = (EDataType)getBuiltInEClassifier(xsdSimpleTypeDefinition.getTargetNamespace(), "anyType".equals(name) ? "anySimpleType" : name);
+        if (result != null)
+        {
+          return result;
+        }
+      }
+    }
+    else if (xsdSimpleTypeDefinition.getContainer() == null)
+    {
+      return (EDataType)getBuiltInEClassifier(rootSchema.getSchemaForSchemaNamespace(), "anySimpleType");
+    }
+
+    String explicitInstanceClassName = getEcoreAttribute(xsdSimpleTypeDefinition, "instanceClass");
+    if (explicitInstanceClassName != null)
+    {
+      EDataType eDataType = ecoreFactory.createEDataType();
+      setAnnotations(eDataType, xsdSimpleTypeDefinition);
+
+      String aliasName = getEcoreAttribute(xsdSimpleTypeDefinition, "name");
+      if (aliasName == null)
+      {
+        aliasName = validAliasName(xsdSimpleTypeDefinition, true);
+      }
+      eDataType.setName(aliasName);
+      extendedMetaData.setName(eDataType, xsdSimpleTypeDefinition.getAliasName());
+
+      eDataType.setInstanceClassName(explicitInstanceClassName);
+
+      EPackage ePackage = getEPackage(xsdSimpleTypeDefinition);
+      addToSortedList(ePackage.getEClassifiers(), eDataType);
+
+      checkForPrimitive(xsdSimpleTypeDefinition, eDataType);
+
+      handleFacets(xsdSimpleTypeDefinition, eDataType);
+
+      String constraints = getEcoreAttribute(xsdSimpleTypeDefinition, "constraints");
+      if (constraints != null)
+      {
+        EcoreUtil.setAnnotation(eDataType, EcorePackage.eNS_URI, "constraints", constraints);
+      }
+
+      if ("false".equals(getEcoreAttribute(xsdSimpleTypeDefinition, "serializable")))
+      {
+        eDataType.setSerializable(false);
+      }
+      return eDataType;
+    }
+    else
+    {
+      EEnum eEnum = computeEEnum(xsdSimpleTypeDefinition);
+      if (eEnum != null)
+      {
+        return eEnum;
+      }
+      else
+      {
+        XSDSimpleTypeDefinition baseTypeDefinition = xsdSimpleTypeDefinition.getBaseTypeDefinition();
+        if (baseTypeDefinition != null)
+        {
+          EDataType eDataType = ecoreFactory.createEDataType();
+          setAnnotations(eDataType, xsdSimpleTypeDefinition);
+
+          String name = getEcoreAttribute(xsdSimpleTypeDefinition, "name");
+          if (name == null)
+          {
+            name = validAliasName(xsdSimpleTypeDefinition, true);
+          }
+
+          eDataType.setName(name);
+          extendedMetaData.setName(eDataType, xsdSimpleTypeDefinition.getAliasName());
+
+          EPackage ePackage = getEPackage(xsdSimpleTypeDefinition);
+          addToSortedList(ePackage.getEClassifiers(), eDataType);
+
+          if (baseTypeDefinition.getVariety() != xsdSimpleTypeDefinition.getVariety())
+          {
+            if (xsdSimpleTypeDefinition.getVariety() == XSDVariety.LIST_LITERAL)
+            {
+              EDataType itemEDataType = getEDataType(xsdSimpleTypeDefinition.getItemTypeDefinition());
+              extendedMetaData.setItemType(eDataType, itemEDataType);
+              eDataType.setInstanceClassName("java.util.List");
+            }
+            else
+            {
+              String instanceClassName = null;
+              List memberTypes = new ArrayList();
+              for (Iterator i = xsdSimpleTypeDefinition.getMemberTypeDefinitions().iterator(); i.hasNext(); )
+              {
+                XSDSimpleTypeDefinition memberTypeDefinition = (XSDSimpleTypeDefinition)i.next();
+                EDataType memberEDataType = getEDataType(memberTypeDefinition);
+                memberTypes.add(memberEDataType);
+                String memberInstanceClassName = memberEDataType.getInstanceClassName();
+                if (memberInstanceClassName == null && memberEDataType instanceof EEnum)
+                {
+                  memberInstanceClassName = "org.eclipse.emf.common.util.Enumerator";
+                }
+                if (instanceClassName == null)
+                {
+                  instanceClassName = memberInstanceClassName;
+                }
+                else if (instanceClassName != memberInstanceClassName)
+                {
+                  instanceClassName = "java.lang.Object";
+                }
+              }
+              extendedMetaData.setMemberTypes(eDataType, memberTypes);
+              eDataType.setInstanceClassName(instanceClassName);
+            }
+          }
+          else
+          {
+            EDataType baseEDataType = getEDataType(baseTypeDefinition);
+            extendedMetaData.setBaseType(eDataType, baseEDataType);
+            String instanceClassName = getInstanceClassName(xsdSimpleTypeDefinition, baseEDataType);
+            eDataType.setInstanceClassName
+              (instanceClassName == null ? 
+                 "org.eclipse.emf.common.util.Enumerator" : 
+                 instanceClassName);
+          }
+
+          checkForPrimitive(xsdSimpleTypeDefinition, eDataType);
+          handleFacets(xsdSimpleTypeDefinition, eDataType);
+
+          String constraints = getEcoreAttribute(xsdSimpleTypeDefinition, "constraints");
+          if (constraints != null)
+          {
+            EcoreUtil.setAnnotation(eDataType, EcorePackage.eNS_URI, "constraints", constraints);
+          }
+
+          if ("false".equals(getEcoreAttribute(xsdSimpleTypeDefinition, "serializable")))
+          {
+            eDataType.setSerializable(false);
+          }
+
+          return eDataType;
+        }
+      }
+      return (EDataType)getBuiltInEClassifier(rootSchema.getSchemaForSchemaNamespace(), "anySimpleType");
+    }
+  }
+
+  protected void checkForPrimitive(EDataType eDataType)
+  {
+    int index = PRIMITIVES.indexOf(eDataType.getInstanceClassName());
+    if (index != -1 || eDataType instanceof EEnum)
+    {
+      EDataType eDataTypeObject = ecoreFactory.createEDataType();
+      eDataTypeObject.setName(eDataType.getName() + "Object");
+      if (index != -1)
+      {
+        eDataTypeObject.setInstanceClassName(PRIMITIVE_WRAPPERS[index]);
+      }
+      else
+      {
+        eDataTypeObject.setInstanceClassName("org.eclipse.emf.common.util.Enumerator");
+      }
+      extendedMetaData.setName(eDataTypeObject, extendedMetaData.getName(eDataType) + ":Object");
+      addToSortedList(eDataType.getEPackage().getEClassifiers(), eDataTypeObject);
+      extendedMetaData.setBaseType(eDataTypeObject, eDataType);
+
+      typeToTypeObjectMap.put(eDataType, eDataTypeObject);
+    }
+  }
+
+  public EClass computeEClass(XSDComplexTypeDefinition xsdComplexTypeDefinition)
+  {
+    if (xsdComplexTypeDefinition == null)
+    {
+      return (EClass)getBuiltInEClassifier(rootSchema.getSchemaForSchemaNamespace(), "anyType");
+    }
+    else if (XSDConstants.isSchemaForSchemaNamespace(xsdComplexTypeDefinition.getTargetNamespace()))
+    {
+      String name = xsdComplexTypeDefinition.getName();
+      if (name != null)
+      {
+        EClass result = (EClass)getBuiltInEClassifier(xsdComplexTypeDefinition.getTargetNamespace(), name);
+        if (result != null)
+        {
+          return result;
+        }
+      }
+    }
+    else if (xsdComplexTypeDefinition.getContainer() == null)
+    {
+      return (EClass)getBuiltInEClassifier(rootSchema.getSchemaForSchemaNamespace(), "anyType");
+    }
+
+    EClass eClass = ecoreFactory.createEClass();
+    setAnnotations(eClass, xsdComplexTypeDefinition);
+    // Do this early to prevent recursive loop.
+    xsdComponentToEModelElementMap.put(xsdComplexTypeDefinition, eClass);
+
+    if ("true".equals(getEcoreAttribute(xsdComplexTypeDefinition, "interface")))
+    {
+      eClass.setInterface(true);
+    }
+
+    String instanceClassName = getEcoreAttribute(xsdComplexTypeDefinition, "instanceClass");
+    if (instanceClassName != null)
+    {
+      eClass.setInstanceClassName(instanceClassName);
+    }
+
+    String aliasName = getEcoreAttribute(xsdComplexTypeDefinition, "name");
+    if (aliasName == null)
+    {
+      aliasName = validAliasName(xsdComplexTypeDefinition, true);
+    }
+    eClass.setName(aliasName);
+    extendedMetaData.setName(eClass, xsdComplexTypeDefinition.getAliasName());
+
+    String constraints = getEcoreAttribute(xsdComplexTypeDefinition, "constraints");
+    if (constraints != null)
+    {
+      EcoreUtil.setAnnotation(eClass, EcorePackage.eNS_URI, "constraints", constraints);
+    }
+
+    EPackage ePackage = getEPackage(xsdComplexTypeDefinition);
+    addToSortedList(ePackage.getEClassifiers(), eClass);
+
+    if (xsdComplexTypeDefinition.isAbstract())
+    {
+      eClass.setAbstract(true);
+    }
+
+    EClass baseClass = null;
+    XSDTypeDefinition baseTypeDefinition = xsdComplexTypeDefinition.getBaseTypeDefinition();
+    if (!baseTypeDefinition.isCircular())
+    {
+      EClassifier baseType = getEClassifier(baseTypeDefinition);
+      if (baseType instanceof EClass && baseType != ecorePackage.getEObject())
+      {
+        eClass.getESuperTypes().add(baseClass = (EClass)baseType);
+      }
+    }
+
+    boolean isRestriction = 
+      !eClass.getESuperTypes().isEmpty() && 
+        xsdComplexTypeDefinition.getDerivationMethod() == XSDDerivationMethod.RESTRICTION_LITERAL;
+
+    for (Iterator i = getEcoreTypeQNamesAttribute(xsdComplexTypeDefinition, "implements").iterator(); i.hasNext(); )
+    {
+      XSDTypeDefinition mixin = (XSDTypeDefinition)i.next();
+      if (!XSDConstants.isURType(mixin))
+      {
+        EClassifier mixinType = getEClassifier(mixin);
+        if (mixinType instanceof EClass && mixinType != ecorePackage.getEObject())
+        {
+          eClass.getESuperTypes().add(mixinType);
+        }
+      }
+    }
+
+    // 51210
+    // EAnnotation contentParticle = null;
+
+    if (xsdComplexTypeDefinition.getContentTypeCategory() == XSDContentTypeCategory.SIMPLE_LITERAL)
+    {
+      extendedMetaData.setContentKind(eClass, ExtendedMetaData.SIMPLE_CONTENT);
+      if (!"SimpleAnyType".equals(eClass.getName()) || !XMLTypePackage.eNS_URI.equals(eClass.getEPackage().getNsURI()))
+      {
+        if (eClass.getEAllStructuralFeatures().isEmpty())
+        {
+          XSDComplexTypeContent xsdComplexTypeContent = xsdComplexTypeDefinition.getContent();
+          String name = getEcoreAttribute(xsdComplexTypeContent, "name");
+          if (name == null)
+          {
+            name = "value";
+          }
+          createFeature
+            (eClass,
+             null,
+             name,
+             xsdComplexTypeContent,
+             false);
+        }
+        else
+        {
+          XSDSimpleTypeDefinition xsdSimpleTypeDefinition = xsdComplexTypeDefinition.getSimpleType();
+          getEClassifier(xsdSimpleTypeDefinition);
+        }
+      }
+    }
+    else 
+    {
+      EStructuralFeature globalGroup = null;
+      boolean isMixed = xsdComplexTypeDefinition.getContentTypeCategory() == XSDContentTypeCategory.MIXED_LITERAL;
+      String featureMapName = getEcoreAttribute(xsdComplexTypeDefinition, "featureMap");
+      if (eClass.getESuperTypes().isEmpty() ?
+            "true".equals(getEcoreAttribute(xsdComplexTypeDefinition, "mixed")) :
+            extendedMetaData.getMixedFeature((EClass)eClass.getESuperTypes().get(0)) != null)
+      {
+        isMixed = true;
+      }
+      extendedMetaData.setContentKind
+        (eClass, 
+         isMixed ? 
+           ExtendedMetaData.MIXED_CONTENT : 
+           xsdComplexTypeDefinition.getContentTypeCategory() == XSDContentTypeCategory.EMPTY_LITERAL ?
+             ExtendedMetaData.EMPTY_CONTENT :
+             ExtendedMetaData.ELEMENT_ONLY_CONTENT);
+      if (isMixed)
+      {
+        EStructuralFeature mixedFeature = extendedMetaData.getMixedFeature(eClass);
+        if (mixedFeature == null)
+        {
+          if (featureMapName == null)
+          {
+            featureMapName = "mixed";
+          }
+          mixedFeature =
+            createFeature
+              (eClass,
+               featureMapName,
+               ecorePackage.getEFeatureMapEntry(),
+               null,
+               0,
+               -1);
+          extendedMetaData.setName(mixedFeature, ":mixed");
+        }
+      }
+      else 
+      {
+        globalGroup = extendedMetaData.getElement(eClass, null, ":group");
+        if (globalGroup == null && featureMapName != null && eClass.getESuperTypes().isEmpty())
+        {
+          globalGroup =
+            createFeature
+              (eClass,
+               featureMapName,
+               ecorePackage.getEFeatureMapEntry(),
+               null,
+               0,
+               -1);
+          extendedMetaData.setName(globalGroup, ":group");
+          extendedMetaData.setFeatureKind(globalGroup, ExtendedMetaData.GROUP_FEATURE);
+        }
+      }
+
+      if (xsdComplexTypeDefinition.getContent() != null)
+      {
+        // 51210
+        // Map particleMap = new HashMap();
+        Map groups = new HashMap();
+        List particleInformation = collectParticles((XSDParticle)xsdComplexTypeDefinition.getContent());
+        for (Iterator i = particleInformation.iterator(); i.hasNext(); )
+        {
+          EffectiveOccurrence effectiveOccurrence = (EffectiveOccurrence)i.next();
+          XSDParticle xsdParticle = effectiveOccurrence.xsdParticle;
+          EStructuralFeature group = (EStructuralFeature)groups.get(effectiveOccurrence.xsdModelGroup);
+          XSDTerm xsdTerm = xsdParticle.getTerm();
+          EStructuralFeature eStructuralFeature = null;
+          String name = getEcoreAttribute(xsdParticle, "name");
+          if (xsdTerm instanceof XSDModelGroup)
+          {
+            if (!isRestriction) 
+            {
+              XSDModelGroup xsdModelGroup = (XSDModelGroup)xsdTerm;
+              if (name == null)
+              {
+                name = getEcoreAttribute(xsdParticle, "featureMap");
+                if (name == null)
+                {
+                  name = getEcoreAttribute(xsdModelGroup, "name");
+                  if (name == null)
+                  {
+                    name = getEcoreAttribute(xsdModelGroup, "featureMap");
+                    if (name == null)
+                    {
+                      if (xsdModelGroup.getContainer() instanceof XSDModelGroupDefinition)
+                      {
+                        XSDModelGroupDefinition xsdModelGroupDefinition = (XSDModelGroupDefinition)xsdModelGroup.getContainer();
+                        name =  getEcoreAttribute(xsdModelGroupDefinition, "name");
+                        if (name == null)
+                        {
+                          name = validName(xsdModelGroupDefinition.getName(), true);
+                        }
+                      }
+                      else
+                      {
+                        name = "group";
+                      }
+                    }
+                  }
+                }
+              }
+
+              eStructuralFeature =
+                createFeature
+                  (eClass,
+                   name,
+                   ecorePackage.getEFeatureMapEntry(),
+                   xsdParticle,
+                   0,
+                   -1);
+              groups.put(xsdTerm, eStructuralFeature);
+              extendedMetaData.setName(eStructuralFeature, name + ":" + eClass.getEAllStructuralFeatures().indexOf(eStructuralFeature));
+            }
+          }
+          else if (xsdTerm instanceof XSDWildcard)
+          {
+            if (!isRestriction) 
+            {
+              if (name == null)
+              {
+                name = getEcoreAttribute(xsdTerm, "name");
+                if (name == null)
+                {
+                  name = "any";
+                }
+              }
+              eStructuralFeature =
+                createFeature
+                  (eClass,
+                   name,
+                   ecorePackage.getEFeatureMapEntry(),
+                   xsdParticle,
+                   effectiveOccurrence.minOccurs,
+                   effectiveOccurrence.maxOccurs);
+              // 51210
+              // particleMap.put(xsdParticle, eStructuralFeature);
+            }
+          }
+          else
+          {
+            XSDElementDeclaration xsdElementDeclaration = (XSDElementDeclaration)xsdTerm;
+
+            boolean isRedundant = false;
+            if (isRestriction)
+            {
+              isRedundant = 
+                extendedMetaData.getElement
+                  (baseClass, xsdElementDeclaration.getTargetNamespace(), xsdElementDeclaration.getName()) != null;
+              
+              if (!isRedundant)
+              {
+                group = 
+                  extendedMetaData.getElementWildcardAffiliation
+                    (baseClass, xsdElementDeclaration.getTargetNamespace(), xsdElementDeclaration.getName());
+              }  
+            }
+
+            if (!isRedundant) 
+            {
+              if (name == null)
+              {
+                name = getEcoreAttribute(xsdElementDeclaration, "name");
+                if (name == null)
+                {
+                  name = validName(xsdElementDeclaration.getName(), true);
+                }
+              }
+
+              String groupName = getEcoreAttribute(xsdParticle, "featureMap");
+              if (groupName == null)
+              {
+                groupName = getEcoreAttribute(xsdElementDeclaration, "featureMap");
+              }
+
+              if (!"".equals(groupName) &&
+                   (groupName != null  ||
+                      xsdElementDeclaration.isAbstract() || 
+                      xsdElementDeclaration.getSubstitutionGroup().size() > 1))
+              {
+                if (groupName == null)
+                {
+                  groupName = name + "Group";
+                }
+                eStructuralFeature = 
+                  createFeature
+                    (eClass,
+                     groupName,
+                     ecorePackage.getEFeatureMapEntry(),
+                     xsdParticle,
+                     effectiveOccurrence.minOccurs,
+                     effectiveOccurrence.maxOccurs);
+
+                eStructuralFeature.setChangeable(true);
+
+                extendedMetaData.setFeatureKind(eStructuralFeature, ExtendedMetaData.GROUP_FEATURE);
+                extendedMetaData.setName(eStructuralFeature, xsdElementDeclaration.getName() + ":group");
+
+                if (group != null)
+                {
+                  extendedMetaData.setGroup(eStructuralFeature, group);
+                  eStructuralFeature.setDerived(true);
+                  eStructuralFeature.setTransient(true);
+                  eStructuralFeature.setVolatile(true);
+                }
+                else if (isMixed)
+                {
+                  eStructuralFeature.setDerived(true);
+                  eStructuralFeature.setTransient(true);
+                  eStructuralFeature.setVolatile(true);
+                }
+                else if (globalGroup != null)
+                {
+                  extendedMetaData.setGroup(eStructuralFeature, globalGroup);
+                  eStructuralFeature.setDerived(true);
+                  eStructuralFeature.setTransient(true);
+                  eStructuralFeature.setVolatile(true);
+                }
+
+                group = eStructuralFeature;
+              }
+
+              eStructuralFeature = 
+                 createFeature(eClass, xsdElementDeclaration, name, xsdParticle, effectiveOccurrence.minOccurs, effectiveOccurrence.maxOccurs);
+              // 51210
+              // particleMap.put(xsdParticle, eStructuralFeature);
+
+              // If the group is turned off, we better make the feature changeable.
+              //
+              if (!eStructuralFeature.isChangeable() && group == null && getEcoreAttribute(xsdParticle, xsdElementDeclaration, "changeable") == null)
+              {
+                eStructuralFeature.setChangeable(true);
+              }
+            }
+          }
+
+          if (eStructuralFeature != null) 
+          {
+            if (group != null)
+            {
+              extendedMetaData.setGroup(eStructuralFeature, group);
+              eStructuralFeature.setDerived(true);
+              eStructuralFeature.setTransient(true);
+              eStructuralFeature.setVolatile(true);
+            }
+            else if (isMixed)
+            {
+              eStructuralFeature.setDerived(true);
+              eStructuralFeature.setTransient(true);
+              eStructuralFeature.setVolatile(true);
+            }
+            else if (globalGroup != null)
+            {
+              extendedMetaData.setGroup(eStructuralFeature, globalGroup);
+              eStructuralFeature.setDerived(true);
+              eStructuralFeature.setTransient(true);
+              eStructuralFeature.setVolatile(true);
+            }
+          }
+        }
+
+        // 51210
+        // contentParticle = computeParticleConstraints(eClass, particleMap, (XSDParticle)xsdComplexTypeDefinition.getContent());
+      }
+    }
+
+    // 51210
+    // EAnnotation attributeParticle = null;
+    // if (isRestriction)
+    // {
+    //   attributeParticle = ecoreFactory.createEAnnotation();
+    //   attributeParticle.setSource("attributes");
+    // }
+
+    XSDWildcard baseXSDWildcard = null;
+    Collection baseAttributeUses = Collections.EMPTY_LIST;
+    Map baseAttributeURIs = new HashMap();
+    if (baseTypeDefinition instanceof XSDComplexTypeDefinition)
+    {
+      XSDComplexTypeDefinition complexBaseTypeDefinition = (XSDComplexTypeDefinition)baseTypeDefinition;
+      baseXSDWildcard = complexBaseTypeDefinition.getAttributeWildcard();
+      baseAttributeUses = complexBaseTypeDefinition.getAttributeUses();
+      for (Iterator i = baseAttributeUses.iterator(); i.hasNext(); )
+      {
+        XSDAttributeUse xsdAttributeUse = (XSDAttributeUse)i.next();
+        baseAttributeURIs.put(xsdAttributeUse.getAttributeDeclaration().getURI(), xsdAttributeUse);
+      }
+    }
+
+    for (Iterator i = getAttributeUses(xsdComplexTypeDefinition).iterator(); i.hasNext(); )
+    {
+      XSDAttributeUse xsdAttributeUse = (XSDAttributeUse)i.next();
+      XSDAttributeDeclaration xsdAttributeDeclaration = xsdAttributeUse.getAttributeDeclaration();
+      if (baseAttributeURIs.remove(xsdAttributeDeclaration.getURI()) == null)
+      {
+        String name = getEcoreAttribute(xsdAttributeUse, "name");
+        if (name == null)
+        {
+          name = getEcoreAttribute(xsdAttributeDeclaration, "name");
+        }
+        if (name == null)
+        {
+          name = validName(xsdAttributeDeclaration.getName(), true);
+        }
+
+        EStructuralFeature eStructuralFeature = 
+          createFeature(eClass, xsdAttributeDeclaration, name, xsdAttributeUse, xsdAttributeUse.isRequired());
+      
+        if (isRestriction)
+        {
+          EStructuralFeature attributeWildcardEStructuralFeature = 
+            extendedMetaData.getAttributeWildcardAffiliation
+              (baseClass, xsdAttributeDeclaration.getTargetNamespace(), xsdAttributeDeclaration.getName());
+          if (attributeWildcardEStructuralFeature != null)
+          {
+            extendedMetaData.setGroup(eStructuralFeature, attributeWildcardEStructuralFeature);
+            eStructuralFeature.setDerived(true);
+            eStructuralFeature.setTransient(true);
+            eStructuralFeature.setVolatile(true);
+          }
+        } 
+      }
+      /* 51210
+      else if (isRestriction && !baseAttributeUses.contains(xsdAttributeUse))
+      {
+        EStructuralFeature eStructuralFeature = 
+          extendedMetaData.getAttribute(eClass, xsdAttributeDeclaration.getTargetNamespace(), xsdAttributeDeclaration.getName());
+        if (eStructuralFeature != null)
+        {
+          EAnnotation attributeEAnnotation = ecoreFactory.createEAnnotation();
+          if (xsdAttributeUse.isRequired())
+          {
+            attributeEAnnotation.getDetails().put("minOccurs", "1");
+          }
+          attributeEAnnotation.getReferences().add(eStructuralFeature);
+
+          if (xsdAttributeDeclaration.getTypeDefinition() != null)
+          {
+            EClassifier type = getEClassifier(xsdAttributeDeclaration.getTypeDefinition());
+            if (type != eStructuralFeature.getEType() && type != null)
+            {
+              attributeEAnnotation.getReferences().add(type);
+            }
+          }
+
+          attributeParticle.getContents().add(attributeEAnnotation);
+        }
+      }
+      */
+    }
+
+    /* 51210
+    if (isRestriction && !baseAttributeURIs.isEmpty())
+    {
+      for (Iterator i = baseAttributeURIs.values().iterator(); i.hasNext(); )
+      {
+        XSDAttributeUse xsdAttributeUse = (XSDAttributeUse)i.next();
+        XSDAttributeDeclaration xsdAttributeDeclaration = xsdAttributeUse.getAttributeDeclaration();
+        EStructuralFeature eStructuralFeature = 
+          extendedMetaData.getAttribute(eClass, xsdAttributeDeclaration.getTargetNamespace(), xsdAttributeDeclaration.getName());
+        if (eStructuralFeature != null)
+        {
+          EAnnotation attributeEAnnotation = ecoreFactory.createEAnnotation();
+          attributeEAnnotation.getReferences().add(eStructuralFeature);
+          attributeEAnnotation.getDetails().put("maxOccurs", "0");
+          attributeParticle.getContents().add(attributeEAnnotation);
+        }
+      }
+    }
+    */
+
+    XSDWildcard xsdWildcard = xsdComplexTypeDefinition.getAttributeWildcard();
+    if (xsdWildcard != null && baseXSDWildcard != xsdWildcard || XSDConstants.isURType(xsdComplexTypeDefinition))
+    {
+      if (isRestriction && !XSDConstants.isURType(xsdComplexTypeDefinition))
+      {
+        // 51210
+        // attributeParticle.getDetails().put
+        //   ("wildcard", BasicExtendedMetaData.getEncodedWildcards(xsdComplexTypeDefinition.getTargetNamespace(), getWildcards(xsdWildcard)));
+      }
+      else
+      {
+        String name = getEcoreAttribute(xsdWildcard, "name");
+        if (name == null)
+        {
+          name = "anyAttribute";
+        }
+        createFeature
+          (eClass,
+           name,
+           ecorePackage.getEFeatureMapEntry(),
+           xsdWildcard,
+           0,
+           -1);
+      }
+    }
+
+    if (isRestriction)
+    {
+      // 51210
+      // EAnnotation restrictionParticle = ecoreFactory.createEAnnotation();
+      // restrictionParticle.setSource("restriction");
+      // if (contentParticle != null)
+      // {
+      //  restrictionParticle.getContents().add(contentParticle);
+      // }
+      // if (!attributeParticle.getContents().isEmpty() || !attributeParticle.getDetails().isEmpty())
+      // {
+      //   restrictionParticle.getContents().add(attributeParticle);
+      // }
+      // contentParticle = restrictionParticle;
+
+      int baseContentKind = extendedMetaData.getContentKind((EClass)eClass.getESuperTypes().get(0));
+      if (baseContentKind == ExtendedMetaData.MIXED_CONTENT && 
+            xsdComplexTypeDefinition.getContentTypeCategory() == XSDContentTypeCategory.SIMPLE_LITERAL)
+      {
+        extendedMetaData.setContentKind(eClass, ExtendedMetaData.SIMPLE_CONTENT);
+        EStructuralFeature eStructuralFeature =
+          createFeature
+            (eClass,
+             "rawValue",
+             getBuiltInEClassifier(xsdComplexTypeDefinition.getSchema().getSchemaForSchemaNamespace(), "string"),
+             null,
+             0,
+             1);
+        eStructuralFeature.setDerived(true);
+        eStructuralFeature.setTransient(true);
+        eStructuralFeature.setVolatile(true);
+
+        eStructuralFeature =
+          createFeature
+            (eClass,
+             "value",
+             getBuiltInEClassifier(xsdComplexTypeDefinition.getSchema().getSchemaForSchemaNamespace(), "anySimpleType"),
+             null,
+             0,
+             1);
+        eStructuralFeature.setDerived(true);
+        eStructuralFeature.setTransient(true);
+        eStructuralFeature.setVolatile(true);
+
+        if ("SimpleAnyType".equals(eClass.getName()) && XMLTypePackage.eNS_URI.equals(eClass.getEPackage().getNsURI()))
+        {
+          eStructuralFeature =
+            createFeature
+              (eClass,
+               "instanceType",
+               ecorePackage.getEDataType(),
+               null,
+               1,
+               1);
+
+          ((EReference)eStructuralFeature).setResolveProxies(false);
+        }
+      }
+      else
+      {
+        extendedMetaData.setContentKind(eClass, baseContentKind);
+      }
+    }
+
+    // 51210
+    // extendedMetaData.setContent(eClass, contentParticle);
+
+    XSDAnnotation xsdAnnotation = xsdComplexTypeDefinition.getAnnotation();
+    if (xsdAnnotation != null)
+    {
+      List applicationInformationList = xsdAnnotation.getApplicationInformation(EcorePackage.eNS_URI);
+      for (Iterator i = applicationInformationList.iterator(); i.hasNext(); )
+      {
+        Element applicationInformation = (Element)i.next();
+        if ("operations".equals(applicationInformation.getAttributeNS(EcorePackage.eNS_URI, "key")))
+        {
+          for (Iterator j =  getElements(applicationInformation, "operation").iterator(); j.hasNext(); )
+          {
+            EOperation eOperation = ecoreFactory.createEOperation();
+            Element operation = (Element)j.next();
+            String operationName = operation.getAttributeNS(null, "name");
+            eOperation.setName(operationName);
+            XSDTypeDefinition returnType = getEcoreTypeQNameAttribute(xsdComplexTypeDefinition, operation, null, "type");
+            if (returnType != null)
+            {
+              EClassifier returnEType = getEClassifier(returnType);
+              eOperation.setEType(returnEType);
+            }
+            
+            List exceptions = getEcoreTypeQNamesAttribute(xsdComplexTypeDefinition, operation, null, "exceptions");
+            for (Iterator k = exceptions.iterator(); k.hasNext(); )
+            {
+              XSDTypeDefinition exceptionTypeDefinition = (XSDTypeDefinition)k.next();
+              eOperation.getEExceptions().add(getEClassifier(exceptionTypeDefinition));
+            }
+          
+            for (Iterator k = getElements(operation, "parameter").iterator(); k.hasNext(); )
+            {
+              EParameter eParameter = ecoreFactory.createEParameter();
+              Element parameter = (Element)k.next();
+              String paramaterName = parameter.getAttributeNS(null, "name");
+              XSDTypeDefinition parameterType = getEcoreTypeQNameAttribute(xsdComplexTypeDefinition, parameter, null, "type");
+              EClassifier parameterEType = getEClassifier(parameterType);
+              eParameter.setName(paramaterName);
+              eParameter.setEType(parameterEType);
+
+              populateETypedElement(eParameter, parameter);
+              eOperation.getEParameters().add(eParameter);
+            }
+            
+            List body = getElements(operation, "body");
+            if (!body.isEmpty())
+            {
+              EcoreUtil.setAnnotation(eOperation, "http://www.eclipse.org/emf/2002/GenModel", "body", getText((Element)body.get(0)));
+            }
+
+            populateETypedElement(eOperation, operation);
+            eClass.getEOperations().add(eOperation);
+          }
+        }
+      }
+    }
+    return eClass;
+  }
+    
+  private String getText(Element element)
+  {
+    StringBuffer text = new StringBuffer();
+    for (Node node = element.getFirstChild(); node != null; node = node.getNextSibling())
+    {
+      switch (node.getNodeType())
+      {
+        case Node.TEXT_NODE:
+        case Node.CDATA_SECTION_NODE:
+        {
+          text.append(node.getNodeValue());
+        }
+      }
+    }
+    return text.toString();
+  }
+
+  private List getElements(Element element, String localName)
+  {
+    List result = new ArrayList();
+    for (Node node = element.getFirstChild(); node != null; node = node.getNextSibling())
+    {
+      if (node.getNodeType() == Node.ELEMENT_NODE)
+      {
+        Element child = (Element)node;
+        if (localName.equals(child.getLocalName()) && child.getNamespaceURI() == null)
+        {
+          result.add(child);
+        }
+      }
+    }
+    return result;
+  }
+  
+  protected EStructuralFeature createFeature
+    (EClass eClass, String name, EClassifier type, XSDComponent xsdComponent, int minOccurs, int maxOccurs)
+  {
+    if (xsdComponent != null)
+    {
+      XSDSchema containingXSDSchema = xsdComponent.getSchema();
+      if (containingXSDSchema != null && !xsdSchemas.contains(containingXSDSchema))
+      {
+        xsdSchemas.add(containingXSDSchema);
+        addInput(containingXSDSchema);
+        validate(containingXSDSchema);
+      }
+    }
+    else if (extendedMetaData.getContentKind(eClass) == ExtendedMetaData.MIXED_CONTENT)
+    {
+      if (type == ecorePackage.getEFeatureMapEntry())
+      {
+        EAttribute eAttribute = ecoreFactory.createEAttribute();
+        setAnnotations(eAttribute, xsdComponent);
+        eAttribute.setName(Character.toLowerCase(name.charAt(0)) + name.substring(1));
+        eAttribute.setUnique(false);
+        eAttribute.setEType(type);
+        eAttribute.setLowerBound(minOccurs);
+        eAttribute.setUpperBound(maxOccurs);
+        eClass.getEStructuralFeatures().add(eAttribute);
+        extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ELEMENT_WILDCARD_FEATURE);
+        extendedMetaData.setName(eAttribute, ":" + eAttribute.getName());
+        return eAttribute;
+      }
+      else
+      {
+        EReference eReference = ecoreFactory.createEReference();
+        setAnnotations(eReference, xsdComponent);
+        eReference.setName(name);
+        eReference.setEType(ecorePackage.getEStringToStringMapEntry());
+        eReference.setLowerBound(0);
+        eReference.setUpperBound(-1);
+        eReference.setContainment(true);
+        eReference.setResolveProxies(false);
+        eReference.setTransient(true);
+        eClass.getEStructuralFeatures().add(eReference);
+        extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.ATTRIBUTE_FEATURE);
+        return eReference;
+      }
+    }
+
+    if (type instanceof EClass)
+    {
+      EReference eReference = ecoreFactory.createEReference();
+      setAnnotations(eReference, xsdComponent);
+      eReference.setName(Character.toLowerCase(name.charAt(0)) + name.substring(1));
+      eReference.setEType(type);
+      eReference.setLowerBound(minOccurs);
+      eReference.setUpperBound(maxOccurs);
+
+      eClass.getEStructuralFeatures().add(eReference);
+      if (xsdComponent == null || xsdComponent instanceof XSDSimpleTypeDefinition)
+      {
+        extendedMetaData.setName(eReference, ":" + eClass.getEAllStructuralFeatures().indexOf(eReference));
+        extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.SIMPLE_FEATURE);
+        eReference.setResolveProxies(!isLocalReferenceType((XSDSimpleTypeDefinition)xsdComponent));
+      }
+      else 
+      {
+        map(xsdComponent, eReference);
+        if (xsdComponent instanceof XSDParticle)
+        {
+          eReference.setContainment(true);
+          eReference.setResolveProxies(false);
+
+          XSDParticle xsdParticle = (XSDParticle)xsdComponent;
+
+          XSDTerm xsdTerm = ((XSDParticle)xsdComponent).getTerm();
+          if (xsdTerm instanceof XSDElementDeclaration)
+          {
+            XSDElementDeclaration xsdElementDeclaration = (XSDElementDeclaration)xsdTerm;
+            extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.ELEMENT_FEATURE);
+            extendedMetaData.setName(eReference, xsdElementDeclaration.getName());
+            extendedMetaData.setNamespace(eReference, xsdElementDeclaration.getTargetNamespace());
+
+            XSDTypeDefinition xsdType = getEffectiveTypeDefinition(xsdParticle, xsdElementDeclaration);
+            if (xsdType instanceof XSDSimpleTypeDefinition)
+            {
+              eReference.setContainment(false);
+              eReference.setResolveProxies(!isLocalReferenceType((XSDSimpleTypeDefinition)xsdType));
+            }
+
+            if (maxOccurs == 1 && xsdElementDeclaration.isNillable())
+            {
+              eReference.setUnsettable(true);
+            }
+
+            if (xsdElementDeclaration.isAbstract())
+            {
+              eReference.setChangeable(false);
+            }
+
+            String opposite = getEcoreAttribute(xsdParticle, "opposite");
+            if (opposite != null)
+            {
+              eReferenceToOppositeNameMap.put(eReference, opposite);
+            }
+          }
+          else if (xsdTerm instanceof XSDWildcard)
+          {
+            // EATM shouldn't happen
+            XSDWildcard xsdWildcard = (XSDWildcard)xsdTerm;
+            extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.ELEMENT_WILDCARD_FEATURE);
+            extendedMetaData.setWildcards(eReference, getWildcards(xsdWildcard));
+            extendedMetaData.setProcessingKind(eReference, xsdWildcard.getProcessContents().getValue() + 1);
+            extendedMetaData.setName(eReference, ":" + eClass.getEAllStructuralFeatures().indexOf(eReference));
+          }
+          else
+          {
+            extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.GROUP_FEATURE);
+            extendedMetaData.setName(eReference, ":" + eClass.getEAllStructuralFeatures().indexOf(eReference));
+          }
+        }
+        else if (xsdComponent instanceof XSDElementDeclaration)
+        {
+          XSDElementDeclaration xsdElementDeclaration = (XSDElementDeclaration)xsdComponent;
+          eReference.setContainment(true);
+          eReference.setResolveProxies(false);
+          extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.ELEMENT_FEATURE);
+          extendedMetaData.setName(eReference, xsdElementDeclaration.getName());
+          extendedMetaData.setNamespace(eReference, xsdElementDeclaration.getTargetNamespace());
+
+          XSDElementDeclaration substitutionGroupAffiliation = xsdElementDeclaration.getSubstitutionGroupAffiliation();
+          if (substitutionGroupAffiliation != null)
+          {
+            EStructuralFeature affiliation = getEStructuralFeature(substitutionGroupAffiliation);
+            extendedMetaData.setAffiliation(eReference, affiliation);
+          }
+          XSDTypeDefinition xsdType = getEffectiveTypeDefinition(null, xsdElementDeclaration);
+          if (xsdType instanceof XSDSimpleTypeDefinition)
+          {
+            eReference.setResolveProxies(!isLocalReferenceType((XSDSimpleTypeDefinition)xsdType));
+          }
+
+          if (maxOccurs == 1 && xsdElementDeclaration.isNillable())
+          {
+            eReference.setUnsettable(true);
+          }
+
+          if (xsdElementDeclaration.isAbstract())
+          {
+            eReference.setChangeable(false);
+          }
+        }
+        else if (xsdComponent instanceof XSDAttributeUse)
+        {
+          String opposite = getEcoreAttribute(xsdComponent, "opposite");
+          if (opposite != null)
+          {
+            eReferenceToOppositeNameMap.put(eReference, opposite);
+          }
+          
+          XSDAttributeUse xsdAttributeUse = (XSDAttributeUse)xsdComponent;
+          XSDAttributeDeclaration xsdAttributeDeclaration = xsdAttributeUse.getAttributeDeclaration();
+          extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.ATTRIBUTE_FEATURE);
+          extendedMetaData.setName(eReference, xsdAttributeDeclaration.getName());
+          extendedMetaData.setNamespace(eReference, xsdAttributeDeclaration.getTargetNamespace());
+          eReference.setResolveProxies
+            (!isLocalReferenceType((XSDSimpleTypeDefinition)getEffectiveTypeDefinition(xsdAttributeUse, xsdAttributeDeclaration)));
+        }
+        else if (xsdComponent instanceof XSDAttributeDeclaration)
+        {
+          XSDAttributeDeclaration xsdAttributeDeclaration = (XSDAttributeDeclaration)xsdComponent;
+          extendedMetaData.setFeatureKind(eReference, ExtendedMetaData.ATTRIBUTE_FEATURE);
+          extendedMetaData.setName(eReference, xsdAttributeDeclaration.getName());
+          extendedMetaData.setNamespace(eReference, xsdAttributeDeclaration.getTargetNamespace());
+          eReference.setResolveProxies
+            (!isLocalReferenceType((XSDSimpleTypeDefinition)getEffectiveTypeDefinition(null, xsdAttributeDeclaration)));
+        }
+      }
+
+      return eReference;
+    }
+    else
+    {
+      EAttribute eAttribute = ecoreFactory.createEAttribute();
+      setAnnotations(eAttribute, xsdComponent);
+      eAttribute.setName(Character.toLowerCase(name.charAt(0)) + name.substring(1));
+      eAttribute.setUnique(false);
+      eAttribute.setEType(type);
+      eAttribute.setLowerBound(minOccurs);
+      eAttribute.setUpperBound(maxOccurs);
+      eClass.getEStructuralFeatures().add(eAttribute);
+
+      if (xsdComponent == null || xsdComponent instanceof XSDSimpleTypeDefinition)
+      {
+        extendedMetaData.setName(eAttribute, ":" + eClass.getEAllStructuralFeatures().indexOf(eAttribute));
+        extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.SIMPLE_FEATURE);
+      }
+      else
+      {
+        map(xsdComponent, eAttribute);
+        if (xsdComponent instanceof XSDAttributeUse)
+        {
+          XSDAttributeUse xsdAttributeUse = (XSDAttributeUse)xsdComponent;
+          XSDAttributeDeclaration xsdAttributeDeclaration = xsdAttributeUse.getAttributeDeclaration();
+          extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ATTRIBUTE_FEATURE);
+          extendedMetaData.setName(eAttribute, xsdAttributeDeclaration.getName());
+          extendedMetaData.setNamespace(eAttribute, xsdAttributeDeclaration.getTargetNamespace());
+
+          String defaultValue = getEcoreAttribute(xsdComponent, "default");
+          if (defaultValue == null)
+          {
+            defaultValue = xsdAttributeUse.getLexicalValue();
+          }
+          eAttribute.setDefaultValueLiteral(defaultValue);
+          initialize(eAttribute, (XSDSimpleTypeDefinition)getEffectiveTypeDefinition(xsdAttributeUse, xsdAttributeDeclaration));
+        }
+        else if (xsdComponent instanceof XSDAttributeDeclaration)
+        {
+          XSDAttributeDeclaration xsdAttributeDeclaration = (XSDAttributeDeclaration)xsdComponent;
+          extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ATTRIBUTE_FEATURE);
+          extendedMetaData.setName(eAttribute, xsdAttributeDeclaration.getName());
+          extendedMetaData.setNamespace(eAttribute, xsdAttributeDeclaration.getTargetNamespace());
+
+          eAttribute.setDefaultValueLiteral(xsdAttributeDeclaration.getLexicalValue());
+          initialize(eAttribute, (XSDSimpleTypeDefinition)getEffectiveTypeDefinition(null, xsdAttributeDeclaration));
+        }
+        else if (xsdComponent instanceof XSDParticle)
+        {
+          XSDTerm xsdTerm = ((XSDParticle)xsdComponent).getTerm();
+          if (xsdTerm instanceof XSDElementDeclaration)
+          {
+            XSDElementDeclaration xsdElementDeclaration = (XSDElementDeclaration)xsdTerm;
+            extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ELEMENT_FEATURE);
+            extendedMetaData.setName(eAttribute, xsdElementDeclaration.getName());
+            extendedMetaData.setNamespace(eAttribute, xsdElementDeclaration.getTargetNamespace());
+
+            eAttribute.setDefaultValueLiteral(xsdElementDeclaration.getLexicalValue());
+            XSDTypeDefinition xsdType = getEffectiveTypeDefinition(xsdComponent, xsdElementDeclaration);
+            if (xsdType instanceof XSDSimpleTypeDefinition)
+            {
+              initialize(eAttribute, (XSDSimpleTypeDefinition)xsdType);
+            }
+
+            if (xsdElementDeclaration.isNillable())
+            {
+              if (!canSupportNull((EDataType)type))
+              {
+                eAttribute.setEType(type = (EDataType)typeToTypeObjectMap.get(type));
+              }
+              if (maxOccurs == 1)
+              {
+                eAttribute.setUnsettable(true);
+              }
+            }
+
+            if (xsdElementDeclaration.isAbstract())
+            {
+              eAttribute.setChangeable(false);
+            }
+          }
+          else if (xsdTerm instanceof XSDWildcard)
+          {
+            XSDWildcard xsdWildcard = (XSDWildcard)xsdTerm;
+            extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ELEMENT_WILDCARD_FEATURE);
+            extendedMetaData.setWildcards(eAttribute, getWildcards(xsdWildcard));
+            extendedMetaData.setProcessingKind(eAttribute, xsdWildcard.getProcessContents().getValue() + 1);
+            extendedMetaData.setName(eAttribute, ":" + eClass.getEAllStructuralFeatures().indexOf(eAttribute));
+          }
+          else
+          {
+            extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.GROUP_FEATURE);
+          }
+        }
+        else if (xsdComponent instanceof XSDWildcard)
+        {
+          XSDWildcard xsdWildcard = (XSDWildcard)xsdComponent;
+          extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ATTRIBUTE_WILDCARD_FEATURE);
+          extendedMetaData.setWildcards(eAttribute, getWildcards(xsdWildcard));
+          extendedMetaData.setProcessingKind(eAttribute, xsdWildcard.getProcessContents().getValue() + 1);
+          extendedMetaData.setName(eAttribute, ":" + eClass.getEAllStructuralFeatures().indexOf(eAttribute));
+        }
+        else if (xsdComponent instanceof XSDElementDeclaration)
+        {
+          XSDElementDeclaration xsdElementDeclaration = (XSDElementDeclaration)xsdComponent;
+          extendedMetaData.setFeatureKind(eAttribute, ExtendedMetaData.ELEMENT_FEATURE);
+          extendedMetaData.setName(eAttribute, xsdElementDeclaration.getName());
+          extendedMetaData.setNamespace(eAttribute, xsdElementDeclaration.getTargetNamespace());
+
+          eAttribute.setDefaultValueLiteral(xsdElementDeclaration.getLexicalValue());
+          XSDTypeDefinition xsdType = getEffectiveTypeDefinition(null, xsdElementDeclaration);
+          if (xsdType instanceof XSDSimpleTypeDefinition)
+          {
+            initialize(eAttribute, (XSDSimpleTypeDefinition)xsdType);
+          }
+
+          XSDElementDeclaration substitutionGroupAffiliation = xsdElementDeclaration.getSubstitutionGroupAffiliation();
+          if (substitutionGroupAffiliation != null)
+          {
+            EStructuralFeature affiliation = getEStructuralFeature(substitutionGroupAffiliation);
+            extendedMetaData.setAffiliation(eAttribute, affiliation);
+          }
+
+          if (xsdElementDeclaration.isNillable() && !canSupportNull((EDataType)type))
+          {
+              eAttribute.setEType(type = (EDataType)typeToTypeObjectMap.get(type));
+            if (maxOccurs == 1)
+            {
+              eAttribute.setUnsettable(true);
+            }
+          }
+
+          if (xsdElementDeclaration.isAbstract())
+          {
+            eAttribute.setChangeable(false);
+          }
+        }
+      }
+
+      if (maxOccurs == 1 && (type.getDefaultValue() != null || eAttribute.getDefaultValueLiteral() != null))
+      {
+        eAttribute.setUnsettable(true);
+      }
+
+      return eAttribute;
+    }
+  }
+
+  protected XSDTypeDefinition getEffectiveTypeDefinition(XSDComponent xsdComponent, XSDFeature xsdFeature) 
+  {
+    return xsdFeature == null ? 
+        ((XSDComplexTypeDefinition)xsdComponent.eContainer()).getSimpleType() : xsdFeature.getType();
+  }
+  
+  protected EStructuralFeature createFeature
+   (EClass eClass, XSDElementDeclaration xsdElementDeclaration, String name, XSDComponent xsdComponent, int minOccurs, int maxOccurs)
+  {
+    XSDTypeDefinition elementTypeDefinition = getEffectiveTypeDefinition(xsdComponent, xsdElementDeclaration);
+    EClassifier eClassifier = getEClassifier(elementTypeDefinition);
+  
+    XSDTypeDefinition referenceType = getEcoreTypeQNameAttribute(xsdComponent, "reference");
+    if (referenceType == null)
+    {
+      referenceType = getEcoreTypeQNameAttribute(xsdElementDeclaration, "reference");
+    }
+    if (referenceType != null)
+    {
+      EClassifier referenceClassifier = getEClassifier(referenceType);
+      boolean needsHolder = false;
+      if (elementTypeDefinition instanceof XSDSimpleTypeDefinition)
+      {
+        XSDSimpleTypeDefinition xsdSimpleTypeDefinition = (XSDSimpleTypeDefinition)elementTypeDefinition;
+        if (xsdSimpleTypeDefinition.getVariety() == XSDVariety.LIST_LITERAL)
+        {
+          needsHolder = true;
+          
+          EPackage holderPackage = getEPackage(xsdElementDeclaration);
+          String holderName = xsdElementDeclaration.getName() + ":holder";
+          EClass holderClass = (EClass)extendedMetaData.getType(holderPackage, holderName);
+          if (holderClass == null)
+          {
+            // Create a holder class like an anonymous complex type.
+            //
+            holderClass = ecoreFactory.createEClass();
+            setAnnotations(holderClass, xsdElementDeclaration);
+            holderClass.setName(validName(holderName, true));
+            extendedMetaData.setName(holderClass, holderName);
+            extendedMetaData.setContentKind(holderClass, ExtendedMetaData.SIMPLE_CONTENT);
+                   
+            addToSortedList(holderPackage.getEClassifiers(), holderClass);
+     
+            EReference holderReference =
+              (EReference)createFeature
+                (holderClass,
+                 "value",
+                 referenceClassifier,
+                 null,
+                 0,
+                 -1);
+     
+            holderReference.setResolveProxies(!isLocalReferenceType(xsdSimpleTypeDefinition));
+          }
+          referenceClassifier = holderClass;
+        }
+      }
+      EStructuralFeature result =
+        createFeature
+          (eClass,
+           name,
+           referenceClassifier,
+           xsdComponent,
+           minOccurs,
+           maxOccurs);
+      ((EReference)result).setContainment(needsHolder);
+      if (needsHolder)
+      {
+        ((EReference)result).setUnsettable(false);
+        ((EReference)result).setResolveProxies(false);
+      }
+      initialize(result, xsdElementDeclaration, xsdComponent);
+      return result;
+    }
+    else
+    {
+      EStructuralFeature result =
+        createFeature
+          (eClass,
+           name,
+           eClassifier,
+           xsdComponent,
+           minOccurs,
+           maxOccurs);
+      initialize(result, xsdElementDeclaration, xsdComponent);
+      return result;
+    }
+  }
+
+  protected EStructuralFeature createFeature
+    (EClass eClass, XSDAttributeDeclaration xsdAttributeDeclaration, String name, XSDComponent xsdComponent, boolean isRequired)
+  {
+    XSDSimpleTypeDefinition attributeTypeDefinition = (XSDSimpleTypeDefinition)getEffectiveTypeDefinition(xsdComponent, xsdAttributeDeclaration);
+    if (attributeTypeDefinition == null)
+    {
+      attributeTypeDefinition = xsdComponent.getSchema().getSchemaForSchema().resolveSimpleTypeDefinition("anySimpleType");
+    }
+  
+    XSDTypeDefinition referenceType = getEcoreTypeQNameAttribute(xsdComponent, "reference");
+    if (referenceType == null && xsdAttributeDeclaration != null)
+    {
+      referenceType = getEcoreTypeQNameAttribute(xsdAttributeDeclaration, "reference");
+    }
+    if (referenceType != null)
+    {
+      int lowerBound = isRequired ? 1 : 0;
+      int upperBound = 1;
+      if (attributeTypeDefinition.getVariety() == XSDVariety.LIST_LITERAL)
+      {
+        XSDLengthFacet xsdLengthFacet = attributeTypeDefinition.getEffectiveLengthFacet();
+        if (isRequired)
+        {
+          if (xsdLengthFacet != null)
+          {
+            lowerBound = xsdLengthFacet.getValue();
+          }
+          else
+          {
+            XSDMinLengthFacet xsdMinLengthFacet = attributeTypeDefinition.getEffectiveMinLengthFacet();
+            if (xsdMinLengthFacet != null)
+            {
+              lowerBound = xsdMinLengthFacet.getValue();
+            }
+          }
+        }
+        if (xsdLengthFacet != null)
+        {
+          upperBound = xsdLengthFacet.getValue();
+        }
+        else
+        {
+          XSDMaxLengthFacet xsdMaxLengthFacet = attributeTypeDefinition.getEffectiveMaxLengthFacet();
+          if (xsdMaxLengthFacet != null)
+          {
+            upperBound = xsdMaxLengthFacet.getValue();
+          }
+          else
+          {
+            upperBound = -1;
+          }
+        }
+      }
+  
+      EClassifier referenceClassifier = getEClassifier(referenceType);
+      EStructuralFeature result =
+        createFeature
+          (eClass,
+           name,
+           referenceClassifier,
+           xsdComponent,
+           lowerBound,
+           upperBound);
+      initialize(result, xsdAttributeDeclaration, xsdComponent);
+      return result;
+    }
+    else
+    {
+      boolean isMany = 
+          attributeTypeDefinition.getVariety() == XSDVariety.LIST_LITERAL &&
+          xsdComponent instanceof XSDAttributeUse && 
+          "true".equals(getEcoreAttribute(xsdComponent, "many"));
+      if (isMany)
+      {
+        EDataType eDataType = getEDataType(attributeTypeDefinition.getItemTypeDefinition());
+        XSDLengthFacet xsdLengthFacet = attributeTypeDefinition.getEffectiveLengthFacet();
+        int lowerBound = isRequired ? 1 : 0;
+        int upperBound = -1;
+        if (isRequired)
+        {
+          if (xsdLengthFacet != null)
+          {
+            lowerBound = xsdLengthFacet.getValue();
+          }
+          else
+          {
+            XSDMinLengthFacet xsdMinLengthFacet = attributeTypeDefinition.getEffectiveMinLengthFacet();
+            if (xsdMinLengthFacet != null)
+            {
+              lowerBound = xsdMinLengthFacet.getValue();
+            }
+          }
+        }
+        if (xsdLengthFacet != null)
+        {
+          upperBound = xsdLengthFacet.getValue();
+        }
+        else
+        {
+          XSDMaxLengthFacet xsdMaxLengthFacet = attributeTypeDefinition.getEffectiveMaxLengthFacet();
+          if (xsdMaxLengthFacet != null)
+          {
+            upperBound = xsdMaxLengthFacet.getValue();
+          }
+        }
+        EStructuralFeature result =
+          createFeature
+            (eClass,
+             name,
+             eDataType,
+             xsdComponent,
+             lowerBound,
+             upperBound);
+        initialize(result, xsdAttributeDeclaration, xsdComponent);
+        return result;
+      }
+      else
+      {
+        EDataType eDataType = getEDataType(attributeTypeDefinition);
+        EStructuralFeature result =
+          createFeature
+            (eClass,
+             name,
+             eDataType,
+             xsdComponent,
+             isRequired ? 1 : 0,
+             1);
+        initialize(result, xsdAttributeDeclaration, xsdComponent);
+        return result;
+      }
+    }
+  }
+  
+  public EStructuralFeature getEStructuralFeature(XSDFeature xsdFeature)
+  {
+    if ("true".equals(getEcoreAttribute(xsdFeature, "ignore"))) return null;
+    EStructuralFeature eStructuralFeature = (EStructuralFeature)xsdComponentToEModelElementMap.get(xsdFeature);
+    if (eStructuralFeature == null)
+    {
+      EPackage ePackage = getEPackage(xsdFeature);
+      EClass documentEClass = extendedMetaData.getDocumentRoot(ePackage);
+      if (documentEClass == null)
+      {
+          createDocumentRoot(xsdFeature.getSchema(), ePackage);
+      }
+
+      String name = getEcoreAttribute(xsdFeature, "name");
+      if (name == null)
+      {
+        name= validName(xsdFeature.getName(), true);       
+      }
+      
+      if (xsdFeature instanceof XSDElementDeclaration)
+      {
+        // Mark the bound as unspecified so that it won't be considered many 
+        // but can nevertheless be recognized as being unspecified and perhaps still be treat as many.
+        //
+        EStructuralFeature result = 
+          createFeature(documentEClass, (XSDElementDeclaration)xsdFeature, name, xsdFeature, 0, ETypedElement.UNSPECIFIED_MULTIPLICITY);            
+
+        result.setDerived(true);
+        result.setTransient(true);
+        result.setVolatile(true);
+        return result;
+      }
+      else
+      {
+        EStructuralFeature result = 
+          createFeature(documentEClass, (XSDAttributeDeclaration)xsdFeature, name, xsdFeature, false);
+        return result;
+      }
+    }
+
+    return eStructuralFeature;
+  }
+
+  public void generate(XSDSchema xsdSchema)
+  {
+    this.rootSchema = xsdSchema;
+    if (xsdSchemas.add(xsdSchema))
+    {
+      addInput(xsdSchema);
+      validate(xsdSchema);
+    }
+
+    Collection visitedElementDeclarations = new ArrayList();
+    Collection elementDeclarations = new ArrayList(xsdSchema.getElementDeclarations());
+
+    Collection visitedAttributeDeclarations = new ArrayList();
+    Collection attributeDeclarations = new ArrayList(xsdSchema.getAttributeDeclarations());
+
+    Collection visitedTypeDefinitions = new ArrayList();
+    Collection typeDefinitions = new ArrayList(xsdSchema.getTypeDefinitions());
+
+    while (!elementDeclarations.isEmpty() || !attributeDeclarations.isEmpty() || !typeDefinitions.isEmpty())
+    {
+      for (Iterator i = elementDeclarations.iterator(); i.hasNext(); )
+      {
+        XSDElementDeclaration xsdElementDeclaration = (XSDElementDeclaration)i.next();
+        getEStructuralFeature(xsdElementDeclaration);
+      }
+      visitedElementDeclarations.addAll(elementDeclarations);
+      elementDeclarations = new ArrayList(xsdSchema.getElementDeclarations());
+      elementDeclarations.removeAll(visitedElementDeclarations);
+
+      for (Iterator i = attributeDeclarations.iterator(); i.hasNext(); )
+      {
+        XSDAttributeDeclaration xsdAttributeDeclaration = (XSDAttributeDeclaration)i.next();
+        if (!XSDConstants.isSchemaInstanceNamespace(xsdAttributeDeclaration.getTargetNamespace()))
+        {
+          getEStructuralFeature(xsdAttributeDeclaration);
+        }
+      }
+      visitedAttributeDeclarations.addAll(attributeDeclarations);
+      attributeDeclarations = new ArrayList(xsdSchema.getAttributeDeclarations());
+      attributeDeclarations.removeAll(visitedAttributeDeclarations);
+
+      for (Iterator i = typeDefinitions.iterator(); i.hasNext(); )
+      {
+        XSDTypeDefinition xsdTypeDefinition = (XSDTypeDefinition)i.next();
+        getEClassifier(xsdTypeDefinition);
+      }
+      visitedTypeDefinitions.addAll(typeDefinitions);
+      typeDefinitions = new ArrayList(xsdSchema.getTypeDefinitions());
+      typeDefinitions.removeAll(visitedTypeDefinitions);
+    }
+
+    resolveNameConflicts();
+
+    for (Iterator i = xsdSchemas.iterator(); i.hasNext(); )
+    {
+      XSDSchema generatedXSDSchema = (XSDSchema)i.next();
+      EPackage ePackage = (EPackage)targetNamespaceToEPackageMap.get(generatedXSDSchema.getTargetNamespace());
+      if (ePackage != null)
+      {
+        String packageName= getEcoreAttribute(generatedXSDSchema, "package");
+        if (packageName != null)
+        {
+          ePackage.setName(packageName);
+        }
+        String packageNsPrefix= getEcoreAttribute(generatedXSDSchema, "nsPrefix");
+        if (packageNsPrefix != null)
+        {
+          ePackage.setNsPrefix(packageNsPrefix);
+        }
+      }
+    }
+
+    for (Iterator i = eReferenceToOppositeNameMap.entrySet().iterator(); i.hasNext(); )
+    {
+      Map.Entry entry = (Map.Entry)i.next();
+      EReference eReference = (EReference)entry.getKey();
+      String opposite = (String)entry.getValue();
+      EClass oppositeEClass = eReference.getEReferenceType();
+      if (eReference.getEOpposite() == null)
+      {
+        EStructuralFeature eOppositeFeature =  oppositeEClass.getEStructuralFeature(opposite);
+        
+        // Match by XML name if this fails.
+        if (eOppositeFeature == null)
+        {
+          for (Iterator j = oppositeEClass.getEAllStructuralFeatures().iterator(); j.hasNext(); )
+          {
+            EStructuralFeature feature = (EStructuralFeature)j.next();
+            if (opposite.equals(extendedMetaData.getName(feature)))
+            {
+              eOppositeFeature = feature;
+              break;
+            }
+          }
+        }
+        
+        if (eOppositeFeature instanceof EReference)
+        {
+          EReference eOpposite = (EReference)eOppositeFeature;
+          eOpposite.setEOpposite(eReference);
+          eReference.setEOpposite(eOpposite);
+        }
+      }
+
+      if (eReference.getEOpposite() == null && eReference.isContainment())
+      {
+        EReference eOpposite = ecoreFactory.createEReference();
+        eOpposite.setName(opposite);
+        eOpposite.setEType(eReference.getEContainingClass());
+        eOpposite.setLowerBound(0);
+        eOpposite.setEOpposite(eReference);
+        eReference.setEOpposite(eOpposite);
+        eOpposite.setTransient(true);
+        oppositeEClass.getEStructuralFeatures().add(eOpposite);
+      }
+    }
+
+    eReferenceToOppositeNameMap.clear();
+  }
+
+}
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/helper/CrossScopeCopyHelperImpl.java b/impl/src/main/java/org/apache/tuscany/sdo/helper/CrossScopeCopyHelperImpl.java
index b7a5534..3f51876 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/helper/CrossScopeCopyHelperImpl.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/helper/CrossScopeCopyHelperImpl.java
@@ -1,255 +1,255 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.helper;

-

-import java.util.Iterator;

-import java.util.Map;

-

-import org.eclipse.emf.ecore.EAttribute;

-import org.eclipse.emf.ecore.EClass;

-import org.eclipse.emf.ecore.EObject;

-import org.eclipse.emf.ecore.EReference;

-import org.eclipse.emf.ecore.EStructuralFeature;

-import org.eclipse.emf.ecore.util.EcoreUtil;

-import org.eclipse.emf.ecore.util.FeatureMap;

-import org.eclipse.emf.ecore.util.FeatureMapUtil;

-import org.eclipse.emf.ecore.util.InternalEList;

-import org.eclipse.emf.ecore.util.EcoreUtil.Copier;

-

-import commonj.sdo.DataObject;

-import commonj.sdo.Type;

-import commonj.sdo.helper.CopyHelper;

-import commonj.sdo.helper.TypeHelper;

-

-/**

- * A CopyHelper implementation that creates the copy objects in a specific metadata scope.

- * The target scope must contain a compatible version of the Types needed to create the copy objects.

- */

-public class CrossScopeCopyHelperImpl implements CopyHelper 

-{

-  protected TypeHelper scope;

-    

-  public CrossScopeCopyHelperImpl(TypeHelper targetScope)

-  {

-    scope = targetScope;

-  }

-    

-  public DataObject copyShallow(DataObject dataObject)

-  {

-    Copier copier = new CrossScopeCopier()

-    {

-      protected void copyContainment(EReference eReference, EObject eObject, EObject copyEObject)

-      {

-      }

-      protected void copyAttribute(EAttribute eAttribute, EObject eObject, EObject copyEObject)

-      {

-        if (eObject.eIsSet(eAttribute) && !FeatureMapUtil.isFeatureMap(eAttribute))

-		{

-		  super.copyAttribute(eAttribute,eObject,copyEObject);

-		}

-	  }

-    };

-    EObject result = copier.copy((EObject)dataObject);

-    copier.copyReferences();

-    return (DataObject)result;

-  }

-

-  public DataObject copy(DataObject dataObject)

-  {

-    Copier copier = new CrossScopeCopier();

-    DataObject result = (DataObject)copier.copy((EObject)dataObject);

-    copier.copyReferences();

-    return (DataObject)result;

-  }

-    

-  protected class CrossScopeCopier extends EcoreUtil.Copier

-  {

-    protected boolean useOriginalReferences = false;

-      

-    protected EClass getTarget(EClass eClass)

-    {

-      EClass target = (EClass)get(eClass);

-      if (target == null)

-      {

-        Type type = (Type)eClass;

-        target = (EClass)scope.getType(type.getURI(), type.getName());

-      }

-      return target;

-    }

-      

-    protected EStructuralFeature getTarget(EStructuralFeature eStructuralFeature)

-    {

-      EClass eClass = getTarget(eStructuralFeature.getEContainingClass());

-      EStructuralFeature targetEf = eClass.getEStructuralFeature(eStructuralFeature.getName());

-      return targetEf;

-    }

-    

-    /**

-     * This Method WILL BE REMOVED when EMF 3.0 is available

-     */

-    public void copyReferences()

-    {

-      for (Iterator i = entrySet().iterator(); i.hasNext();)

-      {

-        Map.Entry entry = (Map.Entry)i.next();

-        EObject eObject = (EObject)entry.getKey();

-        EObject copyEObject = (EObject)entry.getValue();

-        EClass eClass = eObject.eClass();

-        for (int j = 0, size = eClass.getFeatureCount(); j < size; ++j)

-        {

-          EStructuralFeature eStructuralFeature = eClass.getEStructuralFeature(j);

-          if (eStructuralFeature.isChangeable() && !eStructuralFeature.isDerived())

-          {

-            if (eStructuralFeature instanceof EReference)

-            {

-              EReference eReference = (EReference)eStructuralFeature;

-              if (!eReference.isContainment() && !eReference.isContainer())

-              {

-                copyReference(eReference, eObject, copyEObject);

-              }

-            }

-            else if (FeatureMapUtil.isFeatureMap(eStructuralFeature))

-            {

-              FeatureMap featureMap = (FeatureMap)eObject.eGet(eStructuralFeature);

-              FeatureMap copyFeatureMap = (FeatureMap)copyEObject.eGet(getTarget(eStructuralFeature));

-              int copyFeatureMapSize = copyFeatureMap.size();

-              for (int k = 0, featureMapSize = featureMap.size(); k < featureMapSize; ++k)

-              {

-                EStructuralFeature feature = featureMap.getEStructuralFeature(k);

-                if (feature instanceof EReference)

-                {

-                  Object referencedEObject = featureMap.getValue(k);

-                  Object copyReferencedEObject = get(referencedEObject);

-                  if (copyReferencedEObject == null && referencedEObject != null)

-                  {

-                    EReference reference = (EReference)feature;

-                    if (!useOriginalReferences || reference.isContainment() || reference.getEOpposite() != null)

-                    {

-                      continue;

-                    }

-                    copyReferencedEObject = referencedEObject;

-                  }

-                  // If we can't add it, it must aleady be in the list so find it and move it to the end.

-                  //

-                  if (!copyFeatureMap.add(feature, copyReferencedEObject))

-                  {

-                    for (int l = 0; l < copyFeatureMapSize; ++l) 

-                    {

-                      if (copyFeatureMap.getEStructuralFeature(l) == feature && copyFeatureMap.getValue(l) == copyReferencedEObject)

-                      {

-                        copyFeatureMap.move(copyFeatureMap.size() - 1, l);

-                        --copyFeatureMapSize;

-                        break;

-                      }

-                    }

-                  }

-                }

-                else

-                {

-                  copyFeatureMap.add(featureMap.get(k));

-                }

-              }

-            }

-          }

-        }

-      }

-    }

-

-    /**

-     * This Method WILL BE REMOVED when EMF 3.0 is available

-     */

-    protected void copyReference(EReference eReference, EObject eObject, EObject copyEObject)

-    {

-      if (eObject.eIsSet(eReference))

-      {

-        if (eReference.isMany())

-        {

-          InternalEList source = (InternalEList)eObject.eGet(eReference);

-          InternalEList target = (InternalEList)copyEObject.eGet(getTarget(eReference));

-          if (source.isEmpty())

-          {

-            target.clear();

-          }

-          else

-          {

-            boolean isBidirectional = eReference.getEOpposite() != null;

-            int index = 0;

-            for (Iterator k = resolveProxies ? source.iterator() : source.basicIterator(); k.hasNext();)

-            {

-              Object referencedEObject = k.next();

-              Object copyReferencedEObject = get(referencedEObject);

-              if (copyReferencedEObject == null)

-              {

-                if (useOriginalReferences && !isBidirectional)

-                {

-                  target.addUnique(index, referencedEObject);

-                  ++index;

-                }

-              }

-              else

-              {

-                if (isBidirectional)

-                {

-                  int position = target.indexOf(copyReferencedEObject);

-                  if (position == -1)

-                  {

-                    target.addUnique(index, copyReferencedEObject);

-                  }

-                  else if (index != position)

-                  {

-                    target.move(index, copyReferencedEObject);

-                  }

-                }

-                else

-                {

-                  target.addUnique(index, copyReferencedEObject);

-                }

-                ++index;

-              }

-            }

-          }

-        }

-        else

-        {

-          Object referencedEObject = eObject.eGet(eReference, resolveProxies);

-          if (referencedEObject == null)

-          {

-            copyEObject.eSet(getTarget(eReference), null);

-          }

-          else

-          {

-            Object copyReferencedEObject = get(referencedEObject);

-            if (copyReferencedEObject == null)

-            {

-              if (useOriginalReferences && eReference.getEOpposite() == null)

-              {

-                copyEObject.eSet(getTarget(eReference), referencedEObject);

-              }

-            }

-            else

-            {

-              copyEObject.eSet(getTarget(eReference), copyReferencedEObject);

-            }

-          }

-        }

-      }

-    }

-  }

-}

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.helper;
+
+import java.util.Iterator;
+import java.util.Map;
+
+import org.eclipse.emf.ecore.EAttribute;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EReference;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.util.EcoreUtil;
+import org.eclipse.emf.ecore.util.FeatureMap;
+import org.eclipse.emf.ecore.util.FeatureMapUtil;
+import org.eclipse.emf.ecore.util.InternalEList;
+import org.eclipse.emf.ecore.util.EcoreUtil.Copier;
+
+import commonj.sdo.DataObject;
+import commonj.sdo.Type;
+import commonj.sdo.helper.CopyHelper;
+import commonj.sdo.helper.TypeHelper;
+
+/**
+ * A CopyHelper implementation that creates the copy objects in a specific metadata scope.
+ * The target scope must contain a compatible version of the Types needed to create the copy objects.
+ */
+public class CrossScopeCopyHelperImpl implements CopyHelper 
+{
+  protected TypeHelper scope;
+    
+  public CrossScopeCopyHelperImpl(TypeHelper targetScope)
+  {
+    scope = targetScope;
+  }
+    
+  public DataObject copyShallow(DataObject dataObject)
+  {
+    Copier copier = new CrossScopeCopier()
+    {
+      protected void copyContainment(EReference eReference, EObject eObject, EObject copyEObject)
+      {
+      }
+      protected void copyAttribute(EAttribute eAttribute, EObject eObject, EObject copyEObject)
+      {
+        if (eObject.eIsSet(eAttribute) && !FeatureMapUtil.isFeatureMap(eAttribute))
+		{
+		  super.copyAttribute(eAttribute,eObject,copyEObject);
+		}
+	  }
+    };
+    EObject result = copier.copy((EObject)dataObject);
+    copier.copyReferences();
+    return (DataObject)result;
+  }
+
+  public DataObject copy(DataObject dataObject)
+  {
+    Copier copier = new CrossScopeCopier();
+    DataObject result = (DataObject)copier.copy((EObject)dataObject);
+    copier.copyReferences();
+    return (DataObject)result;
+  }
+    
+  protected class CrossScopeCopier extends EcoreUtil.Copier
+  {
+    protected boolean useOriginalReferences = false;
+      
+    protected EClass getTarget(EClass eClass)
+    {
+      EClass target = (EClass)get(eClass);
+      if (target == null)
+      {
+        Type type = (Type)eClass;
+        target = (EClass)scope.getType(type.getURI(), type.getName());
+      }
+      return target;
+    }
+      
+    protected EStructuralFeature getTarget(EStructuralFeature eStructuralFeature)
+    {
+      EClass eClass = getTarget(eStructuralFeature.getEContainingClass());
+      EStructuralFeature targetEf = eClass.getEStructuralFeature(eStructuralFeature.getName());
+      return targetEf;
+    }
+    
+    /**
+     * This Method WILL BE REMOVED when EMF 3.0 is available
+     */
+    public void copyReferences()
+    {
+      for (Iterator i = entrySet().iterator(); i.hasNext();)
+      {
+        Map.Entry entry = (Map.Entry)i.next();
+        EObject eObject = (EObject)entry.getKey();
+        EObject copyEObject = (EObject)entry.getValue();
+        EClass eClass = eObject.eClass();
+        for (int j = 0, size = eClass.getFeatureCount(); j < size; ++j)
+        {
+          EStructuralFeature eStructuralFeature = eClass.getEStructuralFeature(j);
+          if (eStructuralFeature.isChangeable() && !eStructuralFeature.isDerived())
+          {
+            if (eStructuralFeature instanceof EReference)
+            {
+              EReference eReference = (EReference)eStructuralFeature;
+              if (!eReference.isContainment() && !eReference.isContainer())
+              {
+                copyReference(eReference, eObject, copyEObject);
+              }
+            }
+            else if (FeatureMapUtil.isFeatureMap(eStructuralFeature))
+            {
+              FeatureMap featureMap = (FeatureMap)eObject.eGet(eStructuralFeature);
+              FeatureMap copyFeatureMap = (FeatureMap)copyEObject.eGet(getTarget(eStructuralFeature));
+              int copyFeatureMapSize = copyFeatureMap.size();
+              for (int k = 0, featureMapSize = featureMap.size(); k < featureMapSize; ++k)
+              {
+                EStructuralFeature feature = featureMap.getEStructuralFeature(k);
+                if (feature instanceof EReference)
+                {
+                  Object referencedEObject = featureMap.getValue(k);
+                  Object copyReferencedEObject = get(referencedEObject);
+                  if (copyReferencedEObject == null && referencedEObject != null)
+                  {
+                    EReference reference = (EReference)feature;
+                    if (!useOriginalReferences || reference.isContainment() || reference.getEOpposite() != null)
+                    {
+                      continue;
+                    }
+                    copyReferencedEObject = referencedEObject;
+                  }
+                  // If we can't add it, it must aleady be in the list so find it and move it to the end.
+                  //
+                  if (!copyFeatureMap.add(feature, copyReferencedEObject))
+                  {
+                    for (int l = 0; l < copyFeatureMapSize; ++l) 
+                    {
+                      if (copyFeatureMap.getEStructuralFeature(l) == feature && copyFeatureMap.getValue(l) == copyReferencedEObject)
+                      {
+                        copyFeatureMap.move(copyFeatureMap.size() - 1, l);
+                        --copyFeatureMapSize;
+                        break;
+                      }
+                    }
+                  }
+                }
+                else
+                {
+                  copyFeatureMap.add(featureMap.get(k));
+                }
+              }
+            }
+          }
+        }
+      }
+    }
+
+    /**
+     * This Method WILL BE REMOVED when EMF 3.0 is available
+     */
+    protected void copyReference(EReference eReference, EObject eObject, EObject copyEObject)
+    {
+      if (eObject.eIsSet(eReference))
+      {
+        if (eReference.isMany())
+        {
+          InternalEList source = (InternalEList)eObject.eGet(eReference);
+          InternalEList target = (InternalEList)copyEObject.eGet(getTarget(eReference));
+          if (source.isEmpty())
+          {
+            target.clear();
+          }
+          else
+          {
+            boolean isBidirectional = eReference.getEOpposite() != null;
+            int index = 0;
+            for (Iterator k = resolveProxies ? source.iterator() : source.basicIterator(); k.hasNext();)
+            {
+              Object referencedEObject = k.next();
+              Object copyReferencedEObject = get(referencedEObject);
+              if (copyReferencedEObject == null)
+              {
+                if (useOriginalReferences && !isBidirectional)
+                {
+                  target.addUnique(index, referencedEObject);
+                  ++index;
+                }
+              }
+              else
+              {
+                if (isBidirectional)
+                {
+                  int position = target.indexOf(copyReferencedEObject);
+                  if (position == -1)
+                  {
+                    target.addUnique(index, copyReferencedEObject);
+                  }
+                  else if (index != position)
+                  {
+                    target.move(index, copyReferencedEObject);
+                  }
+                }
+                else
+                {
+                  target.addUnique(index, copyReferencedEObject);
+                }
+                ++index;
+              }
+            }
+          }
+        }
+        else
+        {
+          Object referencedEObject = eObject.eGet(eReference, resolveProxies);
+          if (referencedEObject == null)
+          {
+            copyEObject.eSet(getTarget(eReference), null);
+          }
+          else
+          {
+            Object copyReferencedEObject = get(referencedEObject);
+            if (copyReferencedEObject == null)
+            {
+              if (useOriginalReferences && eReference.getEOpposite() == null)
+              {
+                copyEObject.eSet(getTarget(eReference), referencedEObject);
+              }
+            }
+            else
+            {
+              copyEObject.eSet(getTarget(eReference), copyReferencedEObject);
+            }
+          }
+        }
+      }
+    }
+  }
+}
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/helper/DefaultHelperContextImpl.java b/impl/src/main/java/org/apache/tuscany/sdo/helper/DefaultHelperContextImpl.java
index a8804e9..f7ac226 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/helper/DefaultHelperContextImpl.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/helper/DefaultHelperContextImpl.java
@@ -1,72 +1,72 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.helper;

-

-import java.util.Map;

-import java.util.WeakHashMap;

-

-import org.eclipse.emf.ecore.EPackage;

-import org.eclipse.emf.ecore.impl.EPackageRegistryImpl;

-

-public class DefaultHelperContextImpl extends HelperContextImpl {

-    public DefaultHelperContextImpl(final boolean extensibleNamespaces) {

-        super(new SDOExtendedMetaDataImpl(new SDOPackageRegistryDelegator()), extensibleNamespaces);

-    }

-

-    public DefaultHelperContextImpl(final boolean extensibleNamespaces, final Map options) {

-        super(new SDOExtendedMetaDataImpl(new SDOPackageRegistryDelegator()), extensibleNamespaces, options);

-    }

-    

-    protected static class SDOPackageRegistryDelegator extends EPackageRegistryImpl.Delegator {

-        /**

-         * A map from class loader to its associated registry.

-         */

-        protected Map classLoaderToRegistryMap = new WeakHashMap();

-        

-        /**

-         * Returns the package registry associated with the given class loader.

-         * @param classLoader the class loader.

-         * @return the package registry associated with the given class loader.

-         */

-        public synchronized EPackage.Registry getRegistry(final ClassLoader classLoader)

-        {

-          EPackage.Registry result = (EPackage.Registry)classLoaderToRegistryMap.get(classLoader);

-          if (result == null)

-          {

-            if (classLoader == null)

-            {

-              result = HelperContextImpl.getBuiltInModelRegistry();  

-            }

-            else

-            {

-              result = new EPackageRegistryImpl(getRegistry(classLoader.getParent()));

-              classLoaderToRegistryMap.put(classLoader, result);

-            }

-          }

-          return result;

-        }

-        

-        protected EPackage.Registry delegateRegistry(final ClassLoader classLoader)

-        {

-          return getRegistry(classLoader);

-        }

-    }

-}

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.helper;
+
+import java.util.Map;
+import java.util.WeakHashMap;
+
+import org.eclipse.emf.ecore.EPackage;
+import org.eclipse.emf.ecore.impl.EPackageRegistryImpl;
+
+public class DefaultHelperContextImpl extends HelperContextImpl {
+    public DefaultHelperContextImpl(final boolean extensibleNamespaces) {
+        super(new SDOExtendedMetaDataImpl(new SDOPackageRegistryDelegator()), extensibleNamespaces);
+    }
+
+    public DefaultHelperContextImpl(final boolean extensibleNamespaces, final Map options) {
+        super(new SDOExtendedMetaDataImpl(new SDOPackageRegistryDelegator()), extensibleNamespaces, options);
+    }
+    
+    protected static class SDOPackageRegistryDelegator extends EPackageRegistryImpl.Delegator {
+        /**
+         * A map from class loader to its associated registry.
+         */
+        protected Map classLoaderToRegistryMap = new WeakHashMap();
+        
+        /**
+         * Returns the package registry associated with the given class loader.
+         * @param classLoader the class loader.
+         * @return the package registry associated with the given class loader.
+         */
+        public synchronized EPackage.Registry getRegistry(final ClassLoader classLoader)
+        {
+          EPackage.Registry result = (EPackage.Registry)classLoaderToRegistryMap.get(classLoader);
+          if (result == null)
+          {
+            if (classLoader == null)
+            {
+              result = HelperContextImpl.getBuiltInModelRegistry();  
+            }
+            else
+            {
+              result = new EPackageRegistryImpl(getRegistry(classLoader.getParent()));
+              classLoaderToRegistryMap.put(classLoader, result);
+            }
+          }
+          return result;
+        }
+        
+        protected EPackage.Registry delegateRegistry(final ClassLoader classLoader)
+        {
+          return getRegistry(classLoader);
+        }
+    }
+}
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/helper/SDOHelperImpl.java b/impl/src/main/java/org/apache/tuscany/sdo/helper/SDOHelperImpl.java
index 3efd8d0..922f092 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/helper/SDOHelperImpl.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/helper/SDOHelperImpl.java
@@ -1,530 +1,530 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.helper;

-

-import java.io.IOException;

-import java.io.InputStream;

-import java.io.OutputStream;

-import java.util.ArrayList;

-import java.util.Collections;

-import java.util.HashMap;

-import java.util.HashSet;

-import java.util.Iterator;

-import java.util.List;

-import java.util.Map;

-import java.util.Set;

-

-import org.apache.tuscany.sdo.SDOExtendedMetaData;

-import org.apache.tuscany.sdo.SDOFactory;

-import org.apache.tuscany.sdo.SimpleAnyTypeDataObject;

-import org.apache.tuscany.sdo.api.SDOHelper;

-import org.apache.tuscany.sdo.api.XMLStreamHelper;

-import org.apache.tuscany.sdo.api.EventListener;

-import org.apache.tuscany.sdo.impl.ClassImpl;

-import org.apache.tuscany.sdo.impl.DataGraphImpl;

-import org.apache.tuscany.sdo.impl.DynamicDataObjectImpl;

-import org.apache.tuscany.sdo.model.ModelFactory;

-import org.apache.tuscany.sdo.model.impl.ModelFactoryImpl;

-import org.apache.tuscany.sdo.spi.SDOHelperBase;

-import org.apache.tuscany.sdo.util.DataObjectUtil;

-import org.eclipse.emf.common.notify.Adapter;

-import org.eclipse.emf.common.notify.Notifier;

-import org.eclipse.emf.common.util.URI;

-import org.eclipse.emf.common.util.UniqueEList;

-import org.eclipse.emf.ecore.EAnnotation;

-import org.eclipse.emf.ecore.EAttribute;

-import org.eclipse.emf.ecore.EClass;

-import org.eclipse.emf.ecore.EClassifier;

-import org.eclipse.emf.ecore.EDataType;

-import org.eclipse.emf.ecore.EModelElement;

-import org.eclipse.emf.ecore.EObject;

-import org.eclipse.emf.ecore.EPackage;

-import org.eclipse.emf.ecore.EReference;

-import org.eclipse.emf.ecore.EStructuralFeature;

-import org.eclipse.emf.ecore.ETypedElement;

-import org.eclipse.emf.ecore.EcoreFactory;

-import org.eclipse.emf.ecore.EcorePackage;

-import org.eclipse.emf.ecore.resource.Resource;

-import org.eclipse.emf.ecore.resource.ResourceSet;

-import org.eclipse.emf.ecore.util.EcoreUtil;

-import org.eclipse.emf.ecore.util.ExtendedMetaData;

-import org.eclipse.emf.ecore.util.FeatureMap;

-import org.eclipse.emf.ecore.util.FeatureMapUtil;

-import org.eclipse.emf.ecore.xmi.XMLResource;

-

-import commonj.sdo.DataGraph;

-import commonj.sdo.DataObject;

-import commonj.sdo.Property;

-import commonj.sdo.Sequence;

-import commonj.sdo.Type;

-import commonj.sdo.helper.CopyHelper;

-import commonj.sdo.helper.HelperContext;

-import commonj.sdo.helper.TypeHelper;

-import commonj.sdo.impl.HelperProvider;

-

-public class SDOHelperImpl extends SDOHelperBase implements SDOHelper, SDOHelper.MetaDataBuilder {

-  

-  public DataObject createDataTypeWrapper(Type dataType, Object value) {

-        SimpleAnyTypeDataObject simpleAnyType = SDOFactory.eINSTANCE.createSimpleAnyTypeDataObject();

-        simpleAnyType.setInstanceType((EDataType)dataType);

-        simpleAnyType.setValue(value);

-        return simpleAnyType;

-    }

-

-    public Object createFromString(Type dataType, String literal) {

-        return EcoreUtil.createFromString((EDataType)dataType, literal);

-    }

-

-    public String convertToString(Type dataType, Object value) {

-        return EcoreUtil.convertToString((EDataType)dataType, value);

-    }

-

-    public Type getXSDSDOType(String xsdType) {

-        Type type = null;

-        String name = (String)xsdToSdoMappings.get(xsdType);

-        if (name != null)

-            type = (Type)((ModelFactoryImpl)ModelFactory.INSTANCE).getEClassifier(name);

-        return type;

-    }

-

-    public Sequence getSubstitutionValues(DataObject dataObject, Property head) {

-        final EStructuralFeature group = ExtendedMetaData.INSTANCE.getGroup((EStructuralFeature)head);

-        return null == group ? null : (Sequence)((FeatureMap.Internal)((EObject)dataObject).eGet(group)).getWrapper();

-    }

-

-    public Type getJavaSDOType(Class javaClass) {

-        String name = (String)javaToSdoMappings.get(javaClass);

-        if (name != null) {

-            return (Type)((ModelFactoryImpl)ModelFactory.INSTANCE).getEClassifier(name);

-        }

-        return null;

-    }

-

-    public boolean isRequired(Property property) {

-        return ((EStructuralFeature)property).isRequired();

-    }

-

-    public int getUpperBound(Property property) {

-        return ((EStructuralFeature)property).getUpperBound();

-    }

-

-    public int getLowerBound(Property property) {

-        return ((EStructuralFeature)property).getLowerBound();

-    }

-    

-    public List getEnumerationFacet(Type type) {

-    	List instProps = type.getInstanceProperties();

-    	String propertyName = "enumeration";

-    	Property enumProperty = null;

-    	

-		for (int i = 0; i < instProps.size(); i++)

-		{

-		  Property prop = (Property)instProps.get(i);

-		  if (propertyName.equals(prop.getName()))

-			  enumProperty = prop;

-		}

-

-		return (List)DataObjectUtil.getMetaObjectInstanceProperty((EModelElement)type, enumProperty);

-    }

-    

-    public List getPatternFacet(Type type) {

-    	List instProps = type.getInstanceProperties();

-    	String propertyName = "pattern";

-    	Property patternProperty = null;

-    	

-		for (int i = 0; i < instProps.size(); i++)

-		{

-		  Property prop = (Property)instProps.get(i);

-		  if (propertyName.equals(prop.getName()))

-			  patternProperty = prop;

-		}

-

-		return (List)DataObjectUtil.getMetaObjectInstanceProperty((EModelElement)type, patternProperty);

-    }

-

-    public boolean isMany(Property property, DataObject context) {

-        return FeatureMapUtil.isMany((EObject)context, (EStructuralFeature)property);

-    }

-

-    public DataGraph createDataGraph() {

-        return SDOFactory.eINSTANCE.createDataGraph();

-    }

-

-    public void setRootObject(DataGraph dataGraph, DataObject rootObject) {

-        ((DataGraphImpl)dataGraph).setERootObject((EObject)rootObject);

-    }

-

-    public static DataGraph loadDataGraph(InputStream inputStream, Map options) throws IOException {

-        ResourceSet resourceSet = DataObjectUtil.createResourceSet();

-        Resource resource = resourceSet.createResource(URI.createURI("all.datagraph"));

-        resource.load(inputStream, options);

-        return (DataGraph)resource.getContents().get(0);

-    }

-

-    static final Object LOADING_SCOPE = XMLResource.OPTION_EXTENDED_META_DATA;

-

-    protected void registerLoadingScope(Map options, TypeHelper scope) {

-        Object extendedMetaData = ((TypeHelperImpl)scope).getExtendedMetaData();

-        options.put(LOADING_SCOPE, extendedMetaData);

-    }

-

-    public DataGraph loadDataGraph(InputStream inputStream, Map options, HelperContext scope) throws IOException {

-        if (scope == null) {

-            scope = HelperProvider.getDefaultContext();

-        }

-        TypeHelper th = scope.getTypeHelper();

-        DataGraph result = null;

-		if (th == null || th == TypeHelper.INSTANCE) {

-		    result = loadDataGraph(inputStream, options);

-		} else if (options == null) {

-		    options = new HashMap();

-		    registerLoadingScope(options, th);

-		    result = loadDataGraph(inputStream, options);

-		} else if (options.containsKey(LOADING_SCOPE)) {

-		    Object restore = options.get(LOADING_SCOPE);

-		    registerLoadingScope(options, th);

-		    try {

-		        result = loadDataGraph(inputStream, options);

-		    } finally {

-		        options.put(LOADING_SCOPE, restore);

-		    }

-		} else {

-		    registerLoadingScope(options, th);

-		    try {

-		        result = loadDataGraph(inputStream, options);

-		    } finally {

-		        options.remove(LOADING_SCOPE);

-		    }

-		}

-		return result;

-    }

-

-    public void saveDataGraph(DataGraph dataGraph, OutputStream outputStream, Map options) throws IOException {

-        ((DataGraphImpl)dataGraph).getDataGraphResource().save(outputStream, options);

-    }

-

-    public void registerDataGraphTypes(DataGraph dataGraph, List/* Type */types) {

-        // if (types == null)

-        // types = SDOUtil.getDataGraphTypes(dataGraph);

-

-        Set/* EPackage */packages = new HashSet();

-        for (final Iterator iterator = types.iterator(); iterator.hasNext();) {

-            EClassifier type = (EClassifier)iterator.next();

-            packages.add(type.getEPackage());

-        }

-

-        ResourceSet resourceSet = ((DataGraphImpl)dataGraph).getResourceSet();

-

-        for (Iterator iterator = packages.iterator(); iterator.hasNext();) {

-            EPackage typePackage = (EPackage)iterator.next();

-            Resource resource = typePackage.eResource();

-            if (resource == null) {

-                resource = resourceSet.createResource(URI.createURI(".ecore"));

-                resource.setURI(URI.createURI(typePackage.getNsURI()));

-                resource.getContents().add(typePackage);

-            } else if (resource.getResourceSet() != resourceSet)

-                resourceSet.getResources().add(resource);

-        }

-    }

-

-    public HelperContext createHelperContext() {

-        return new HelperContextImpl(false, null);

-    }

-    

-    public HelperContext createHelperContext(boolean extensibleNamespaces) {

-        return new HelperContextImpl(extensibleNamespaces);

-    }

-    

-    public HelperContext createHelperContext(Map options) {

-        return new HelperContextImpl(false, options);

-    }

-

-    public HelperContext createHelperContext(boolean extensibleNamespaces, Map options) {

-        return new HelperContextImpl(extensibleNamespaces, options);

-    }

-

-

-    public CopyHelper createCrossScopeCopyHelper(HelperContext hc) {

-        return new CrossScopeCopyHelperImpl(hc.getTypeHelper());

-    }

-

-    

-    public XMLStreamHelper createXMLStreamHelper(HelperContext hc) {

-        return ((HelperContextImpl)hc).getXMLStreamHelper();

-    }

-

-    

-    public List getTypes(HelperContext hc, String uri) {

-

-        EPackage ePackage = ((HelperContextImpl)hc).getExtendedMetaData().getPackage(uri);

-        if (ePackage != null) {

-            return new ArrayList(ePackage.getEClassifiers());

-        }

-        return null;

-    }

-

-    public List getOpenContentProperties(DataObject dataObject) {

-        List result = new UniqueEList();

-        ((ClassImpl)dataObject.getType()).addOpenProperties((EObject)dataObject, result);

-        return result;

-    }

-

-    public boolean isDocumentRoot(Type type) {

-        return "".equals(SDOExtendedMetaData.INSTANCE.getName((EClassifier)type));

-    }

-

-    

-    public Type createType(HelperContext hc, String uri, String name, boolean isDataType) {

-        ExtendedMetaData extendedMetaData = ((HelperContextImpl)hc).getExtendedMetaData();

-        if ("".equals(uri))

-            uri = null; // FB

-

-        EPackage ePackage = extendedMetaData.getPackage(uri);

-        if (ePackage == null) {

-            ePackage = EcoreFactory.eINSTANCE.createEPackage();

-            ePackage.setEFactoryInstance(new DynamicDataObjectImpl.FactoryImpl());

-            ePackage.setNsURI(uri);

-            String packagePrefix = uri != null ? URI.createURI(uri).trimFileExtension().lastSegment() : ""; // FB

-            ePackage.setName(packagePrefix);

-            ePackage.setNsPrefix(packagePrefix);

-            extendedMetaData.putPackage(uri, ePackage);

-        }

-

-        EClassifier eClassifier = ePackage.getEClassifier(name);

-        if (eClassifier != null) // already defined?

-        {

-            // throw new IllegalArgumentException();

-            return null;

-        }

-

-        if (name != null) {

-            eClassifier =

-                isDataType ? (EClassifier)SDOFactory.eINSTANCE.createDataType() : (EClassifier)SDOFactory.eINSTANCE

-                    .createClass();

-            eClassifier.setName(name);

-        } else {

-            eClassifier = DataObjectUtil.createDocumentRoot();

-        }

-

-        ePackage.getEClassifiers().add(eClassifier);

-

-        return (Type)eClassifier;

-    }

-

-    public void addBaseType(Type type, Type baseType) {

-        ((EClass)type).getESuperTypes().add(baseType);

-    }

-

-    public void addAliasName(Type type, String aliasName) {

-        throw new UnsupportedOperationException(); // TODO: implement this

-                                                    // method properly

-        // type.getAliasNames().add(aliasName);

-    }

-

-    public void setOpen(Type type, boolean isOpen) {

-        if (isOpen == type.isOpen())

-            return;

-

-        if (isOpen) {

-            EAttribute eAttribute = (EAttribute)SDOFactory.eINSTANCE.createAttribute();

-            ((EClass)type).getEStructuralFeatures().add(eAttribute);

-

-            eAttribute.setName("any");

-            eAttribute.setUnique(false);

-            eAttribute.setUpperBound(ETypedElement.UNBOUNDED_MULTIPLICITY);

-            eAttribute.setEType(EcorePackage.eINSTANCE.getEFeatureMapEntry());

-            ExtendedMetaData.INSTANCE.setFeatureKind(eAttribute, ExtendedMetaData.ELEMENT_WILDCARD_FEATURE);

-            ExtendedMetaData.INSTANCE.setProcessingKind(eAttribute, ExtendedMetaData.LAX_PROCESSING);

-            ExtendedMetaData.INSTANCE.setWildcards(eAttribute, Collections.singletonList("##any"));

-

-            // FB TBD Add an "anyAttribute" EAttribute as well.

-

-            if (ExtendedMetaData.INSTANCE.getMixedFeature((EClass)type) != null) {

-                eAttribute.setDerived(true);

-                eAttribute.setTransient(true);

-                eAttribute.setVolatile(true);

-            }

-        } else {

-            EClass eClass = (EClass)type;

-            EAttribute any = (EAttribute)eClass.getEStructuralFeature("any");

-            eClass.getEStructuralFeatures().remove(any);

-        }

-    }

-

-    public void setSequenced(Type type, boolean isSequenced) {

-        // currently, we require setSequenced to be called first, before

-        // anything else is added to the type.

-        if (type.isDataType() || !type.getProperties().isEmpty()) {

-            if (type.getName() != "DocumentRoot") // document root is a

-                                                    // special case

-                throw new IllegalArgumentException();

-        }

-

-        if (isSequenced) {

-            EClass eClass = (EClass)type;

-            ExtendedMetaData.INSTANCE.setContentKind(eClass, ExtendedMetaData.MIXED_CONTENT);

-            EAttribute mixedFeature = (EAttribute)SDOFactory.eINSTANCE.createAttribute();

-            mixedFeature.setName("mixed");

-            mixedFeature.setUnique(false);

-            mixedFeature.setEType(EcorePackage.eINSTANCE.getEFeatureMapEntry());

-            mixedFeature.setLowerBound(0);

-            mixedFeature.setUpperBound(-1);

-            // eClass.getEStructuralFeatures().add(mixedFeature);

-            ((ClassImpl)eClass).setSequenceFeature(mixedFeature);

-            ExtendedMetaData.INSTANCE.setFeatureKind(mixedFeature, ExtendedMetaData.ELEMENT_WILDCARD_FEATURE);

-            ExtendedMetaData.INSTANCE.setName(mixedFeature, ":mixed");

-        } else {

-            // nothing to do, because of current restriction that setSequence

-            // must be called first.

-        }

-    }

-

-    public void setAbstract(Type type, boolean isAbstract) {

-        ((EClass)type).setAbstract(isAbstract);

-    }

-

-    public void setJavaClassName(Type type, String javaClassName) {

-        ((EClassifier)type).setInstanceClassName(javaClassName);

-    }

-

-    public Property createProperty(Type containingType, String name, Type propertyType) {

-      EStructuralFeature eStructuralFeature = 

-            propertyType.isDataType() ? (EStructuralFeature)SDOFactory.eINSTANCE.createAttribute()

-                : (EStructuralFeature)SDOFactory.eINSTANCE.createReference();

-

-      eStructuralFeature.setName(name);

-      eStructuralFeature.setEType((EClassifier)propertyType);

-      ((EClass)containingType).getEStructuralFeatures().add(eStructuralFeature);

-

-        if ("".equals(ExtendedMetaData.INSTANCE.getName((EClass)containingType))) // DocumentRoot

-                                                                                    // containingType?

-      {

-        ExtendedMetaData.INSTANCE.setNamespace(eStructuralFeature, containingType.getURI());

-        //FB???eStructuralFeature.setUnique(false);

-        //FB???eStructuralFeature.setUpperBound(ETypedElement.UNSPECIFIED_MULTIPLICITY);

-      }

-      

-      if (ExtendedMetaData.INSTANCE.getMixedFeature((EClass)containingType) != null) {

-        eStructuralFeature.setDerived(true);

-        eStructuralFeature.setTransient(true);

-        eStructuralFeature.setVolatile(true);

-        ExtendedMetaData.INSTANCE.setFeatureKind(eStructuralFeature, ExtendedMetaData.ELEMENT_FEATURE);

-      } else {

-          // By default, a SDO property is an XSD element

-          ExtendedMetaData.INSTANCE.setFeatureKind(eStructuralFeature, ExtendedMetaData.ELEMENT_FEATURE);

-      }

-      

-      return (Property)eStructuralFeature;

-    }

-

-  public void setPropertyXMLKind(Property property, boolean isXmlElement) {

-      if (isXmlElement) {

-          ExtendedMetaData.INSTANCE.setFeatureKind((EStructuralFeature)property, ExtendedMetaData.ELEMENT_FEATURE);

-      }

-      else {

-          ExtendedMetaData.INSTANCE.setFeatureKind((EStructuralFeature)property, ExtendedMetaData.ATTRIBUTE_FEATURE);

-      }

-  }

-  

-  

-  public Property createOpenContentProperty(HelperContext hc, String uri, String name, Type type)

-  {

-        ExtendedMetaData extendedMetaData = ((HelperContextImpl)hc).getExtendedMetaData();

-

-        // get/create document root

-        EPackage ePackage = extendedMetaData.getPackage(uri);

-        Type documentRoot = ePackage != null ? (Type)extendedMetaData.getType(ePackage, "") : null;

-        if (documentRoot == null) {

-            documentRoot = createType(hc, uri, null, false);

-        }

-

-        // Determine if property already exists

-        Property newProperty = documentRoot.getProperty(name);

-        if (newProperty == null) {

-            // Create the new property 'under' the document root.....

-            newProperty = createProperty(documentRoot, name, type);

-        } else {

-            // if property already exists, validate the expected type

-            if (!newProperty.getType().equals(type))

-                throw new IllegalArgumentException();

-        }

-        return newProperty;

-    }

-

-

-    public void addAliasName(Property property, String aliasName) {

-        throw new UnsupportedOperationException(); // TODO: implement this

-                                                    // method properly

-        // property.getAliasNames().add(aliasName);

-    }

-

-    public void setMany(Property property, boolean isMany) {

-        ((EStructuralFeature)property).setUpperBound(isMany ? EStructuralFeature.UNBOUNDED_MULTIPLICITY : 1);

-    }

-

-    public void setContainment(Property property, boolean isContainment) {

-        ((EReference)property).setContainment(isContainment);

-    }

-

-    public void setDefault(Property property, String defaultValue) {

-        ((EStructuralFeature)property).setDefaultValueLiteral(defaultValue);

-    }

-

-    public void setReadOnly(Property property, boolean isReadOnly) {

-        ((EStructuralFeature)property).setChangeable(!isReadOnly);

-    }

-

-    public void setOpposite(Property property, Property opposite) {

-        ((EReference)property).setEOpposite((EReference)opposite);

-    }

-

-    public void addTypeInstanceProperty(Type definedType, Property instanceProperty, Object value) {

-        addInstanceProperty((EModelElement)definedType, instanceProperty, value);

-    }

-

-    public void addPropertyInstanceProperty(Property definedProperty, Property instanceProperty, Object value) {

-        addInstanceProperty((EModelElement)definedProperty, instanceProperty, value);

-    }

-

-    protected void addInstanceProperty(EModelElement metaObject, Property property, Object value) {

-        String uri = property.getContainingType().getURI();

-        EAnnotation eAnnotation = metaObject.getEAnnotation(uri);

-        if (eAnnotation == null) {

-            eAnnotation = EcoreFactory.eINSTANCE.createEAnnotation();

-            eAnnotation.setSource(uri);

-            metaObject.getEAnnotations().add(eAnnotation);

-        }

-        // TODO if (property.isMany()) ... // convert list of values

-        String stringValue = convertToString(property.getType(), value);

-        eAnnotation.getDetails().put(property.getName(), stringValue);

-    }

-

-    

-    public void addChangeListener(DataObject dob, EventListener listener) {

-      // Adapter l = (Adapter)listener;

-      ((Notifier)dob).eAdapters().add(listener);

-    }

-    

-    public void removeChangeListener(DataObject dob, EventListener listener) {

-      ((Notifier)dob).eAdapters().remove(listener);

-    }

-    

-    

-}

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.helper;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.tuscany.sdo.SDOExtendedMetaData;
+import org.apache.tuscany.sdo.SDOFactory;
+import org.apache.tuscany.sdo.SimpleAnyTypeDataObject;
+import org.apache.tuscany.sdo.api.SDOHelper;
+import org.apache.tuscany.sdo.api.XMLStreamHelper;
+import org.apache.tuscany.sdo.api.EventListener;
+import org.apache.tuscany.sdo.impl.ClassImpl;
+import org.apache.tuscany.sdo.impl.DataGraphImpl;
+import org.apache.tuscany.sdo.impl.DynamicDataObjectImpl;
+import org.apache.tuscany.sdo.model.ModelFactory;
+import org.apache.tuscany.sdo.model.impl.ModelFactoryImpl;
+import org.apache.tuscany.sdo.spi.SDOHelperBase;
+import org.apache.tuscany.sdo.util.DataObjectUtil;
+import org.eclipse.emf.common.notify.Adapter;
+import org.eclipse.emf.common.notify.Notifier;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.common.util.UniqueEList;
+import org.eclipse.emf.ecore.EAnnotation;
+import org.eclipse.emf.ecore.EAttribute;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EClassifier;
+import org.eclipse.emf.ecore.EDataType;
+import org.eclipse.emf.ecore.EModelElement;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EPackage;
+import org.eclipse.emf.ecore.EReference;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.ETypedElement;
+import org.eclipse.emf.ecore.EcoreFactory;
+import org.eclipse.emf.ecore.EcorePackage;
+import org.eclipse.emf.ecore.resource.Resource;
+import org.eclipse.emf.ecore.resource.ResourceSet;
+import org.eclipse.emf.ecore.util.EcoreUtil;
+import org.eclipse.emf.ecore.util.ExtendedMetaData;
+import org.eclipse.emf.ecore.util.FeatureMap;
+import org.eclipse.emf.ecore.util.FeatureMapUtil;
+import org.eclipse.emf.ecore.xmi.XMLResource;
+
+import commonj.sdo.DataGraph;
+import commonj.sdo.DataObject;
+import commonj.sdo.Property;
+import commonj.sdo.Sequence;
+import commonj.sdo.Type;
+import commonj.sdo.helper.CopyHelper;
+import commonj.sdo.helper.HelperContext;
+import commonj.sdo.helper.TypeHelper;
+import commonj.sdo.impl.HelperProvider;
+
+public class SDOHelperImpl extends SDOHelperBase implements SDOHelper, SDOHelper.MetaDataBuilder {
+  
+  public DataObject createDataTypeWrapper(Type dataType, Object value) {
+        SimpleAnyTypeDataObject simpleAnyType = SDOFactory.eINSTANCE.createSimpleAnyTypeDataObject();
+        simpleAnyType.setInstanceType((EDataType)dataType);
+        simpleAnyType.setValue(value);
+        return simpleAnyType;
+    }
+
+    public Object createFromString(Type dataType, String literal) {
+        return EcoreUtil.createFromString((EDataType)dataType, literal);
+    }
+
+    public String convertToString(Type dataType, Object value) {
+        return EcoreUtil.convertToString((EDataType)dataType, value);
+    }
+
+    public Type getXSDSDOType(String xsdType) {
+        Type type = null;
+        String name = (String)xsdToSdoMappings.get(xsdType);
+        if (name != null)
+            type = (Type)((ModelFactoryImpl)ModelFactory.INSTANCE).getEClassifier(name);
+        return type;
+    }
+
+    public Sequence getSubstitutionValues(DataObject dataObject, Property head) {
+        final EStructuralFeature group = ExtendedMetaData.INSTANCE.getGroup((EStructuralFeature)head);
+        return null == group ? null : (Sequence)((FeatureMap.Internal)((EObject)dataObject).eGet(group)).getWrapper();
+    }
+
+    public Type getJavaSDOType(Class javaClass) {
+        String name = (String)javaToSdoMappings.get(javaClass);
+        if (name != null) {
+            return (Type)((ModelFactoryImpl)ModelFactory.INSTANCE).getEClassifier(name);
+        }
+        return null;
+    }
+
+    public boolean isRequired(Property property) {
+        return ((EStructuralFeature)property).isRequired();
+    }
+
+    public int getUpperBound(Property property) {
+        return ((EStructuralFeature)property).getUpperBound();
+    }
+
+    public int getLowerBound(Property property) {
+        return ((EStructuralFeature)property).getLowerBound();
+    }
+    
+    public List getEnumerationFacet(Type type) {
+    	List instProps = type.getInstanceProperties();
+    	String propertyName = "enumeration";
+    	Property enumProperty = null;
+    	
+		for (int i = 0; i < instProps.size(); i++)
+		{
+		  Property prop = (Property)instProps.get(i);
+		  if (propertyName.equals(prop.getName()))
+			  enumProperty = prop;
+		}
+
+		return (List)DataObjectUtil.getMetaObjectInstanceProperty((EModelElement)type, enumProperty);
+    }
+    
+    public List getPatternFacet(Type type) {
+    	List instProps = type.getInstanceProperties();
+    	String propertyName = "pattern";
+    	Property patternProperty = null;
+    	
+		for (int i = 0; i < instProps.size(); i++)
+		{
+		  Property prop = (Property)instProps.get(i);
+		  if (propertyName.equals(prop.getName()))
+			  patternProperty = prop;
+		}
+
+		return (List)DataObjectUtil.getMetaObjectInstanceProperty((EModelElement)type, patternProperty);
+    }
+
+    public boolean isMany(Property property, DataObject context) {
+        return FeatureMapUtil.isMany((EObject)context, (EStructuralFeature)property);
+    }
+
+    public DataGraph createDataGraph() {
+        return SDOFactory.eINSTANCE.createDataGraph();
+    }
+
+    public void setRootObject(DataGraph dataGraph, DataObject rootObject) {
+        ((DataGraphImpl)dataGraph).setERootObject((EObject)rootObject);
+    }
+
+    public static DataGraph loadDataGraph(InputStream inputStream, Map options) throws IOException {
+        ResourceSet resourceSet = DataObjectUtil.createResourceSet();
+        Resource resource = resourceSet.createResource(URI.createURI("all.datagraph"));
+        resource.load(inputStream, options);
+        return (DataGraph)resource.getContents().get(0);
+    }
+
+    static final Object LOADING_SCOPE = XMLResource.OPTION_EXTENDED_META_DATA;
+
+    protected void registerLoadingScope(Map options, TypeHelper scope) {
+        Object extendedMetaData = ((TypeHelperImpl)scope).getExtendedMetaData();
+        options.put(LOADING_SCOPE, extendedMetaData);
+    }
+
+    public DataGraph loadDataGraph(InputStream inputStream, Map options, HelperContext scope) throws IOException {
+        if (scope == null) {
+            scope = HelperProvider.getDefaultContext();
+        }
+        TypeHelper th = scope.getTypeHelper();
+        DataGraph result = null;
+		if (th == null || th == TypeHelper.INSTANCE) {
+		    result = loadDataGraph(inputStream, options);
+		} else if (options == null) {
+		    options = new HashMap();
+		    registerLoadingScope(options, th);
+		    result = loadDataGraph(inputStream, options);
+		} else if (options.containsKey(LOADING_SCOPE)) {
+		    Object restore = options.get(LOADING_SCOPE);
+		    registerLoadingScope(options, th);
+		    try {
+		        result = loadDataGraph(inputStream, options);
+		    } finally {
+		        options.put(LOADING_SCOPE, restore);
+		    }
+		} else {
+		    registerLoadingScope(options, th);
+		    try {
+		        result = loadDataGraph(inputStream, options);
+		    } finally {
+		        options.remove(LOADING_SCOPE);
+		    }
+		}
+		return result;
+    }
+
+    public void saveDataGraph(DataGraph dataGraph, OutputStream outputStream, Map options) throws IOException {
+        ((DataGraphImpl)dataGraph).getDataGraphResource().save(outputStream, options);
+    }
+
+    public void registerDataGraphTypes(DataGraph dataGraph, List/* Type */types) {
+        // if (types == null)
+        // types = SDOUtil.getDataGraphTypes(dataGraph);
+
+        Set/* EPackage */packages = new HashSet();
+        for (final Iterator iterator = types.iterator(); iterator.hasNext();) {
+            EClassifier type = (EClassifier)iterator.next();
+            packages.add(type.getEPackage());
+        }
+
+        ResourceSet resourceSet = ((DataGraphImpl)dataGraph).getResourceSet();
+
+        for (Iterator iterator = packages.iterator(); iterator.hasNext();) {
+            EPackage typePackage = (EPackage)iterator.next();
+            Resource resource = typePackage.eResource();
+            if (resource == null) {
+                resource = resourceSet.createResource(URI.createURI(".ecore"));
+                resource.setURI(URI.createURI(typePackage.getNsURI()));
+                resource.getContents().add(typePackage);
+            } else if (resource.getResourceSet() != resourceSet)
+                resourceSet.getResources().add(resource);
+        }
+    }
+
+    public HelperContext createHelperContext() {
+        return new HelperContextImpl(false, null);
+    }
+    
+    public HelperContext createHelperContext(boolean extensibleNamespaces) {
+        return new HelperContextImpl(extensibleNamespaces);
+    }
+    
+    public HelperContext createHelperContext(Map options) {
+        return new HelperContextImpl(false, options);
+    }
+
+    public HelperContext createHelperContext(boolean extensibleNamespaces, Map options) {
+        return new HelperContextImpl(extensibleNamespaces, options);
+    }
+
+
+    public CopyHelper createCrossScopeCopyHelper(HelperContext hc) {
+        return new CrossScopeCopyHelperImpl(hc.getTypeHelper());
+    }
+
+    
+    public XMLStreamHelper createXMLStreamHelper(HelperContext hc) {
+        return ((HelperContextImpl)hc).getXMLStreamHelper();
+    }
+
+    
+    public List getTypes(HelperContext hc, String uri) {
+
+        EPackage ePackage = ((HelperContextImpl)hc).getExtendedMetaData().getPackage(uri);
+        if (ePackage != null) {
+            return new ArrayList(ePackage.getEClassifiers());
+        }
+        return null;
+    }
+
+    public List getOpenContentProperties(DataObject dataObject) {
+        List result = new UniqueEList();
+        ((ClassImpl)dataObject.getType()).addOpenProperties((EObject)dataObject, result);
+        return result;
+    }
+
+    public boolean isDocumentRoot(Type type) {
+        return "".equals(SDOExtendedMetaData.INSTANCE.getName((EClassifier)type));
+    }
+
+    
+    public Type createType(HelperContext hc, String uri, String name, boolean isDataType) {
+        ExtendedMetaData extendedMetaData = ((HelperContextImpl)hc).getExtendedMetaData();
+        if ("".equals(uri))
+            uri = null; // FB
+
+        EPackage ePackage = extendedMetaData.getPackage(uri);
+        if (ePackage == null) {
+            ePackage = EcoreFactory.eINSTANCE.createEPackage();
+            ePackage.setEFactoryInstance(new DynamicDataObjectImpl.FactoryImpl());
+            ePackage.setNsURI(uri);
+            String packagePrefix = uri != null ? URI.createURI(uri).trimFileExtension().lastSegment() : ""; // FB
+            ePackage.setName(packagePrefix);
+            ePackage.setNsPrefix(packagePrefix);
+            extendedMetaData.putPackage(uri, ePackage);
+        }
+
+        EClassifier eClassifier = ePackage.getEClassifier(name);
+        if (eClassifier != null) // already defined?
+        {
+            // throw new IllegalArgumentException();
+            return null;
+        }
+
+        if (name != null) {
+            eClassifier =
+                isDataType ? (EClassifier)SDOFactory.eINSTANCE.createDataType() : (EClassifier)SDOFactory.eINSTANCE
+                    .createClass();
+            eClassifier.setName(name);
+        } else {
+            eClassifier = DataObjectUtil.createDocumentRoot();
+        }
+
+        ePackage.getEClassifiers().add(eClassifier);
+
+        return (Type)eClassifier;
+    }
+
+    public void addBaseType(Type type, Type baseType) {
+        ((EClass)type).getESuperTypes().add(baseType);
+    }
+
+    public void addAliasName(Type type, String aliasName) {
+        throw new UnsupportedOperationException(); // TODO: implement this
+                                                    // method properly
+        // type.getAliasNames().add(aliasName);
+    }
+
+    public void setOpen(Type type, boolean isOpen) {
+        if (isOpen == type.isOpen())
+            return;
+
+        if (isOpen) {
+            EAttribute eAttribute = (EAttribute)SDOFactory.eINSTANCE.createAttribute();
+            ((EClass)type).getEStructuralFeatures().add(eAttribute);
+
+            eAttribute.setName("any");
+            eAttribute.setUnique(false);
+            eAttribute.setUpperBound(ETypedElement.UNBOUNDED_MULTIPLICITY);
+            eAttribute.setEType(EcorePackage.eINSTANCE.getEFeatureMapEntry());
+            ExtendedMetaData.INSTANCE.setFeatureKind(eAttribute, ExtendedMetaData.ELEMENT_WILDCARD_FEATURE);
+            ExtendedMetaData.INSTANCE.setProcessingKind(eAttribute, ExtendedMetaData.LAX_PROCESSING);
+            ExtendedMetaData.INSTANCE.setWildcards(eAttribute, Collections.singletonList("##any"));
+
+            // FB TBD Add an "anyAttribute" EAttribute as well.
+
+            if (ExtendedMetaData.INSTANCE.getMixedFeature((EClass)type) != null) {
+                eAttribute.setDerived(true);
+                eAttribute.setTransient(true);
+                eAttribute.setVolatile(true);
+            }
+        } else {
+            EClass eClass = (EClass)type;
+            EAttribute any = (EAttribute)eClass.getEStructuralFeature("any");
+            eClass.getEStructuralFeatures().remove(any);
+        }
+    }
+
+    public void setSequenced(Type type, boolean isSequenced) {
+        // currently, we require setSequenced to be called first, before
+        // anything else is added to the type.
+        if (type.isDataType() || !type.getProperties().isEmpty()) {
+            if (type.getName() != "DocumentRoot") // document root is a
+                                                    // special case
+                throw new IllegalArgumentException();
+        }
+
+        if (isSequenced) {
+            EClass eClass = (EClass)type;
+            ExtendedMetaData.INSTANCE.setContentKind(eClass, ExtendedMetaData.MIXED_CONTENT);
+            EAttribute mixedFeature = (EAttribute)SDOFactory.eINSTANCE.createAttribute();
+            mixedFeature.setName("mixed");
+            mixedFeature.setUnique(false);
+            mixedFeature.setEType(EcorePackage.eINSTANCE.getEFeatureMapEntry());
+            mixedFeature.setLowerBound(0);
+            mixedFeature.setUpperBound(-1);
+            // eClass.getEStructuralFeatures().add(mixedFeature);
+            ((ClassImpl)eClass).setSequenceFeature(mixedFeature);
+            ExtendedMetaData.INSTANCE.setFeatureKind(mixedFeature, ExtendedMetaData.ELEMENT_WILDCARD_FEATURE);
+            ExtendedMetaData.INSTANCE.setName(mixedFeature, ":mixed");
+        } else {
+            // nothing to do, because of current restriction that setSequence
+            // must be called first.
+        }
+    }
+
+    public void setAbstract(Type type, boolean isAbstract) {
+        ((EClass)type).setAbstract(isAbstract);
+    }
+
+    public void setJavaClassName(Type type, String javaClassName) {
+        ((EClassifier)type).setInstanceClassName(javaClassName);
+    }
+
+    public Property createProperty(Type containingType, String name, Type propertyType) {
+      EStructuralFeature eStructuralFeature = 
+            propertyType.isDataType() ? (EStructuralFeature)SDOFactory.eINSTANCE.createAttribute()
+                : (EStructuralFeature)SDOFactory.eINSTANCE.createReference();
+
+      eStructuralFeature.setName(name);
+      eStructuralFeature.setEType((EClassifier)propertyType);
+      ((EClass)containingType).getEStructuralFeatures().add(eStructuralFeature);
+
+        if ("".equals(ExtendedMetaData.INSTANCE.getName((EClass)containingType))) // DocumentRoot
+                                                                                    // containingType?
+      {
+        ExtendedMetaData.INSTANCE.setNamespace(eStructuralFeature, containingType.getURI());
+        //FB???eStructuralFeature.setUnique(false);
+        //FB???eStructuralFeature.setUpperBound(ETypedElement.UNSPECIFIED_MULTIPLICITY);
+      }
+      
+      if (ExtendedMetaData.INSTANCE.getMixedFeature((EClass)containingType) != null) {
+        eStructuralFeature.setDerived(true);
+        eStructuralFeature.setTransient(true);
+        eStructuralFeature.setVolatile(true);
+        ExtendedMetaData.INSTANCE.setFeatureKind(eStructuralFeature, ExtendedMetaData.ELEMENT_FEATURE);
+      } else {
+          // By default, a SDO property is an XSD element
+          ExtendedMetaData.INSTANCE.setFeatureKind(eStructuralFeature, ExtendedMetaData.ELEMENT_FEATURE);
+      }
+      
+      return (Property)eStructuralFeature;
+    }
+
+  public void setPropertyXMLKind(Property property, boolean isXmlElement) {
+      if (isXmlElement) {
+          ExtendedMetaData.INSTANCE.setFeatureKind((EStructuralFeature)property, ExtendedMetaData.ELEMENT_FEATURE);
+      }
+      else {
+          ExtendedMetaData.INSTANCE.setFeatureKind((EStructuralFeature)property, ExtendedMetaData.ATTRIBUTE_FEATURE);
+      }
+  }
+  
+  
+  public Property createOpenContentProperty(HelperContext hc, String uri, String name, Type type)
+  {
+        ExtendedMetaData extendedMetaData = ((HelperContextImpl)hc).getExtendedMetaData();
+
+        // get/create document root
+        EPackage ePackage = extendedMetaData.getPackage(uri);
+        Type documentRoot = ePackage != null ? (Type)extendedMetaData.getType(ePackage, "") : null;
+        if (documentRoot == null) {
+            documentRoot = createType(hc, uri, null, false);
+        }
+
+        // Determine if property already exists
+        Property newProperty = documentRoot.getProperty(name);
+        if (newProperty == null) {
+            // Create the new property 'under' the document root.....
+            newProperty = createProperty(documentRoot, name, type);
+        } else {
+            // if property already exists, validate the expected type
+            if (!newProperty.getType().equals(type))
+                throw new IllegalArgumentException();
+        }
+        return newProperty;
+    }
+
+
+    public void addAliasName(Property property, String aliasName) {
+        throw new UnsupportedOperationException(); // TODO: implement this
+                                                    // method properly
+        // property.getAliasNames().add(aliasName);
+    }
+
+    public void setMany(Property property, boolean isMany) {
+        ((EStructuralFeature)property).setUpperBound(isMany ? EStructuralFeature.UNBOUNDED_MULTIPLICITY : 1);
+    }
+
+    public void setContainment(Property property, boolean isContainment) {
+        ((EReference)property).setContainment(isContainment);
+    }
+
+    public void setDefault(Property property, String defaultValue) {
+        ((EStructuralFeature)property).setDefaultValueLiteral(defaultValue);
+    }
+
+    public void setReadOnly(Property property, boolean isReadOnly) {
+        ((EStructuralFeature)property).setChangeable(!isReadOnly);
+    }
+
+    public void setOpposite(Property property, Property opposite) {
+        ((EReference)property).setEOpposite((EReference)opposite);
+    }
+
+    public void addTypeInstanceProperty(Type definedType, Property instanceProperty, Object value) {
+        addInstanceProperty((EModelElement)definedType, instanceProperty, value);
+    }
+
+    public void addPropertyInstanceProperty(Property definedProperty, Property instanceProperty, Object value) {
+        addInstanceProperty((EModelElement)definedProperty, instanceProperty, value);
+    }
+
+    protected void addInstanceProperty(EModelElement metaObject, Property property, Object value) {
+        String uri = property.getContainingType().getURI();
+        EAnnotation eAnnotation = metaObject.getEAnnotation(uri);
+        if (eAnnotation == null) {
+            eAnnotation = EcoreFactory.eINSTANCE.createEAnnotation();
+            eAnnotation.setSource(uri);
+            metaObject.getEAnnotations().add(eAnnotation);
+        }
+        // TODO if (property.isMany()) ... // convert list of values
+        String stringValue = convertToString(property.getType(), value);
+        eAnnotation.getDetails().put(property.getName(), stringValue);
+    }
+
+    
+    public void addChangeListener(DataObject dob, EventListener listener) {
+      // Adapter l = (Adapter)listener;
+      ((Notifier)dob).eAdapters().add(listener);
+    }
+    
+    public void removeChangeListener(DataObject dob, EventListener listener) {
+      ((Notifier)dob).eAdapters().remove(listener);
+    }
+    
+    
+}
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/impl/EventImpl.java b/impl/src/main/java/org/apache/tuscany/sdo/impl/EventImpl.java
index a99ccb6..206a3c1 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/impl/EventImpl.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/impl/EventImpl.java
@@ -1,78 +1,78 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.impl;

-

-import org.apache.tuscany.sdo.api.Event;

-import org.eclipse.emf.common.notify.Notification;

-

-import commonj.sdo.Property;

-

-

-public class EventImpl implements Event {

-

-  protected Notification emfEvent;

-  protected Object notifier;

-

-  public EventImpl(Notification notification)

-  {

-    this.emfEvent = notification;

-  }

-  

-  public Object getNotifier()

-  {

-    return notifier == null ? emfEvent.getNotifier() : notifier;

-  }

-

-  public int getEventType()

-  {

-    return emfEvent.getEventType();

-  }

-

-

-  public Property getProperty()

-  {

-    return (Property)emfEvent.getFeature();

-  }

-

-  public Object getOldValue()

-  {

-    return emfEvent.getOldValue();

-  }

-

-  public Object getNewValue()

-  {

-    return emfEvent.getNewValue();

-  }

-

-  public boolean wasSet()

-  {

-    return emfEvent.wasSet();

-  }

-

-  public boolean isTouch()

-  {

-    return emfEvent.isTouch();

-  }

-

-  public int getPosition()

-  {

-    return emfEvent.getPosition();

-  }

-}

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.impl;
+
+import org.apache.tuscany.sdo.api.Event;
+import org.eclipse.emf.common.notify.Notification;
+
+import commonj.sdo.Property;
+
+
+public class EventImpl implements Event {
+
+  protected Notification emfEvent;
+  protected Object notifier;
+
+  public EventImpl(Notification notification)
+  {
+    this.emfEvent = notification;
+  }
+  
+  public Object getNotifier()
+  {
+    return notifier == null ? emfEvent.getNotifier() : notifier;
+  }
+
+  public int getEventType()
+  {
+    return emfEvent.getEventType();
+  }
+
+
+  public Property getProperty()
+  {
+    return (Property)emfEvent.getFeature();
+  }
+
+  public Object getOldValue()
+  {
+    return emfEvent.getOldValue();
+  }
+
+  public Object getNewValue()
+  {
+    return emfEvent.getNewValue();
+  }
+
+  public boolean wasSet()
+  {
+    return emfEvent.wasSet();
+  }
+
+  public boolean isTouch()
+  {
+    return emfEvent.isTouch();
+  }
+
+  public int getPosition()
+  {
+    return emfEvent.getPosition();
+  }
+}
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/impl/ListenerBase.java b/impl/src/main/java/org/apache/tuscany/sdo/impl/ListenerBase.java
index db840b1..986628b 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/impl/ListenerBase.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/impl/ListenerBase.java
@@ -1,33 +1,33 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.impl;

-

-import org.apache.tuscany.sdo.api.Event;

-import org.apache.tuscany.sdo.api.EventListener;

-import org.eclipse.emf.common.notify.Notification;

-import org.eclipse.emf.common.notify.impl.AdapterImpl;

-

-public abstract class ListenerBase extends AdapterImpl implements EventListener  {

-

-  public void notifyChanged(Notification msg) {

-    Event e = new EventImpl(msg);

-    eventNotification(e);

-  }

-}

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.impl;
+
+import org.apache.tuscany.sdo.api.Event;
+import org.apache.tuscany.sdo.api.EventListener;
+import org.eclipse.emf.common.notify.Notification;
+import org.eclipse.emf.common.notify.impl.AdapterImpl;
+
+public abstract class ListenerBase extends AdapterImpl implements EventListener  {
+
+  public void notifyChanged(Notification msg) {
+    Event e = new EventImpl(msg);
+    eventNotification(e);
+  }
+}
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/model/internal/InternalFactory.java b/impl/src/main/java/org/apache/tuscany/sdo/model/internal/InternalFactory.java
index 4776cb9..061d082 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/model/internal/InternalFactory.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/model/internal/InternalFactory.java
@@ -1,52 +1,52 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.model.internal;

-

-import commonj.sdo.helper.HelperContext;

-

-

-/**

- * <!-- begin-user-doc -->

- * The <b>Factory</b> for the model.

- * It provides a create method for each non-abstract class of the model.

- * <!-- end-user-doc -->

- * @generated

- */

-public interface InternalFactory

-{

-

-  /**

-   * The singleton instance of the factory.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  InternalFactory INSTANCE = org.apache.tuscany.sdo.model.internal.impl.InternalFactoryImpl.init();

-

-  /**

-   * Registers the types supported by this Factory within the supplied scope.argument

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @param scope an instance of HelperContext used to manage the scoping of types.

-   * @generated

-   */

-  public void register(HelperContext scope);

-   

-} //InternalFactory

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.model.internal;
+
+import commonj.sdo.helper.HelperContext;
+
+
+/**
+ * <!-- begin-user-doc -->
+ * The <b>Factory</b> for the model.
+ * It provides a create method for each non-abstract class of the model.
+ * <!-- end-user-doc -->
+ * @generated
+ */
+public interface InternalFactory
+{
+
+  /**
+   * The singleton instance of the factory.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  InternalFactory INSTANCE = org.apache.tuscany.sdo.model.internal.impl.InternalFactoryImpl.init();
+
+  /**
+   * Registers the types supported by this Factory within the supplied scope.argument
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @param scope an instance of HelperContext used to manage the scoping of types.
+   * @generated
+   */
+  public void register(HelperContext scope);
+   
+} //InternalFactory
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/model/internal/impl/InternalFactoryImpl.java b/impl/src/main/java/org/apache/tuscany/sdo/model/internal/impl/InternalFactoryImpl.java
index 4517f4a..06d002e 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/model/internal/impl/InternalFactoryImpl.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/model/internal/impl/InternalFactoryImpl.java
@@ -1,296 +1,296 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.model.internal.impl;

-

-import commonj.sdo.helper.HelperContext;

-import org.apache.tuscany.sdo.helper.TypeHelperImpl;

-

-import commonj.sdo.DataObject;

-import commonj.sdo.Property;

-import commonj.sdo.Type;

-

-import org.apache.tuscany.sdo.impl.FactoryBase;

-

-import org.apache.tuscany.sdo.model.internal.*;

-import org.eclipse.emf.ecore.xml.type.XMLTypeFactory;

-

-/**

- * <!-- begin-user-doc -->

- * An implementation of the commonj.sdo.internal model factory.

- * This model is generated from sdoInternal.xsd, in the tuscany-sdo-impl project.

- * Until the SDO code generator supports regen/merge, follow the following steps to regenerate this model:

- *   1. Regenerate the model into a temporary directory:

- *         XSD2JavaGenerator -generateBuiltIn http://www.apache.org/tuscany/commonj.sdo.internal -targetDirectory <temp-dir> -javaPackage org.apache.tuscany.sdo.model.internal <tuscany-sdo-impl-dir>/src/main/resources/xml/sdoInternal.xsd

- *   2. Delete all the createXXXFromString() and convertXXXToString() methods in the newly generated InternalFactoryImpl and

- *      replace them with the ones from this file (resolve any missing imports).

- *   3. Comment out all simple depedencies (SDOUtil.registerStaticTypes calls) in the init() method.

- *   4. Make sure the top of each generated file contains the ASF License.      

- *   5. Move this JavaDoc comment into the newly generated ModelFactoryImpl class.

- * <!-- end-user-doc -->

- * @generated

- */

-public class InternalFactoryImpl extends FactoryBase implements InternalFactory

-{

-

-  /**

-   * The package namespace URI.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public static final String NAMESPACE_URI = "http://www.apache.org/tuscany/commonj.sdo.internal";

-

-  /**

-   * The package namespace name.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public static final String NAMESPACE_PREFIX = "internal";

-

-  /**

-   * The version of the generator pattern used to generate this class.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public static final String PATTERN_VERSION = "1.2";

-  

-  public static final int BASE64_BYTES = 1;	

-  public static final int QNAME = 2;

-  

-  /**

-   * Creates an instance of the factory.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public InternalFactoryImpl()

-  {

-    super(NAMESPACE_URI, NAMESPACE_PREFIX, "org.apache.tuscany.sdo.model.internal");

-  }

-

-  /**

-   * Registers the Factory instance so that it is available within the supplied scope.

-   * @argument scope a HelperContext instance that will make the types supported by this Factory available.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public void register(HelperContext scope) 

-  {

-    if(scope == null) {

-      throw new IllegalArgumentException("Scope can not be null");

-    }

-    

-    //Register dependent packages with provided scope

-    

-    // Initialize this package   

-    TypeHelperImpl th = (TypeHelperImpl)scope.getTypeHelper();

-    th.getExtendedMetaData().putPackage(NAMESPACE_URI, this);

-  }

-  

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public DataObject create(int typeNumber)

-  {

-    switch (typeNumber)

-    {

-      default:

-        return super.create(typeNumber);

-    }

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public Object createFromString(int typeNumber, String initialValue)

-  {

-    switch (typeNumber)

-    {

-      case BASE64_BYTES:

-        return createBase64BytesFromString(initialValue);

-      case QNAME:

-        return createQNameFromString(initialValue);

-      default:

-        throw new IllegalArgumentException("The type number '" + typeNumber + "' is not a valid datatype");

-    }

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public String convertToString(int typeNumber, Object instanceValue)

-  {

-    switch (typeNumber)

-    {

-      case BASE64_BYTES:

-        return convertBase64BytesToString(instanceValue);

-      case QNAME:

-        return convertQNameToString(instanceValue);

-      default:

-        throw new IllegalArgumentException("The type number '" + typeNumber + "' is not a valid datatype");

-    }

-  }

-  

-  // Following creates and initializes SDO metadata for the supported types.		

-  protected Type base64BytesType = null;

-

-  public Type getBase64Bytes()

-  {

-    return base64BytesType;

-  }

-    

-  protected Type qNameType = null;

-

-  public Type getQName()

-  {

-    return qNameType;

-  }

-  

-

-  private static InternalFactoryImpl instance = null; 

-  public static InternalFactoryImpl init()

-  {

-    if (instance != null ) return instance;

-    instance = new InternalFactoryImpl();

-

-    // Initialize dependent packages

-    

-    // Create package meta-data objects

-    instance.createMetaData();

-

-    // Initialize created meta-data

-    instance.initializeMetaData();

-    

-    // Mark meta-data to indicate it can't be changed

-    //theInternalFactoryImpl.freeze(); //FB do we need to freeze / should we freeze ????

-

-    return instance;

-  }

-  

-  private boolean isCreated = false;

-

-  public void createMetaData()

-  {

-    if (isCreated) return;

-    isCreated = true;

-

-    // Create data types

-    base64BytesType = createType(true, BASE64_BYTES );

-    qNameType = createType(true, QNAME );

-  }

-  

-  private boolean isInitialized = false;

-

-  public void initializeMetaData()

-  {

-    if (isInitialized) return;

-    isInitialized = true;

-    Property property = null;

-

-    // Add supertypes to types

-

-    // Initialize types and properties

-    // Initialize data types

-    initializeType(base64BytesType, byte[].class, "Base64Bytes", true, false);

-    setInstanceProperty (base64BytesType, "commonj.sdo/java", "instanceClass", "byte[]");

-

-    initializeType(qNameType, String.class, "QName", true, false);

-    setInstanceProperty (qNameType, "commonj.sdo/java", "instanceClass", "java.lang.String");

-

-    createXSDMetaData();

-  }

-    

-  protected void createXSDMetaData()

-  {

-    super.initXSD();

-    

-    Property property = null;

-    

-

-    addXSDMapping

-      (base64BytesType,

-       new String[] 

-       {

-       "name", "Base64Bytes"

-       });

-

-    addXSDMapping

-      (qNameType,

-       new String[] 

-       {

-       "name", "QName"

-       });

-

-  }

-    

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated NOT

-   */

-  public byte[] createBase64BytesFromString(String initialValue)

-  {

-      return XMLTypeFactory.eINSTANCE.createBase64Binary(initialValue);

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated NOT

-   */

-  public String convertBase64BytesToString(Object instanceValue)

-  {

-      if (instanceValue instanceof byte[]) {

-          return XMLTypeFactory.eINSTANCE.convertBase64Binary((byte[])instanceValue);

-        } else {

-          return XMLTypeFactory.eINSTANCE.convertBase64Binary(instanceValue.toString().getBytes());

-      }

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public String createQNameFromString(String initialValue)

-  {

-    return (String)super.createFromString(QNAME, initialValue);

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public String convertQNameToString(Object instanceValue)

-  {

-    return super.convertToString(QNAME, instanceValue);

-  }

-

-} //InternalFactoryImpl

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.model.internal.impl;
+
+import commonj.sdo.helper.HelperContext;
+import org.apache.tuscany.sdo.helper.TypeHelperImpl;
+
+import commonj.sdo.DataObject;
+import commonj.sdo.Property;
+import commonj.sdo.Type;
+
+import org.apache.tuscany.sdo.impl.FactoryBase;
+
+import org.apache.tuscany.sdo.model.internal.*;
+import org.eclipse.emf.ecore.xml.type.XMLTypeFactory;
+
+/**
+ * <!-- begin-user-doc -->
+ * An implementation of the commonj.sdo.internal model factory.
+ * This model is generated from sdoInternal.xsd, in the tuscany-sdo-impl project.
+ * Until the SDO code generator supports regen/merge, follow the following steps to regenerate this model:
+ *   1. Regenerate the model into a temporary directory:
+ *         XSD2JavaGenerator -generateBuiltIn http://www.apache.org/tuscany/commonj.sdo.internal -targetDirectory <temp-dir> -javaPackage org.apache.tuscany.sdo.model.internal <tuscany-sdo-impl-dir>/src/main/resources/xml/sdoInternal.xsd
+ *   2. Delete all the createXXXFromString() and convertXXXToString() methods in the newly generated InternalFactoryImpl and
+ *      replace them with the ones from this file (resolve any missing imports).
+ *   3. Comment out all simple depedencies (SDOUtil.registerStaticTypes calls) in the init() method.
+ *   4. Make sure the top of each generated file contains the ASF License.      
+ *   5. Move this JavaDoc comment into the newly generated ModelFactoryImpl class.
+ * <!-- end-user-doc -->
+ * @generated
+ */
+public class InternalFactoryImpl extends FactoryBase implements InternalFactory
+{
+
+  /**
+   * The package namespace URI.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public static final String NAMESPACE_URI = "http://www.apache.org/tuscany/commonj.sdo.internal";
+
+  /**
+   * The package namespace name.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public static final String NAMESPACE_PREFIX = "internal";
+
+  /**
+   * The version of the generator pattern used to generate this class.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public static final String PATTERN_VERSION = "1.2";
+  
+  public static final int BASE64_BYTES = 1;	
+  public static final int QNAME = 2;
+  
+  /**
+   * Creates an instance of the factory.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public InternalFactoryImpl()
+  {
+    super(NAMESPACE_URI, NAMESPACE_PREFIX, "org.apache.tuscany.sdo.model.internal");
+  }
+
+  /**
+   * Registers the Factory instance so that it is available within the supplied scope.
+   * @argument scope a HelperContext instance that will make the types supported by this Factory available.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public void register(HelperContext scope) 
+  {
+    if(scope == null) {
+      throw new IllegalArgumentException("Scope can not be null");
+    }
+    
+    //Register dependent packages with provided scope
+    
+    // Initialize this package   
+    TypeHelperImpl th = (TypeHelperImpl)scope.getTypeHelper();
+    th.getExtendedMetaData().putPackage(NAMESPACE_URI, this);
+  }
+  
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public DataObject create(int typeNumber)
+  {
+    switch (typeNumber)
+    {
+      default:
+        return super.create(typeNumber);
+    }
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public Object createFromString(int typeNumber, String initialValue)
+  {
+    switch (typeNumber)
+    {
+      case BASE64_BYTES:
+        return createBase64BytesFromString(initialValue);
+      case QNAME:
+        return createQNameFromString(initialValue);
+      default:
+        throw new IllegalArgumentException("The type number '" + typeNumber + "' is not a valid datatype");
+    }
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public String convertToString(int typeNumber, Object instanceValue)
+  {
+    switch (typeNumber)
+    {
+      case BASE64_BYTES:
+        return convertBase64BytesToString(instanceValue);
+      case QNAME:
+        return convertQNameToString(instanceValue);
+      default:
+        throw new IllegalArgumentException("The type number '" + typeNumber + "' is not a valid datatype");
+    }
+  }
+  
+  // Following creates and initializes SDO metadata for the supported types.		
+  protected Type base64BytesType = null;
+
+  public Type getBase64Bytes()
+  {
+    return base64BytesType;
+  }
+    
+  protected Type qNameType = null;
+
+  public Type getQName()
+  {
+    return qNameType;
+  }
+  
+
+  private static InternalFactoryImpl instance = null; 
+  public static InternalFactoryImpl init()
+  {
+    if (instance != null ) return instance;
+    instance = new InternalFactoryImpl();
+
+    // Initialize dependent packages
+    
+    // Create package meta-data objects
+    instance.createMetaData();
+
+    // Initialize created meta-data
+    instance.initializeMetaData();
+    
+    // Mark meta-data to indicate it can't be changed
+    //theInternalFactoryImpl.freeze(); //FB do we need to freeze / should we freeze ????
+
+    return instance;
+  }
+  
+  private boolean isCreated = false;
+
+  public void createMetaData()
+  {
+    if (isCreated) return;
+    isCreated = true;
+
+    // Create data types
+    base64BytesType = createType(true, BASE64_BYTES );
+    qNameType = createType(true, QNAME );
+  }
+  
+  private boolean isInitialized = false;
+
+  public void initializeMetaData()
+  {
+    if (isInitialized) return;
+    isInitialized = true;
+    Property property = null;
+
+    // Add supertypes to types
+
+    // Initialize types and properties
+    // Initialize data types
+    initializeType(base64BytesType, byte[].class, "Base64Bytes", true, false);
+    setInstanceProperty (base64BytesType, "commonj.sdo/java", "instanceClass", "byte[]");
+
+    initializeType(qNameType, String.class, "QName", true, false);
+    setInstanceProperty (qNameType, "commonj.sdo/java", "instanceClass", "java.lang.String");
+
+    createXSDMetaData();
+  }
+    
+  protected void createXSDMetaData()
+  {
+    super.initXSD();
+    
+    Property property = null;
+    
+
+    addXSDMapping
+      (base64BytesType,
+       new String[] 
+       {
+       "name", "Base64Bytes"
+       });
+
+    addXSDMapping
+      (qNameType,
+       new String[] 
+       {
+       "name", "QName"
+       });
+
+  }
+    
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated NOT
+   */
+  public byte[] createBase64BytesFromString(String initialValue)
+  {
+      return XMLTypeFactory.eINSTANCE.createBase64Binary(initialValue);
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated NOT
+   */
+  public String convertBase64BytesToString(Object instanceValue)
+  {
+      if (instanceValue instanceof byte[]) {
+          return XMLTypeFactory.eINSTANCE.convertBase64Binary((byte[])instanceValue);
+        } else {
+          return XMLTypeFactory.eINSTANCE.convertBase64Binary(instanceValue.toString().getBytes());
+      }
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public String createQNameFromString(String initialValue)
+  {
+    return (String)super.createFromString(QNAME, initialValue);
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public String convertQNameToString(Object instanceValue)
+  {
+    return super.convertToString(QNAME, instanceValue);
+  }
+
+} //InternalFactoryImpl
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/model/xml/XMLFactory.java b/impl/src/main/java/org/apache/tuscany/sdo/model/xml/XMLFactory.java
index 84a60cf..39119a1 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/model/xml/XMLFactory.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/model/xml/XMLFactory.java
@@ -1,61 +1,61 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.model.xml;

-

-import commonj.sdo.helper.HelperContext;

-

-

-/**

- * <!-- begin-user-doc -->

- * The <b>Factory</b> for the model.

- * It provides a create method for each non-abstract class of the model.

- * <!-- end-user-doc -->

- * @generated

- */

-public interface XMLFactory

-{

-

-  /**

-   * The singleton instance of the factory.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  XMLFactory INSTANCE = org.apache.tuscany.sdo.model.xml.impl.XMLFactoryImpl.init();

-

-  /**

-   * Returns a new object of class '<em>Info</em>'.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @return a new object of class '<em>Info</em>'.

-   * @generated

-   */

-  XMLInfo createXMLInfo();

-

-  /**

-   * Registers the types supported by this Factory within the supplied scope.argument

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @param scope an instance of HelperContext used to manage the scoping of types.

-   * @generated

-   */

-  public void register(HelperContext scope);

-   

-} //XMLFactory

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.model.xml;
+
+import commonj.sdo.helper.HelperContext;
+
+
+/**
+ * <!-- begin-user-doc -->
+ * The <b>Factory</b> for the model.
+ * It provides a create method for each non-abstract class of the model.
+ * <!-- end-user-doc -->
+ * @generated
+ */
+public interface XMLFactory
+{
+
+  /**
+   * The singleton instance of the factory.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  XMLFactory INSTANCE = org.apache.tuscany.sdo.model.xml.impl.XMLFactoryImpl.init();
+
+  /**
+   * Returns a new object of class '<em>Info</em>'.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @return a new object of class '<em>Info</em>'.
+   * @generated
+   */
+  XMLInfo createXMLInfo();
+
+  /**
+   * Registers the types supported by this Factory within the supplied scope.argument
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @param scope an instance of HelperContext used to manage the scoping of types.
+   * @generated
+   */
+  public void register(HelperContext scope);
+   
+} //XMLFactory
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/model/xml/XMLInfo.java b/impl/src/main/java/org/apache/tuscany/sdo/model/xml/XMLInfo.java
index 85cad64..6f438bc 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/model/xml/XMLInfo.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/model/xml/XMLInfo.java
@@ -1,92 +1,92 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.model.xml;

-

-import java.io.Serializable;

-

-/**

- * <!-- begin-user-doc -->

- * A representation of the model object '<em><b>Info</b></em>'.

- * <!-- end-user-doc -->

- *

- * <p>

- * The following features are supported:

- * <ul>

- *   <li>{@link org.apache.tuscany.sdo.model.xml.XMLInfo#isXmlElement <em>Xml Element</em>}</li>

- * </ul>

- * </p>

- *

- * @extends Serializable

- * @generated

- */

-public interface XMLInfo extends Serializable

-{

-  /**

-   * Returns the value of the '<em><b>Xml Element</b></em>' attribute.

-   * <!-- begin-user-doc -->

-   * <p>

-   * If the meaning of the '<em>Xml Element</em>' attribute isn't clear,

-   * there really should be more of a description here...

-   * </p>

-   * <!-- end-user-doc -->

-   * @return the value of the '<em>Xml Element</em>' attribute.

-   * @see #isSetXmlElement()

-   * @see #unsetXmlElement()

-   * @see #setXmlElement(boolean)

-   * @generated

-   */

-  boolean isXmlElement();

-

-  /**

-   * Sets the value of the '{@link org.apache.tuscany.sdo.model.xml.XMLInfo#isXmlElement <em>Xml Element</em>}' attribute.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @param value the new value of the '<em>Xml Element</em>' attribute.

-   * @see #isSetXmlElement()

-   * @see #unsetXmlElement()

-   * @see #isXmlElement()

-   * @generated

-   */

-  void setXmlElement(boolean value);

-

-  /**

-   * Unsets the value of the '{@link org.apache.tuscany.sdo.model.xml.XMLInfo#isXmlElement <em>Xml Element</em>}' attribute.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @see #isSetXmlElement()

-   * @see #isXmlElement()

-   * @see #setXmlElement(boolean)

-   * @generated

-   */

-  void unsetXmlElement();

-

-  /**

-   * Returns whether the value of the '{@link org.apache.tuscany.sdo.model.xml.XMLInfo#isXmlElement <em>Xml Element</em>}' attribute is set.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @return whether the value of the '<em>Xml Element</em>' attribute is set.

-   * @see #unsetXmlElement()

-   * @see #isXmlElement()

-   * @see #setXmlElement(boolean)

-   * @generated

-   */

-  boolean isSetXmlElement();

-

-} // XMLInfo

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.model.xml;
+
+import java.io.Serializable;
+
+/**
+ * <!-- begin-user-doc -->
+ * A representation of the model object '<em><b>Info</b></em>'.
+ * <!-- end-user-doc -->
+ *
+ * <p>
+ * The following features are supported:
+ * <ul>
+ *   <li>{@link org.apache.tuscany.sdo.model.xml.XMLInfo#isXmlElement <em>Xml Element</em>}</li>
+ * </ul>
+ * </p>
+ *
+ * @extends Serializable
+ * @generated
+ */
+public interface XMLInfo extends Serializable
+{
+  /**
+   * Returns the value of the '<em><b>Xml Element</b></em>' attribute.
+   * <!-- begin-user-doc -->
+   * <p>
+   * If the meaning of the '<em>Xml Element</em>' attribute isn't clear,
+   * there really should be more of a description here...
+   * </p>
+   * <!-- end-user-doc -->
+   * @return the value of the '<em>Xml Element</em>' attribute.
+   * @see #isSetXmlElement()
+   * @see #unsetXmlElement()
+   * @see #setXmlElement(boolean)
+   * @generated
+   */
+  boolean isXmlElement();
+
+  /**
+   * Sets the value of the '{@link org.apache.tuscany.sdo.model.xml.XMLInfo#isXmlElement <em>Xml Element</em>}' attribute.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @param value the new value of the '<em>Xml Element</em>' attribute.
+   * @see #isSetXmlElement()
+   * @see #unsetXmlElement()
+   * @see #isXmlElement()
+   * @generated
+   */
+  void setXmlElement(boolean value);
+
+  /**
+   * Unsets the value of the '{@link org.apache.tuscany.sdo.model.xml.XMLInfo#isXmlElement <em>Xml Element</em>}' attribute.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @see #isSetXmlElement()
+   * @see #isXmlElement()
+   * @see #setXmlElement(boolean)
+   * @generated
+   */
+  void unsetXmlElement();
+
+  /**
+   * Returns whether the value of the '{@link org.apache.tuscany.sdo.model.xml.XMLInfo#isXmlElement <em>Xml Element</em>}' attribute is set.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @return whether the value of the '<em>Xml Element</em>' attribute is set.
+   * @see #unsetXmlElement()
+   * @see #isXmlElement()
+   * @see #setXmlElement(boolean)
+   * @generated
+   */
+  boolean isSetXmlElement();
+
+} // XMLInfo
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/model/xml/impl/XMLFactoryImpl.java b/impl/src/main/java/org/apache/tuscany/sdo/model/xml/impl/XMLFactoryImpl.java
index 293a7b0..f07d8b7 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/model/xml/impl/XMLFactoryImpl.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/model/xml/impl/XMLFactoryImpl.java
@@ -1,341 +1,341 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.model.xml.impl;

-

-import commonj.sdo.helper.HelperContext;

-import org.apache.tuscany.sdo.helper.TypeHelperImpl;

-

-import commonj.sdo.DataObject;

-import commonj.sdo.Property;

-import commonj.sdo.Type;

-

-import org.apache.tuscany.sdo.impl.FactoryBase;

-

-import org.apache.tuscany.sdo.model.ModelFactory;

-

-import org.apache.tuscany.sdo.model.impl.ModelFactoryImpl;

-

-import org.apache.tuscany.sdo.model.internal.InternalFactory;

-

-import org.apache.tuscany.sdo.model.internal.impl.InternalFactoryImpl;

-

-import org.apache.tuscany.sdo.model.xml.*;

-

-/**

- * <!-- begin-user-doc -->

- * An implementation of the commonj.sdo/xml model factory.

- * This model is generated from sdoXML.xsd, in the sdo-api project.

- * Until the SDO code generator supports name conflicts and regen/merge, follow the following steps to regenerate this model:

- *   1. Regenerate the model into a temporary directory:

- *         XSD2JavaGenerator -generateBuiltIn commonj.sdo/xml -prefix XML -targetDirectory <temp-dir> -javaPackage org.apache.tuscany.sdo.model.xml <sdo-api-dir>/src/main/resources/xml/sdoXML.xsd

- *   2. Make sure the top of each generated file contains the ASF License.      

- *   3. Move this JavaDoc comment into the newly generated XMLFactoryImpl class.

- * <!-- end-user-doc -->

- * @generated

- */

-public class XMLFactoryImpl extends FactoryBase implements XMLFactory

-{

-

-  /**

-   * The package namespace URI.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public static final String NAMESPACE_URI = "commonj.sdo/xml";

-

-  /**

-   * The package namespace name.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public static final String NAMESPACE_PREFIX = "sdoXML";

-

-  /**

-   * The version of the generator pattern used to generate this class.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public static final String PATTERN_VERSION = "1.2";

-  

-  public static final int XML_INFO = 1;

-  

-  /**

-   * Creates an instance of the factory.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public XMLFactoryImpl()

-  {

-    super(NAMESPACE_URI, NAMESPACE_PREFIX, "org.apache.tuscany.sdo.model.xml");

-  }

-

-  /**

-   * Registers the Factory instance so that it is available within the supplied scope.

-   * @argument scope a HelperContext instance that will make the types supported by this Factory available.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public void register(HelperContext scope) 

-  {

-    if(scope == null) {

-      throw new IllegalArgumentException("Scope can not be null");

-    }

-    

-    //Register dependent packages with provided scope

-    ModelFactory.INSTANCE.register(scope);

-    InternalFactory.INSTANCE.register(scope);

-    

-    // Initialize this package   

-    TypeHelperImpl th = (TypeHelperImpl)scope.getTypeHelper();

-    th.getExtendedMetaData().putPackage(NAMESPACE_URI, this);

-  }

-  

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public DataObject create(int typeNumber)

-  {

-    switch (typeNumber)

-    {

-      case XML_INFO: return (DataObject)createXMLInfo();

-      default:

-        return super.create(typeNumber);

-    }

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public XMLInfo createXMLInfo()

-  {

-    XMLInfoImpl xmlInfo = new XMLInfoImpl();

-    return xmlInfo;

-  }

-  

-  // Following creates and initializes SDO metadata for the supported types.			

-  protected Type xmlInfoType = null;

-

-  public Type getXMLInfo()

-  {

-    return xmlInfoType;

-  }

-  

-

-  private static XMLFactoryImpl instance = null; 

-  public static XMLFactoryImpl init()

-  {

-    if (instance != null ) return instance;

-    instance = new XMLFactoryImpl();

-

-    // Initialize dependent packages

-    ModelFactory ModelFactoryInstance = ModelFactory.INSTANCE;

-    InternalFactory InternalFactoryInstance = InternalFactory.INSTANCE;

-    

-    // Create package meta-data objects

-    instance.createMetaData();

-

-    // Initialize created meta-data

-    instance.initializeMetaData();

-    

-    // Mark meta-data to indicate it can't be changed

-    //theXMLFactoryImpl.freeze(); //FB do we need to freeze / should we freeze ????

-

-    return instance;

-  }

-  

-  private boolean isCreated = false;

-

-  public void createMetaData()

-  {

-    if (isCreated) return;

-    isCreated = true;	

-

-    // Create types and their properties

-    xmlInfoType = createType(false, XML_INFO);

-    createProperty(true, xmlInfoType,XMLInfoImpl.INTERNAL_XML_ELEMENT); 

-  }

-  

-  private boolean isInitialized = false;

-

-  public void initializeMetaData()

-  {

-    if (isInitialized) return;

-    isInitialized = true;

-

-    // Obtain other dependent packages

-    ModelFactoryImpl theModelPackageImpl = (ModelFactoryImpl)ModelFactory.INSTANCE;

-    InternalFactoryImpl theInternalPackageImpl = (InternalFactoryImpl)InternalFactory.INSTANCE;

-    Property property = null;

-

-    // Add supertypes to types

-

-    // Initialize types and properties

-    initializeType(xmlInfoType, XMLInfo.class, "XMLInfo", false);

-    property = getLocalProperty(xmlInfoType, 0);

-    initializeProperty(property, theModelPackageImpl.getBoolean(), "xmlElement", null, 0, 1, XMLInfo.class, false, true, false);

-

-    createXSDMetaData(theModelPackageImpl, theInternalPackageImpl);

-  }

-    

-  protected void createXSDMetaData(ModelFactoryImpl theModelPackageImpl, InternalFactoryImpl theInternalPackageImpl)

-  {

-    super.initXSD();

-    

-    Property property = null;

-    

-

-    property = createGlobalProperty

-      ("aliasName",

-      theModelPackageImpl.getString(),

-       new String[]

-       {

-       "kind", "attribute",

-       "name", "aliasName",

-       "namespace", "##targetNamespace"

-       },

-       IS_ATTRIBUTE);

-                

-    property = createGlobalProperty

-      ("dataType",

-      theInternalPackageImpl.getQName(),

-       new String[]

-       {

-       "kind", "attribute",

-       "name", "dataType",

-       "namespace", "##targetNamespace"

-       },

-       IS_ATTRIBUTE);

-                

-    property = createGlobalProperty

-      ("many",

-      theModelPackageImpl.getBoolean(),

-       new String[]

-       {

-       "kind", "attribute",

-       "name", "many",

-       "namespace", "##targetNamespace"

-       },

-       IS_ATTRIBUTE);

-                

-    property = createGlobalProperty

-      ("name",

-      theModelPackageImpl.getString(),

-       new String[]

-       {

-       "kind", "attribute",

-       "name", "name",

-       "namespace", "##targetNamespace"

-       },

-       IS_ATTRIBUTE);

-                

-    property = createGlobalProperty

-      ("oppositeProperty",

-      theModelPackageImpl.getString(),

-       new String[]

-       {

-       "kind", "attribute",

-       "name", "oppositeProperty",

-       "namespace", "##targetNamespace"

-       },

-       IS_ATTRIBUTE);

-                

-    property = createGlobalProperty

-      ("propertyType",

-      theInternalPackageImpl.getQName(),

-       new String[]

-       {

-       "kind", "attribute",

-       "name", "propertyType",

-       "namespace", "##targetNamespace"

-       },

-       IS_ATTRIBUTE);

-                

-    property = createGlobalProperty

-      ("readOnly",

-      theModelPackageImpl.getBoolean(),

-       new String[]

-       {

-       "kind", "attribute",

-       "name", "readOnly",

-       "namespace", "##targetNamespace"

-       },

-       IS_ATTRIBUTE);

-                

-    property = createGlobalProperty

-      ("sequence",

-      theModelPackageImpl.getBoolean(),

-       new String[]

-       {

-       "kind", "attribute",

-       "name", "sequence",

-       "namespace", "##targetNamespace"

-       },

-       IS_ATTRIBUTE);

-                

-    property = createGlobalProperty

-      ("string",

-      theModelPackageImpl.getBoolean(),

-       new String[]

-       {

-       "kind", "attribute",

-       "name", "string",

-       "namespace", "##targetNamespace"

-       },

-       IS_ATTRIBUTE);

-                

-    property = createGlobalProperty

-      ("xmlElement",

-      theModelPackageImpl.getBoolean(),

-       new String[]

-       {

-       "kind", "attribute",

-       "name", "xmlElement",

-       "namespace", "##targetNamespace"

-       },

-       IS_ATTRIBUTE);

-                

-    addXSDMapping

-      (xmlInfoType,

-       new String[] 

-       {

-       "name", "XMLInfo",

-       "kind", "empty"

-       });

-

-    addXSDMapping

-      (getProperty(xmlInfoType, XMLInfoImpl.INTERNAL_XML_ELEMENT),

-       new String[]

-       {

-       "kind", "attribute",

-       "name", "xmlElement"

-       });

-

-  }

-    

-} //XMLFactoryImpl

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.model.xml.impl;
+
+import commonj.sdo.helper.HelperContext;
+import org.apache.tuscany.sdo.helper.TypeHelperImpl;
+
+import commonj.sdo.DataObject;
+import commonj.sdo.Property;
+import commonj.sdo.Type;
+
+import org.apache.tuscany.sdo.impl.FactoryBase;
+
+import org.apache.tuscany.sdo.model.ModelFactory;
+
+import org.apache.tuscany.sdo.model.impl.ModelFactoryImpl;
+
+import org.apache.tuscany.sdo.model.internal.InternalFactory;
+
+import org.apache.tuscany.sdo.model.internal.impl.InternalFactoryImpl;
+
+import org.apache.tuscany.sdo.model.xml.*;
+
+/**
+ * <!-- begin-user-doc -->
+ * An implementation of the commonj.sdo/xml model factory.
+ * This model is generated from sdoXML.xsd, in the sdo-api project.
+ * Until the SDO code generator supports name conflicts and regen/merge, follow the following steps to regenerate this model:
+ *   1. Regenerate the model into a temporary directory:
+ *         XSD2JavaGenerator -generateBuiltIn commonj.sdo/xml -prefix XML -targetDirectory <temp-dir> -javaPackage org.apache.tuscany.sdo.model.xml <sdo-api-dir>/src/main/resources/xml/sdoXML.xsd
+ *   2. Make sure the top of each generated file contains the ASF License.      
+ *   3. Move this JavaDoc comment into the newly generated XMLFactoryImpl class.
+ * <!-- end-user-doc -->
+ * @generated
+ */
+public class XMLFactoryImpl extends FactoryBase implements XMLFactory
+{
+
+  /**
+   * The package namespace URI.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public static final String NAMESPACE_URI = "commonj.sdo/xml";
+
+  /**
+   * The package namespace name.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public static final String NAMESPACE_PREFIX = "sdoXML";
+
+  /**
+   * The version of the generator pattern used to generate this class.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public static final String PATTERN_VERSION = "1.2";
+  
+  public static final int XML_INFO = 1;
+  
+  /**
+   * Creates an instance of the factory.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public XMLFactoryImpl()
+  {
+    super(NAMESPACE_URI, NAMESPACE_PREFIX, "org.apache.tuscany.sdo.model.xml");
+  }
+
+  /**
+   * Registers the Factory instance so that it is available within the supplied scope.
+   * @argument scope a HelperContext instance that will make the types supported by this Factory available.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public void register(HelperContext scope) 
+  {
+    if(scope == null) {
+      throw new IllegalArgumentException("Scope can not be null");
+    }
+    
+    //Register dependent packages with provided scope
+    ModelFactory.INSTANCE.register(scope);
+    InternalFactory.INSTANCE.register(scope);
+    
+    // Initialize this package   
+    TypeHelperImpl th = (TypeHelperImpl)scope.getTypeHelper();
+    th.getExtendedMetaData().putPackage(NAMESPACE_URI, this);
+  }
+  
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public DataObject create(int typeNumber)
+  {
+    switch (typeNumber)
+    {
+      case XML_INFO: return (DataObject)createXMLInfo();
+      default:
+        return super.create(typeNumber);
+    }
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public XMLInfo createXMLInfo()
+  {
+    XMLInfoImpl xmlInfo = new XMLInfoImpl();
+    return xmlInfo;
+  }
+  
+  // Following creates and initializes SDO metadata for the supported types.			
+  protected Type xmlInfoType = null;
+
+  public Type getXMLInfo()
+  {
+    return xmlInfoType;
+  }
+  
+
+  private static XMLFactoryImpl instance = null; 
+  public static XMLFactoryImpl init()
+  {
+    if (instance != null ) return instance;
+    instance = new XMLFactoryImpl();
+
+    // Initialize dependent packages
+    ModelFactory ModelFactoryInstance = ModelFactory.INSTANCE;
+    InternalFactory InternalFactoryInstance = InternalFactory.INSTANCE;
+    
+    // Create package meta-data objects
+    instance.createMetaData();
+
+    // Initialize created meta-data
+    instance.initializeMetaData();
+    
+    // Mark meta-data to indicate it can't be changed
+    //theXMLFactoryImpl.freeze(); //FB do we need to freeze / should we freeze ????
+
+    return instance;
+  }
+  
+  private boolean isCreated = false;
+
+  public void createMetaData()
+  {
+    if (isCreated) return;
+    isCreated = true;	
+
+    // Create types and their properties
+    xmlInfoType = createType(false, XML_INFO);
+    createProperty(true, xmlInfoType,XMLInfoImpl.INTERNAL_XML_ELEMENT); 
+  }
+  
+  private boolean isInitialized = false;
+
+  public void initializeMetaData()
+  {
+    if (isInitialized) return;
+    isInitialized = true;
+
+    // Obtain other dependent packages
+    ModelFactoryImpl theModelPackageImpl = (ModelFactoryImpl)ModelFactory.INSTANCE;
+    InternalFactoryImpl theInternalPackageImpl = (InternalFactoryImpl)InternalFactory.INSTANCE;
+    Property property = null;
+
+    // Add supertypes to types
+
+    // Initialize types and properties
+    initializeType(xmlInfoType, XMLInfo.class, "XMLInfo", false);
+    property = getLocalProperty(xmlInfoType, 0);
+    initializeProperty(property, theModelPackageImpl.getBoolean(), "xmlElement", null, 0, 1, XMLInfo.class, false, true, false);
+
+    createXSDMetaData(theModelPackageImpl, theInternalPackageImpl);
+  }
+    
+  protected void createXSDMetaData(ModelFactoryImpl theModelPackageImpl, InternalFactoryImpl theInternalPackageImpl)
+  {
+    super.initXSD();
+    
+    Property property = null;
+    
+
+    property = createGlobalProperty
+      ("aliasName",
+      theModelPackageImpl.getString(),
+       new String[]
+       {
+       "kind", "attribute",
+       "name", "aliasName",
+       "namespace", "##targetNamespace"
+       },
+       IS_ATTRIBUTE);
+                
+    property = createGlobalProperty
+      ("dataType",
+      theInternalPackageImpl.getQName(),
+       new String[]
+       {
+       "kind", "attribute",
+       "name", "dataType",
+       "namespace", "##targetNamespace"
+       },
+       IS_ATTRIBUTE);
+                
+    property = createGlobalProperty
+      ("many",
+      theModelPackageImpl.getBoolean(),
+       new String[]
+       {
+       "kind", "attribute",
+       "name", "many",
+       "namespace", "##targetNamespace"
+       },
+       IS_ATTRIBUTE);
+                
+    property = createGlobalProperty
+      ("name",
+      theModelPackageImpl.getString(),
+       new String[]
+       {
+       "kind", "attribute",
+       "name", "name",
+       "namespace", "##targetNamespace"
+       },
+       IS_ATTRIBUTE);
+                
+    property = createGlobalProperty
+      ("oppositeProperty",
+      theModelPackageImpl.getString(),
+       new String[]
+       {
+       "kind", "attribute",
+       "name", "oppositeProperty",
+       "namespace", "##targetNamespace"
+       },
+       IS_ATTRIBUTE);
+                
+    property = createGlobalProperty
+      ("propertyType",
+      theInternalPackageImpl.getQName(),
+       new String[]
+       {
+       "kind", "attribute",
+       "name", "propertyType",
+       "namespace", "##targetNamespace"
+       },
+       IS_ATTRIBUTE);
+                
+    property = createGlobalProperty
+      ("readOnly",
+      theModelPackageImpl.getBoolean(),
+       new String[]
+       {
+       "kind", "attribute",
+       "name", "readOnly",
+       "namespace", "##targetNamespace"
+       },
+       IS_ATTRIBUTE);
+                
+    property = createGlobalProperty
+      ("sequence",
+      theModelPackageImpl.getBoolean(),
+       new String[]
+       {
+       "kind", "attribute",
+       "name", "sequence",
+       "namespace", "##targetNamespace"
+       },
+       IS_ATTRIBUTE);
+                
+    property = createGlobalProperty
+      ("string",
+      theModelPackageImpl.getBoolean(),
+       new String[]
+       {
+       "kind", "attribute",
+       "name", "string",
+       "namespace", "##targetNamespace"
+       },
+       IS_ATTRIBUTE);
+                
+    property = createGlobalProperty
+      ("xmlElement",
+      theModelPackageImpl.getBoolean(),
+       new String[]
+       {
+       "kind", "attribute",
+       "name", "xmlElement",
+       "namespace", "##targetNamespace"
+       },
+       IS_ATTRIBUTE);
+                
+    addXSDMapping
+      (xmlInfoType,
+       new String[] 
+       {
+       "name", "XMLInfo",
+       "kind", "empty"
+       });
+
+    addXSDMapping
+      (getProperty(xmlInfoType, XMLInfoImpl.INTERNAL_XML_ELEMENT),
+       new String[]
+       {
+       "kind", "attribute",
+       "name", "xmlElement"
+       });
+
+  }
+    
+} //XMLFactoryImpl
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/model/xml/impl/XMLInfoImpl.java b/impl/src/main/java/org/apache/tuscany/sdo/model/xml/impl/XMLInfoImpl.java
index a0906e3..83d8a67 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/model/xml/impl/XMLInfoImpl.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/model/xml/impl/XMLInfoImpl.java
@@ -1,256 +1,256 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.model.xml.impl;

-

-import commonj.sdo.Type;

-

-import org.apache.tuscany.sdo.impl.DataObjectBase;

-

-import org.apache.tuscany.sdo.model.xml.XMLFactory;

-import org.apache.tuscany.sdo.model.xml.XMLInfo;

-

-/**

- * <!-- begin-user-doc -->

- * An implementation of the model object '<em><b>Info</b></em>'.

- * <!-- end-user-doc -->

- * <p>

- * The following features are implemented:

- * <ul>

- *   <li>{@link org.apache.tuscany.sdo.model.xml.impl.XMLInfoImpl#isXmlElement <em>Xml Element</em>}</li>

- * </ul>

- * </p>

- *

- * @generated

- */

-public class XMLInfoImpl extends DataObjectBase implements XMLInfo

-{

-

-  public final static int XML_ELEMENT = 0;

-

-  public final static int SDO_PROPERTY_COUNT = 1;

-

-  public final static int EXTENDED_PROPERTY_COUNT = 0;

-

-

-  /**

-   * The internal feature id for the '<em><b>Xml Element</b></em>' attribute.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   * @ordered

-   */ 

-  public final static int INTERNAL_XML_ELEMENT = 0;

-

-  /**

-   * The number of properties for this type.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   * @ordered

-   */

-  public final static int INTERNAL_PROPERTY_COUNT = 1;

-

-  protected int internalConvertIndex(int internalIndex)

-  {

-    switch (internalIndex)

-    {

-      case INTERNAL_XML_ELEMENT: return XML_ELEMENT;

-    }

-    return super.internalConvertIndex(internalIndex);

-  }

-

-

-  /**

-   * The default value of the '{@link #isXmlElement() <em>Xml Element</em>}' attribute.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @see #isXmlElement()

-   * @generated

-   * @ordered

-   */

-  protected static final boolean XML_ELEMENT_DEFAULT_ = false;

-

-  /**

-   * The cached value of the '{@link #isXmlElement() <em>Xml Element</em>}' attribute.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @see #isXmlElement()

-   * @generated

-   * @ordered

-   */

-  protected boolean xmlElement = XML_ELEMENT_DEFAULT_;

-

-  /**

-   * This is true if the Xml Element attribute has been set.

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   * @ordered

-   */

-  protected boolean xmlElement_set_ = false;

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public XMLInfoImpl()

-  {

-    super();

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public Type getStaticType()

-  {

-    return ((XMLFactoryImpl)XMLFactory.INSTANCE).getXMLInfo();

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public boolean isXmlElement()

-  {

-    return xmlElement;

-  }

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public void setXmlElement(boolean newXmlElement)

-  {

-    boolean oldXmlElement = xmlElement;

-    xmlElement = newXmlElement;

-    boolean oldXmlElement_set_ = xmlElement_set_;

-    xmlElement_set_ = true;

-    if (isNotifying())

-      notify(ChangeKind.SET, INTERNAL_XML_ELEMENT, oldXmlElement, xmlElement, !oldXmlElement_set_);

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public void unsetXmlElement()

-  {

-    boolean oldXmlElement = xmlElement;

-    boolean oldXmlElement_set_ = xmlElement_set_;

-    xmlElement = XML_ELEMENT_DEFAULT_;

-    xmlElement_set_ = false;

-    if (isNotifying())

-      notify(ChangeKind.UNSET, INTERNAL_XML_ELEMENT, oldXmlElement, XML_ELEMENT_DEFAULT_, oldXmlElement_set_);

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public boolean isSetXmlElement()

-  {

-    return xmlElement_set_;

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public Object get(int propertyIndex, boolean resolve)

-  {

-    switch (propertyIndex)

-    {

-      case XML_ELEMENT:

-        return isXmlElement() ? Boolean.TRUE : Boolean.FALSE;

-    }

-    return super.get(propertyIndex, resolve);

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public void set(int propertyIndex, Object newValue)

-  {

-    switch (propertyIndex)

-    {

-      case XML_ELEMENT:

-        setXmlElement(((Boolean)newValue).booleanValue());

-        return;

-    }

-    super.set(propertyIndex, newValue);

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public void unset(int propertyIndex)

-  {

-    switch (propertyIndex)

-    {

-      case XML_ELEMENT:

-        unsetXmlElement();

-        return;

-    }

-    super.unset(propertyIndex);

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public boolean isSet(int propertyIndex)

-  {

-    switch (propertyIndex)

-    {

-      case XML_ELEMENT:

-        return isSetXmlElement();

-    }

-    return super.isSet(propertyIndex);

-  }

-

-  /**

-   * <!-- begin-user-doc -->

-   * <!-- end-user-doc -->

-   * @generated

-   */

-  public String toString()

-  {

-    if (isProxy(this)) return super.toString();

-

-    StringBuffer result = new StringBuffer(super.toString());

-    result.append(" (xmlElement: ");

-    if (xmlElement_set_) result.append(xmlElement); else result.append("<unset>");

-    result.append(')');

-    return result.toString();

-  }

-

-} //XMLInfoImpl

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.model.xml.impl;
+
+import commonj.sdo.Type;
+
+import org.apache.tuscany.sdo.impl.DataObjectBase;
+
+import org.apache.tuscany.sdo.model.xml.XMLFactory;
+import org.apache.tuscany.sdo.model.xml.XMLInfo;
+
+/**
+ * <!-- begin-user-doc -->
+ * An implementation of the model object '<em><b>Info</b></em>'.
+ * <!-- end-user-doc -->
+ * <p>
+ * The following features are implemented:
+ * <ul>
+ *   <li>{@link org.apache.tuscany.sdo.model.xml.impl.XMLInfoImpl#isXmlElement <em>Xml Element</em>}</li>
+ * </ul>
+ * </p>
+ *
+ * @generated
+ */
+public class XMLInfoImpl extends DataObjectBase implements XMLInfo
+{
+
+  public final static int XML_ELEMENT = 0;
+
+  public final static int SDO_PROPERTY_COUNT = 1;
+
+  public final static int EXTENDED_PROPERTY_COUNT = 0;
+
+
+  /**
+   * The internal feature id for the '<em><b>Xml Element</b></em>' attribute.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   * @ordered
+   */ 
+  public final static int INTERNAL_XML_ELEMENT = 0;
+
+  /**
+   * The number of properties for this type.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   * @ordered
+   */
+  public final static int INTERNAL_PROPERTY_COUNT = 1;
+
+  protected int internalConvertIndex(int internalIndex)
+  {
+    switch (internalIndex)
+    {
+      case INTERNAL_XML_ELEMENT: return XML_ELEMENT;
+    }
+    return super.internalConvertIndex(internalIndex);
+  }
+
+
+  /**
+   * The default value of the '{@link #isXmlElement() <em>Xml Element</em>}' attribute.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @see #isXmlElement()
+   * @generated
+   * @ordered
+   */
+  protected static final boolean XML_ELEMENT_DEFAULT_ = false;
+
+  /**
+   * The cached value of the '{@link #isXmlElement() <em>Xml Element</em>}' attribute.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @see #isXmlElement()
+   * @generated
+   * @ordered
+   */
+  protected boolean xmlElement = XML_ELEMENT_DEFAULT_;
+
+  /**
+   * This is true if the Xml Element attribute has been set.
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   * @ordered
+   */
+  protected boolean xmlElement_set_ = false;
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public XMLInfoImpl()
+  {
+    super();
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public Type getStaticType()
+  {
+    return ((XMLFactoryImpl)XMLFactory.INSTANCE).getXMLInfo();
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public boolean isXmlElement()
+  {
+    return xmlElement;
+  }
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public void setXmlElement(boolean newXmlElement)
+  {
+    boolean oldXmlElement = xmlElement;
+    xmlElement = newXmlElement;
+    boolean oldXmlElement_set_ = xmlElement_set_;
+    xmlElement_set_ = true;
+    if (isNotifying())
+      notify(ChangeKind.SET, INTERNAL_XML_ELEMENT, oldXmlElement, xmlElement, !oldXmlElement_set_);
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public void unsetXmlElement()
+  {
+    boolean oldXmlElement = xmlElement;
+    boolean oldXmlElement_set_ = xmlElement_set_;
+    xmlElement = XML_ELEMENT_DEFAULT_;
+    xmlElement_set_ = false;
+    if (isNotifying())
+      notify(ChangeKind.UNSET, INTERNAL_XML_ELEMENT, oldXmlElement, XML_ELEMENT_DEFAULT_, oldXmlElement_set_);
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public boolean isSetXmlElement()
+  {
+    return xmlElement_set_;
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public Object get(int propertyIndex, boolean resolve)
+  {
+    switch (propertyIndex)
+    {
+      case XML_ELEMENT:
+        return isXmlElement() ? Boolean.TRUE : Boolean.FALSE;
+    }
+    return super.get(propertyIndex, resolve);
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public void set(int propertyIndex, Object newValue)
+  {
+    switch (propertyIndex)
+    {
+      case XML_ELEMENT:
+        setXmlElement(((Boolean)newValue).booleanValue());
+        return;
+    }
+    super.set(propertyIndex, newValue);
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public void unset(int propertyIndex)
+  {
+    switch (propertyIndex)
+    {
+      case XML_ELEMENT:
+        unsetXmlElement();
+        return;
+    }
+    super.unset(propertyIndex);
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public boolean isSet(int propertyIndex)
+  {
+    switch (propertyIndex)
+    {
+      case XML_ELEMENT:
+        return isSetXmlElement();
+    }
+    return super.isSet(propertyIndex);
+  }
+
+  /**
+   * <!-- begin-user-doc -->
+   * <!-- end-user-doc -->
+   * @generated
+   */
+  public String toString()
+  {
+    if (isProxy(this)) return super.toString();
+
+    StringBuffer result = new StringBuffer(super.toString());
+    result.append(" (xmlElement: ");
+    if (xmlElement_set_) result.append(xmlElement); else result.append("<unset>");
+    result.append(')');
+    return result.toString();
+  }
+
+} //XMLInfoImpl
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/util/StreamDeserializer.java b/impl/src/main/java/org/apache/tuscany/sdo/util/StreamDeserializer.java
index 5d7bee9..9e1492c 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/util/StreamDeserializer.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/util/StreamDeserializer.java
@@ -1,92 +1,92 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.util;

-

-import java.util.Comparator;

-

-import javax.xml.XMLConstants;

-import javax.xml.namespace.NamespaceContext;

-import javax.xml.stream.XMLStreamConstants;

-import javax.xml.stream.XMLStreamReader;

-

-import org.apache.tuscany.sdo.util.resource.RecordedEventXMLStreamReader;

-import org.eclipse.emf.ecore.EDataType;

-import org.eclipse.emf.ecore.util.EcoreUtil;

-import org.eclipse.emf.ecore.util.ExtendedMetaData;

-import org.eclipse.emf.ecore.xmi.XMLResource;

-import org.eclipse.emf.ecore.xml.type.internal.QName;

-

-/**

- * StAX Deserializer. The instance isn't thread-safe, however it's safe to use the instance any times on the same thread.

- */

-public class StreamDeserializer implements XMLStreamConstants {

-    protected XMLStreamReader reader;

-

-    protected final XMLStreamReader play(RecordedEventXMLStreamReader.Tag tag) {

-        return tag.play(reader);

-    }

-

-    protected String nameSpace, name;

-

-    protected final boolean typedXSI() {

-        name = reader.getAttributeValue(ExtendedMetaData.XSI_URI, XMLResource.TYPE);

-        if (name == null)

-            return false;

-        int index = name.indexOf(':');

-        if (index == -1)

-            nameSpace = reader.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX); // may be XMLConstants.NULL_NS_URI

-        else {

-            nameSpace = reader.getNamespaceURI(name.substring(0, index));

-            name = name.substring(++index);

-        }

-        return true;

-    }

-

-    static protected Object value(Object type, String literal, NamespaceContext nameSpaces) {

-        Object value = EcoreUtil.createFromString((EDataType) type, literal);

-        if (!(value instanceof QName))

-            return value;

-        QName qName = (QName) value;

-        qName.setNamespaceURI(nameSpaces.getNamespaceURI(qName.getPrefix()));

-        return value;

-    }

-

-    static public class Attribute {

-        public String name, value;

-    }

-

-    static public final class QualifiedAttribute extends Attribute {

-        public String nameSpace;

-    }

-

-    static protected final Comparator EQUAL_NULL = new Comparator() {

-        public int compare(Object v, Object NULL) {

-            return v == null || v.equals(null) ? 0 : 1;

-        }

-    }, EQUAL = new Comparator() {

-        public int compare(Object v, Object value) {

-            return value.equals(v) ? 0 : -1;

-        }

-    }, SAME = new Comparator() {

-        public int compare(Object v, Object value) {

-            return value == v ? 0 : -1;

-        }

-    };

-}

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.util;
+
+import java.util.Comparator;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamReader;
+
+import org.apache.tuscany.sdo.util.resource.RecordedEventXMLStreamReader;
+import org.eclipse.emf.ecore.EDataType;
+import org.eclipse.emf.ecore.util.EcoreUtil;
+import org.eclipse.emf.ecore.util.ExtendedMetaData;
+import org.eclipse.emf.ecore.xmi.XMLResource;
+import org.eclipse.emf.ecore.xml.type.internal.QName;
+
+/**
+ * StAX Deserializer. The instance isn't thread-safe, however it's safe to use the instance any times on the same thread.
+ */
+public class StreamDeserializer implements XMLStreamConstants {
+    protected XMLStreamReader reader;
+
+    protected final XMLStreamReader play(RecordedEventXMLStreamReader.Tag tag) {
+        return tag.play(reader);
+    }
+
+    protected String nameSpace, name;
+
+    protected final boolean typedXSI() {
+        name = reader.getAttributeValue(ExtendedMetaData.XSI_URI, XMLResource.TYPE);
+        if (name == null)
+            return false;
+        int index = name.indexOf(':');
+        if (index == -1)
+            nameSpace = reader.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX); // may be XMLConstants.NULL_NS_URI
+        else {
+            nameSpace = reader.getNamespaceURI(name.substring(0, index));
+            name = name.substring(++index);
+        }
+        return true;
+    }
+
+    static protected Object value(Object type, String literal, NamespaceContext nameSpaces) {
+        Object value = EcoreUtil.createFromString((EDataType) type, literal);
+        if (!(value instanceof QName))
+            return value;
+        QName qName = (QName) value;
+        qName.setNamespaceURI(nameSpaces.getNamespaceURI(qName.getPrefix()));
+        return value;
+    }
+
+    static public class Attribute {
+        public String name, value;
+    }
+
+    static public final class QualifiedAttribute extends Attribute {
+        public String nameSpace;
+    }
+
+    static protected final Comparator EQUAL_NULL = new Comparator() {
+        public int compare(Object v, Object NULL) {
+            return v == null || v.equals(null) ? 0 : 1;
+        }
+    }, EQUAL = new Comparator() {
+        public int compare(Object v, Object value) {
+            return value.equals(v) ? 0 : -1;
+        }
+    }, SAME = new Comparator() {
+        public int compare(Object v, Object value) {
+            return value == v ? 0 : -1;
+        }
+    };
+}
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/util/VirtualSequence.java b/impl/src/main/java/org/apache/tuscany/sdo/util/VirtualSequence.java
index 2f86fa9..a5982ce 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/util/VirtualSequence.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/util/VirtualSequence.java
@@ -1,780 +1,780 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.util;

-

-import java.util.Iterator;

-import java.util.List;

-

-import org.apache.tuscany.sdo.impl.ClassImpl;

-import org.eclipse.emf.common.util.EList;

-import org.eclipse.emf.ecore.EClass;

-import org.eclipse.emf.ecore.EStructuralFeature;

-import org.eclipse.emf.ecore.util.FeatureMapUtil;

-

-import commonj.sdo.DataObject;

-import commonj.sdo.Property;

-import commonj.sdo.Sequence;

-

-/**

- *  SDO Sequance implementation which delegates to a Collection of DataObject properties.

- */

-public class VirtualSequence implements Sequence

-{

-  private final DataObject dataObject;

-  protected final List delegateProperties; // size > 1

-

-  public VirtualSequence(DataObject object)

-  {

-    dataObject = object;

-    delegateProperties = ((ClassImpl)dataObject.getType()).getVirtualSequenceProperties();

-  }

-  

-  static protected boolean isSequenceProperty(Object property)

-  {

-    return FeatureMapUtil.isFeatureMap((EStructuralFeature)property);

-  }

-  

-  public int size()

-  {

-    int size = 0;

-    for (Iterator iterator = delegateProperties.iterator() ; iterator.hasNext() ;)

-    {

-      Property property = (Property)iterator.next();

-      if (dataObject.isSet(property))

-        if (isSequenceProperty(property))

-          size += ((Sequence)dataObject.get(property)).size();

-        else if (property.isMany())

-          size += dataObject.getList(property).size();

-        else

-          ++size;

-    }

-    return size;

-  }

-

-  public Property getProperty(int index)

-  {

-    for (Iterator iterator = delegateProperties.iterator() ; iterator.hasNext() ;)

-    {

-      Property property = (Property)iterator.next();

-      if (dataObject.isSet(property))

-        if (isSequenceProperty(property))

-        {

-          Sequence sequence = (Sequence)dataObject.get(property);

-          int size = sequence.size();

-          if (index < size)

-            return sequence.getProperty(index);

-          index -= size;

-        }

-        else if (property.isMany())

-        {

-          int size = dataObject.getList(property).size();

-          if (index < size)

-            return property;

-          index -= size;

-        }

-        else if (index == 0)

-          return property;

-        else

-          --index;

-    }

-    throw new IndexOutOfBoundsException();

-  }

-

-  public Object getValue(int index)

-  {

-    for (Iterator iterator = delegateProperties.iterator() ; iterator.hasNext() ;)

-    {

-      Property property = (Property)iterator.next();

-      if (dataObject.isSet(property))

-        if (isSequenceProperty(property))

-        {

-          Sequence sequence = (Sequence)dataObject.get(property);

-          int size = sequence.size();

-          if (index < size)

-            return sequence.getValue(index);

-          index -= size;

-        }

-        else if (property.isMany())

-        {

-          List values = dataObject.getList(property);

-          int size = values.size();

-          if (index < size)

-            return values.get(index);

-          index -= size;

-        }

-        else if (index == 0)

-          return dataObject.get(property);

-        else

-          --index;

-    }

-    throw new IndexOutOfBoundsException();

-  }

-

-  public Object setValue(int index, Object value)

-  {

-    for (Iterator iterator = delegateProperties.iterator() ; iterator.hasNext() ;)

-    {

-      Property property = (Property)iterator.next();

-      if (dataObject.isSet(property))

-        if (isSequenceProperty(property))

-        {

-          Sequence sequence = (Sequence)dataObject.get(property);

-          int size = sequence.size();

-          if (index < size)

-            return sequence.setValue(index, value);

-          index -= size;

-        }

-        else if (property.isMany())

-        {

-          List values = dataObject.getList(property);

-          int size = values.size();

-          if (index < size)

-            return values.set(index, value);

-          index -= size;

-        }

-        else if (index == 0)

-        {

-          Object old = dataObject.get(property);  

-          dataObject.set(property, value);

-          return old;

-        }

-        else

-          --index;

-    }

-    throw new IndexOutOfBoundsException();

-  }

-  

-  boolean validate(EStructuralFeature feature, Object property)

-  {

-    return FeatureMapUtil.getValidator((EClass)dataObject.getType(), feature).isValid((EStructuralFeature)property);

-  }

-

-  boolean append(Property delegateProperty, Property property, Object value)

-  {

-    return ((Sequence)dataObject.get(delegateProperty)).add(property, value);

-  }

-  

-  boolean append(Property property, Object value)

-  {

-    return dataObject.getList(property).add(value);

-  }

-  

-  boolean set(Property property, Object value)

-  {

-    if (property.isMany())

-      return append(property, value);

-    dataObject.set(property, value);

-    return true;

-  }

-  

-  public final boolean add(Property p, Object value)

-  {

-    Property property;

-    int size = delegateProperties.size(), index = size;

-    do

-    {

-      property = (Property)delegateProperties.get(--index);

-      if (!dataObject.isSet(property))

-        continue;

-      EStructuralFeature feature = (EStructuralFeature)property;

-      if (FeatureMapUtil.isFeatureMap(feature))

-      {

-        if (validate(feature, p))

-          return append(property, p, value);

-      }

-      else if (property == p && property.isMany())

-        return append(property, value);

-      if (size == ++index)

-        return false;

-      property = (Property)delegateProperties.get(index);

-      break;

-    }

-    while (index != 0);

-    for (;;)

-    {

-      EStructuralFeature feature = (EStructuralFeature)property;

-      if (FeatureMapUtil.isFeatureMap(feature))

-      {

-        if (validate(feature, p))

-          return append(property, p, value);

-      }

-      else if (property == p)

-        return set(p, value);

-      if (size == ++index)

-        return false;

-      property = (Property)delegateProperties.get(index);

-    }

-  }

-

-  protected final Property property(String name)

-  {

-    return dataObject.getType().getProperty(name);

-  }

-

-  public boolean add(String propertyName, Object value)

-  {

-    return add(property(propertyName), value);

-  }

-

-  protected final Property property(int index)

-  {

-    return (Property)dataObject.getType().getProperties().get(index);

-  }

-

-  public boolean add(int propertyIndex, Object value)

-  {

-    return add(property(propertyIndex), value);

-  }

-  

-  void insert(Property property, Property p, Object value)

-  {

-    ((Sequence)dataObject.get(property)).add(0, p, value);

-  }

-  

-  void insert(Property property, Object value)

-  {

-    dataObject.getList(property).add(0, value);

-  }

-  

-  protected final int insert(Iterator iterator, Property p, Object value)

-  {

-    while (iterator.hasNext())

-    {

-      Property property = (Property)iterator.next();

-      EStructuralFeature feature = (EStructuralFeature)property;

-      if (dataObject.isSet(property))

-      {

-        if (FeatureMapUtil.isFeatureMap(feature))

-        {

-          if (!validate(feature, p))

-            return 2;

-          insert(property, p, value);

-          return 0;

-        }

-        if (property != p || !property.isMany())

-          return 2;

-        insert(property, value);

-        return 0;

-      }

-      if (FeatureMapUtil.isFeatureMap(feature))

-      {

-        if (validate(feature, p))

-        {

-          append(property, p, value);

-          return 0;

-        }

-      }

-      else if (property == p)

-      {

-        set(property, value);

-        return 0;

-      }

-    } // iterator.hasNext()

-    return 1;

-  }

-  

-  public final void add(int index, Property p, Object value)

-  {

-    Iterator iterator = delegateProperties.iterator();

-    if (index == 0)

-      switch (insert(iterator, p, value))

-      {

-        case 0:

-          return;

-        case 1:  

-          throw new IndexOutOfBoundsException();

-        default: // 2  

-          throw new IllegalArgumentException();

-      }

-    while (iterator.hasNext())

-    {

-      Property property = (Property)iterator.next();

-      if (dataObject.isSet(property))

-        if (isSequenceProperty(property))

-        {

-          Sequence sequence = (Sequence)dataObject.get(property);

-          int size = sequence.size();

-          if (index < size)

-          {

-            sequence.add(index, p, value);

-            return;

-          }

-          index -= size;

-          if (index != 0)

-            continue;

-          if (insert(iterator, p, value) != 0)

-            /*assert */sequence.add(p, value);

-          return;

-        } // sequence(property)

-        else if (property.isMany())

-        {

-          List values = dataObject.getList(property);

-          int size = values.size();

-          if (index < size)

-          {

-            values.add(index, value);

-            return;

-          }

-          index -= size;

-          if (index == 0 && property == p)

-          {

-            values.add(value);

-            return;

-          }

-        }

-        else if (index == 0)

-          throw new IllegalArgumentException();

-        else

-          --index;

-    }

-    throw new IndexOutOfBoundsException();

-  }

-

-  public void add(int index, String propertyName, Object value)

-  {

-    add(index, property(propertyName), value);

-  }

-

-  public void add(int index, int propertyIndex, Object value)

-  {

-    add(index, property(propertyIndex), value);

-  }

-

-  public final void addText(String text)

-  {

-    throw new IllegalArgumentException();

-  }

-

-  /**

-   * @deprecated

-   */

-  public void add(String text)

-  {

-    addText(text);

-  }

-

-  public final void addText(int index, String text)

-  {

-    throw new IllegalArgumentException();

-  }

-

-  /**

-   * @deprecated

-   */

-  public void add(int index, String text)

-  {

-    addText(index, text);

-  }

-

-  public void remove(int index)

-  {

-    for (Iterator iterator = delegateProperties.iterator() ; iterator.hasNext() ;)

-    {

-      Property property = (Property)iterator.next();

-      if (dataObject.isSet(property))

-        if (isSequenceProperty(property))

-        {

-          Sequence sequence = (Sequence)dataObject.get(property);

-          int size = sequence.size();

-          if (index < size)

-          {

-            sequence.remove(index);

-            return;

-          }

-          index -= size;

-        }

-        else if (property.isMany())

-        {

-          List values = dataObject.getList(property);

-          int size = values.size();

-          if (index < size)

-          {

-            values.remove(index);

-            return;

-          }

-          index -= size;

-        }

-        else if (index == 0)

-        {

-          dataObject.unset(property);

-          return;

-        }

-        else

-          --index;

-    }

-    throw new IndexOutOfBoundsException();

-  }

-

-  static private Object remove(Sequence sequence, int index)

-  {

-    Object value = sequence.getValue(index);

-    sequence.remove(index);

-    return value;

-  }

-  

-  static void move(Sequence fromSequence, int fromIndex, Sequence toSequence, int toIndex, Property property)

-  {

-    toSequence.add(toIndex, property, remove(fromSequence, fromIndex)); // removes containment

-  }

-  

-  static protected void move(Sequence fromSequence, int fromIndex, Sequence toSequence, int toIndex)

-  {

-    move(fromSequence, fromIndex, toSequence, toIndex, fromSequence.getProperty(fromIndex));

-  }

-  

-  static protected void add(Object value,List list,int index, int size)

-  {

-    if (++index == size)

-      /*assert */list.add(value);

-    else

-      list.add(index, value); // removes containment

-  }

-  

-  static protected void add(Property property, Object value, Sequence toSequence, int toIndex, int size)

-  {

-    if (++toIndex == size)

-      toSequence.add(property, value); // removes containment

-    else

-      toSequence.add(toIndex, property, value); // removes containment

-  }

-  

-  public void move(int toIndex, int fromIndex)

-  {

-    for (Iterator iterator = delegateProperties.iterator(); iterator.hasNext() ;)

-    {

-      Property property = (Property)iterator.next();

-      if (dataObject.isSet(property))

-        if (isSequenceProperty(property))

-        {

-          Sequence sequence = (Sequence)dataObject.get(property);

-          int size = sequence.size();

-          if (toIndex < size)

-          {

-            if (fromIndex < size)

-            {

-              sequence.move(toIndex, fromIndex);

-              return;

-            }

-            while (iterator.hasNext())

-            {

-              property = (Property)iterator.next();

-              if (!dataObject.isSet(property))

-                continue;

-              fromIndex -= size;

-              if (isSequenceProperty(property))

-              {

-                Sequence fromSequence = (Sequence)dataObject.get(property);

-                size = fromSequence.size();

-                if (fromIndex >= size)

-                  continue;

-                move(fromSequence, fromIndex, sequence, toIndex);

-                return;

-              }

-              if (property.isMany())

-              {

-                List list = dataObject.getList(property);

-                size = list.size();

-                if (fromIndex >= size)

-                  continue;

-                sequence.add(toIndex, property, list.remove(fromIndex)); // removes containment

-                return;

-              }

-              if (fromIndex == 0)

-              {

-                sequence.add(toIndex, property, dataObject.get(property)); // removes containment

-                dataObject.unset(property);

-                return;

-              }

-              size = 1;

-            } // iterator.hasNext()

-            break;

-          } // toIndex < size

-          if (fromIndex < size)

-          {

-            while (iterator.hasNext())

-            {

-              property = (Property)iterator.next();

-              if (!dataObject.isSet(property))

-                continue;

-              toIndex -= size;

-              if (isSequenceProperty(property))

-              {

-                Sequence toSequence = (Sequence)dataObject.get(property);

-                size = toSequence.size();

-                if (toIndex >= size)

-                  continue;

-                if (++toIndex == size)

-                  toSequence.add(sequence.getProperty(fromIndex), remove(sequence, fromIndex)); // Java pushes stack from left to right

-                    // removes containment

-                else

-                  move(sequence, fromIndex, toSequence, toIndex);

-                return;

-              }

-              if (property.isMany())

-              {

-                List list = dataObject.getList(property);

-                size = list.size();

-                if (toIndex >= size)

-                  continue;

-                if (sequence.getProperty(fromIndex) != property)

-                  throw new IllegalArgumentException();

-                add(remove(sequence, fromIndex), list, toIndex, size);

-                return;

-              }

-              if (toIndex == 0)

-              {

-                while (iterator.hasNext())

-                {

-                  Property p = sequence.getProperty(fromIndex);

-                  property = (Property)iterator.next();

-                  EStructuralFeature feature = (EStructuralFeature)property;

-                  if (dataObject.isSet(property))

-                  {

-                    if (FeatureMapUtil.isFeatureMap(feature))

-                    {

-                      /*if (!validate(feature, p))

-                        throw new IllegalArgumentException(); */

-                      move(sequence, fromIndex, (Sequence)dataObject.get(property), 0, p);

-                      return;

-                    }

-                    if (property != p || !property.isMany())

-                      throw new IllegalArgumentException();

-                    insert(property, remove(sequence, fromIndex)); // removes containment

-                    return;

-                  }

-                  if (FeatureMapUtil.isFeatureMap(feature))

-                  {

-                    if (validate(feature, p))

-                    {

-                      append(property, p, remove(sequence, fromIndex)); // removes containment

-                      return;

-                    }

-                  }

-                  else if (property == p)

-                  {

-                    set(property, remove(sequence, fromIndex));

-                    return;

-                  }

-                } // iterator.hasNext()

-                break;

-              }

-              size = 1;

-            } // iterator.hasNext()

-            break;

-          } // fromIndex < size

-          toIndex -= size;

-          fromIndex -= size;

-        } // sequence(property)

-        else if (property.isMany())

-        {

-          List list = dataObject.getList(property);

-          int size = list.size();

-          if (toIndex < size)

-          {

-            if (fromIndex < size)

-            {

-              ((EList)list).move(toIndex, fromIndex);

-              return;

-            }

-            while (iterator.hasNext())

-            {

-              Property p = (Property)iterator.next();

-              if (!dataObject.isSet(p))

-                continue;

-              fromIndex -= size;

-              if (isSequenceProperty(p))

-              {

-                Sequence fromSequence = (Sequence)dataObject.get(p);

-                size = fromSequence.size();

-                if (fromIndex >= size)

-                  continue;

-                if (fromSequence.getProperty(fromIndex) != property)

-                  throw new IllegalArgumentException();

-                list.add(toIndex, remove(fromSequence, fromIndex)); // removes containment

-                return;

-              }

-              if (p.isMany())

-              {

-                List l = dataObject.getList(p);

-                size = l.size();

-                if (fromIndex >= size)

-                  continue;

-                /*if (p != property)

-                  throw new IllegalArgumentException(); */

-                list.add(toIndex, l.remove(fromIndex)); // removes containment

-                return;

-              }

-              if (fromIndex == 0)

-              {

-                /*if (p != property)

-                throw new IllegalArgumentException(); */

-                list.add(toIndex, dataObject.get(p)); // removes containment

-                dataObject.unset(p);

-                return;

-              }

-              size = 1;

-            } // iterator.hasNext()

-            break;

-          } // toIndex < size

-          if (fromIndex < size)

-          {

-            while (iterator.hasNext())

-            {

-              Property p = (Property)iterator.next();

-              if (!dataObject.isSet(p))

-                continue;

-              toIndex -= size;

-              if (isSequenceProperty(p))

-              {

-                Sequence toSequence = (Sequence)dataObject.get(p);

-                size = toSequence.size();

-                if (toIndex >= size)

-                  continue;

-                add(property, list.remove(fromIndex), toSequence, toIndex, size);

-                return;

-              }

-              if (p.isMany())

-              {

-                List l = dataObject.getList(p);

-                size = l.size();

-                if (toIndex >= size)

-                  continue;

-                /*if (property != p)

-                  throw new IllegalArgumentException(); */

-                add(list.remove(fromIndex), l, toIndex, size);

-                return;

-              }

-              if (toIndex == 0)

-              {

-                while (iterator.hasNext())

-                {

-                  p = (Property)iterator.next();

-                  EStructuralFeature feature = (EStructuralFeature)p;

-                  if (dataObject.isSet(p))

-                  {

-                    if (FeatureMapUtil.isFeatureMap(feature))

-                    {

-                      /*if (!validate(feature, property))

-                        throw new IllegalArgumentException(); */

-                      insert(p, property, list.remove(fromIndex));

-                      return;

-                    }

-                    if (/*p != property || */!p.isMany())

-                      throw new IllegalArgumentException();

-                    insert(p, list.remove(fromIndex)); // removes containment

-                    return;

-                  }

-                  if (FeatureMapUtil.isFeatureMap(feature))

-                  {

-                    if (!validate(feature, property))

-                      continue;

-                    append(p, property, list.remove(fromIndex)); // removes containment

-                    return;

-                  }

-                  else if (p == property)

-                  {

-                    set(p, list.remove(fromIndex));

-                    return;

-                  }

-                } // iterator.hasNext()

-                break;

-              } // toIndex == 0

-              size = 1;

-            } // iterator.hasNext()

-            break;

-          } // fromIndex < size

-          toIndex -= size;

-          fromIndex -= size;

-        } // property.isMany()

-        else if (toIndex == 0)

-          throw new IllegalArgumentException();

-        else if (fromIndex == 0)

-        {

-          for (int size = 1; iterator.hasNext() ;)

-          {

-            Property p = (Property)iterator.next();

-            if (!dataObject.isSet(p))

-              continue;

-            toIndex -= size;

-            if (isSequenceProperty(p))

-            {

-              Sequence toSequence = (Sequence)dataObject.get(p);

-              size = toSequence.size();

-              if (toIndex >= size)

-                continue;

-              add(property, dataObject.get(property), toSequence, toIndex, size);

-              dataObject.unset(property);

-              return;

-            }

-            if (p.isMany())

-            {

-              List l = dataObject.getList(p);

-              size = l.size();

-              if (toIndex >= size)

-                continue;

-              /*if (property != p)

-                throw new IllegalArgumentException(); */

-              add(dataObject.get(property), l, toIndex, size);

-              dataObject.unset(property);

-              return;

-            }

-            if (toIndex == 0)

-            {

-              while (iterator.hasNext())

-              {

-                p = (Property)iterator.next();

-                EStructuralFeature feature = (EStructuralFeature)p;

-                if (dataObject.isSet(p))

-                  if (FeatureMapUtil.isFeatureMap(feature))

-                    /*if (!validate(feature, property))

-                      throw new IllegalArgumentException(); */

-                    insert(p, property, dataObject.get(property));

-                  else if (/*p == property && */p.isMany())

-                    insert(p, dataObject.get(property)); // removes containment

-                  else

-                    throw new IllegalArgumentException();

-                else if (FeatureMapUtil.isFeatureMap(feature))

-                {

-                  if (!validate(feature, property))

-                    continue;

-                  append(p, property, dataObject.get(property)); // removes containment

-                }

-                else if (p == property)

-                  set(p, dataObject.get(property));

-                else

-                  continue;

-                dataObject.unset(property);

-                return;

-              } // iterator.hasNext()

-              break;

-            } // toIndex == 0

-            size = 1;

-          } // iterator.hasNext()

-          break;

-        } // fromIndex == 0

-        else

-        {

-          --toIndex;

-          --fromIndex;

-        }

-    }

-    throw new IndexOutOfBoundsException();

-  }

-}

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.util;
+
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.tuscany.sdo.impl.ClassImpl;
+import org.eclipse.emf.common.util.EList;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.util.FeatureMapUtil;
+
+import commonj.sdo.DataObject;
+import commonj.sdo.Property;
+import commonj.sdo.Sequence;
+
+/**
+ *  SDO Sequance implementation which delegates to a Collection of DataObject properties.
+ */
+public class VirtualSequence implements Sequence
+{
+  private final DataObject dataObject;
+  protected final List delegateProperties; // size > 1
+
+  public VirtualSequence(DataObject object)
+  {
+    dataObject = object;
+    delegateProperties = ((ClassImpl)dataObject.getType()).getVirtualSequenceProperties();
+  }
+  
+  static protected boolean isSequenceProperty(Object property)
+  {
+    return FeatureMapUtil.isFeatureMap((EStructuralFeature)property);
+  }
+  
+  public int size()
+  {
+    int size = 0;
+    for (Iterator iterator = delegateProperties.iterator() ; iterator.hasNext() ;)
+    {
+      Property property = (Property)iterator.next();
+      if (dataObject.isSet(property))
+        if (isSequenceProperty(property))
+          size += ((Sequence)dataObject.get(property)).size();
+        else if (property.isMany())
+          size += dataObject.getList(property).size();
+        else
+          ++size;
+    }
+    return size;
+  }
+
+  public Property getProperty(int index)
+  {
+    for (Iterator iterator = delegateProperties.iterator() ; iterator.hasNext() ;)
+    {
+      Property property = (Property)iterator.next();
+      if (dataObject.isSet(property))
+        if (isSequenceProperty(property))
+        {
+          Sequence sequence = (Sequence)dataObject.get(property);
+          int size = sequence.size();
+          if (index < size)
+            return sequence.getProperty(index);
+          index -= size;
+        }
+        else if (property.isMany())
+        {
+          int size = dataObject.getList(property).size();
+          if (index < size)
+            return property;
+          index -= size;
+        }
+        else if (index == 0)
+          return property;
+        else
+          --index;
+    }
+    throw new IndexOutOfBoundsException();
+  }
+
+  public Object getValue(int index)
+  {
+    for (Iterator iterator = delegateProperties.iterator() ; iterator.hasNext() ;)
+    {
+      Property property = (Property)iterator.next();
+      if (dataObject.isSet(property))
+        if (isSequenceProperty(property))
+        {
+          Sequence sequence = (Sequence)dataObject.get(property);
+          int size = sequence.size();
+          if (index < size)
+            return sequence.getValue(index);
+          index -= size;
+        }
+        else if (property.isMany())
+        {
+          List values = dataObject.getList(property);
+          int size = values.size();
+          if (index < size)
+            return values.get(index);
+          index -= size;
+        }
+        else if (index == 0)
+          return dataObject.get(property);
+        else
+          --index;
+    }
+    throw new IndexOutOfBoundsException();
+  }
+
+  public Object setValue(int index, Object value)
+  {
+    for (Iterator iterator = delegateProperties.iterator() ; iterator.hasNext() ;)
+    {
+      Property property = (Property)iterator.next();
+      if (dataObject.isSet(property))
+        if (isSequenceProperty(property))
+        {
+          Sequence sequence = (Sequence)dataObject.get(property);
+          int size = sequence.size();
+          if (index < size)
+            return sequence.setValue(index, value);
+          index -= size;
+        }
+        else if (property.isMany())
+        {
+          List values = dataObject.getList(property);
+          int size = values.size();
+          if (index < size)
+            return values.set(index, value);
+          index -= size;
+        }
+        else if (index == 0)
+        {
+          Object old = dataObject.get(property);  
+          dataObject.set(property, value);
+          return old;
+        }
+        else
+          --index;
+    }
+    throw new IndexOutOfBoundsException();
+  }
+  
+  boolean validate(EStructuralFeature feature, Object property)
+  {
+    return FeatureMapUtil.getValidator((EClass)dataObject.getType(), feature).isValid((EStructuralFeature)property);
+  }
+
+  boolean append(Property delegateProperty, Property property, Object value)
+  {
+    return ((Sequence)dataObject.get(delegateProperty)).add(property, value);
+  }
+  
+  boolean append(Property property, Object value)
+  {
+    return dataObject.getList(property).add(value);
+  }
+  
+  boolean set(Property property, Object value)
+  {
+    if (property.isMany())
+      return append(property, value);
+    dataObject.set(property, value);
+    return true;
+  }
+  
+  public final boolean add(Property p, Object value)
+  {
+    Property property;
+    int size = delegateProperties.size(), index = size;
+    do
+    {
+      property = (Property)delegateProperties.get(--index);
+      if (!dataObject.isSet(property))
+        continue;
+      EStructuralFeature feature = (EStructuralFeature)property;
+      if (FeatureMapUtil.isFeatureMap(feature))
+      {
+        if (validate(feature, p))
+          return append(property, p, value);
+      }
+      else if (property == p && property.isMany())
+        return append(property, value);
+      if (size == ++index)
+        return false;
+      property = (Property)delegateProperties.get(index);
+      break;
+    }
+    while (index != 0);
+    for (;;)
+    {
+      EStructuralFeature feature = (EStructuralFeature)property;
+      if (FeatureMapUtil.isFeatureMap(feature))
+      {
+        if (validate(feature, p))
+          return append(property, p, value);
+      }
+      else if (property == p)
+        return set(p, value);
+      if (size == ++index)
+        return false;
+      property = (Property)delegateProperties.get(index);
+    }
+  }
+
+  protected final Property property(String name)
+  {
+    return dataObject.getType().getProperty(name);
+  }
+
+  public boolean add(String propertyName, Object value)
+  {
+    return add(property(propertyName), value);
+  }
+
+  protected final Property property(int index)
+  {
+    return (Property)dataObject.getType().getProperties().get(index);
+  }
+
+  public boolean add(int propertyIndex, Object value)
+  {
+    return add(property(propertyIndex), value);
+  }
+  
+  void insert(Property property, Property p, Object value)
+  {
+    ((Sequence)dataObject.get(property)).add(0, p, value);
+  }
+  
+  void insert(Property property, Object value)
+  {
+    dataObject.getList(property).add(0, value);
+  }
+  
+  protected final int insert(Iterator iterator, Property p, Object value)
+  {
+    while (iterator.hasNext())
+    {
+      Property property = (Property)iterator.next();
+      EStructuralFeature feature = (EStructuralFeature)property;
+      if (dataObject.isSet(property))
+      {
+        if (FeatureMapUtil.isFeatureMap(feature))
+        {
+          if (!validate(feature, p))
+            return 2;
+          insert(property, p, value);
+          return 0;
+        }
+        if (property != p || !property.isMany())
+          return 2;
+        insert(property, value);
+        return 0;
+      }
+      if (FeatureMapUtil.isFeatureMap(feature))
+      {
+        if (validate(feature, p))
+        {
+          append(property, p, value);
+          return 0;
+        }
+      }
+      else if (property == p)
+      {
+        set(property, value);
+        return 0;
+      }
+    } // iterator.hasNext()
+    return 1;
+  }
+  
+  public final void add(int index, Property p, Object value)
+  {
+    Iterator iterator = delegateProperties.iterator();
+    if (index == 0)
+      switch (insert(iterator, p, value))
+      {
+        case 0:
+          return;
+        case 1:  
+          throw new IndexOutOfBoundsException();
+        default: // 2  
+          throw new IllegalArgumentException();
+      }
+    while (iterator.hasNext())
+    {
+      Property property = (Property)iterator.next();
+      if (dataObject.isSet(property))
+        if (isSequenceProperty(property))
+        {
+          Sequence sequence = (Sequence)dataObject.get(property);
+          int size = sequence.size();
+          if (index < size)
+          {
+            sequence.add(index, p, value);
+            return;
+          }
+          index -= size;
+          if (index != 0)
+            continue;
+          if (insert(iterator, p, value) != 0)
+            /*assert */sequence.add(p, value);
+          return;
+        } // sequence(property)
+        else if (property.isMany())
+        {
+          List values = dataObject.getList(property);
+          int size = values.size();
+          if (index < size)
+          {
+            values.add(index, value);
+            return;
+          }
+          index -= size;
+          if (index == 0 && property == p)
+          {
+            values.add(value);
+            return;
+          }
+        }
+        else if (index == 0)
+          throw new IllegalArgumentException();
+        else
+          --index;
+    }
+    throw new IndexOutOfBoundsException();
+  }
+
+  public void add(int index, String propertyName, Object value)
+  {
+    add(index, property(propertyName), value);
+  }
+
+  public void add(int index, int propertyIndex, Object value)
+  {
+    add(index, property(propertyIndex), value);
+  }
+
+  public final void addText(String text)
+  {
+    throw new IllegalArgumentException();
+  }
+
+  /**
+   * @deprecated
+   */
+  public void add(String text)
+  {
+    addText(text);
+  }
+
+  public final void addText(int index, String text)
+  {
+    throw new IllegalArgumentException();
+  }
+
+  /**
+   * @deprecated
+   */
+  public void add(int index, String text)
+  {
+    addText(index, text);
+  }
+
+  public void remove(int index)
+  {
+    for (Iterator iterator = delegateProperties.iterator() ; iterator.hasNext() ;)
+    {
+      Property property = (Property)iterator.next();
+      if (dataObject.isSet(property))
+        if (isSequenceProperty(property))
+        {
+          Sequence sequence = (Sequence)dataObject.get(property);
+          int size = sequence.size();
+          if (index < size)
+          {
+            sequence.remove(index);
+            return;
+          }
+          index -= size;
+        }
+        else if (property.isMany())
+        {
+          List values = dataObject.getList(property);
+          int size = values.size();
+          if (index < size)
+          {
+            values.remove(index);
+            return;
+          }
+          index -= size;
+        }
+        else if (index == 0)
+        {
+          dataObject.unset(property);
+          return;
+        }
+        else
+          --index;
+    }
+    throw new IndexOutOfBoundsException();
+  }
+
+  static private Object remove(Sequence sequence, int index)
+  {
+    Object value = sequence.getValue(index);
+    sequence.remove(index);
+    return value;
+  }
+  
+  static void move(Sequence fromSequence, int fromIndex, Sequence toSequence, int toIndex, Property property)
+  {
+    toSequence.add(toIndex, property, remove(fromSequence, fromIndex)); // removes containment
+  }
+  
+  static protected void move(Sequence fromSequence, int fromIndex, Sequence toSequence, int toIndex)
+  {
+    move(fromSequence, fromIndex, toSequence, toIndex, fromSequence.getProperty(fromIndex));
+  }
+  
+  static protected void add(Object value,List list,int index, int size)
+  {
+    if (++index == size)
+      /*assert */list.add(value);
+    else
+      list.add(index, value); // removes containment
+  }
+  
+  static protected void add(Property property, Object value, Sequence toSequence, int toIndex, int size)
+  {
+    if (++toIndex == size)
+      toSequence.add(property, value); // removes containment
+    else
+      toSequence.add(toIndex, property, value); // removes containment
+  }
+  
+  public void move(int toIndex, int fromIndex)
+  {
+    for (Iterator iterator = delegateProperties.iterator(); iterator.hasNext() ;)
+    {
+      Property property = (Property)iterator.next();
+      if (dataObject.isSet(property))
+        if (isSequenceProperty(property))
+        {
+          Sequence sequence = (Sequence)dataObject.get(property);
+          int size = sequence.size();
+          if (toIndex < size)
+          {
+            if (fromIndex < size)
+            {
+              sequence.move(toIndex, fromIndex);
+              return;
+            }
+            while (iterator.hasNext())
+            {
+              property = (Property)iterator.next();
+              if (!dataObject.isSet(property))
+                continue;
+              fromIndex -= size;
+              if (isSequenceProperty(property))
+              {
+                Sequence fromSequence = (Sequence)dataObject.get(property);
+                size = fromSequence.size();
+                if (fromIndex >= size)
+                  continue;
+                move(fromSequence, fromIndex, sequence, toIndex);
+                return;
+              }
+              if (property.isMany())
+              {
+                List list = dataObject.getList(property);
+                size = list.size();
+                if (fromIndex >= size)
+                  continue;
+                sequence.add(toIndex, property, list.remove(fromIndex)); // removes containment
+                return;
+              }
+              if (fromIndex == 0)
+              {
+                sequence.add(toIndex, property, dataObject.get(property)); // removes containment
+                dataObject.unset(property);
+                return;
+              }
+              size = 1;
+            } // iterator.hasNext()
+            break;
+          } // toIndex < size
+          if (fromIndex < size)
+          {
+            while (iterator.hasNext())
+            {
+              property = (Property)iterator.next();
+              if (!dataObject.isSet(property))
+                continue;
+              toIndex -= size;
+              if (isSequenceProperty(property))
+              {
+                Sequence toSequence = (Sequence)dataObject.get(property);
+                size = toSequence.size();
+                if (toIndex >= size)
+                  continue;
+                if (++toIndex == size)
+                  toSequence.add(sequence.getProperty(fromIndex), remove(sequence, fromIndex)); // Java pushes stack from left to right
+                    // removes containment
+                else
+                  move(sequence, fromIndex, toSequence, toIndex);
+                return;
+              }
+              if (property.isMany())
+              {
+                List list = dataObject.getList(property);
+                size = list.size();
+                if (toIndex >= size)
+                  continue;
+                if (sequence.getProperty(fromIndex) != property)
+                  throw new IllegalArgumentException();
+                add(remove(sequence, fromIndex), list, toIndex, size);
+                return;
+              }
+              if (toIndex == 0)
+              {
+                while (iterator.hasNext())
+                {
+                  Property p = sequence.getProperty(fromIndex);
+                  property = (Property)iterator.next();
+                  EStructuralFeature feature = (EStructuralFeature)property;
+                  if (dataObject.isSet(property))
+                  {
+                    if (FeatureMapUtil.isFeatureMap(feature))
+                    {
+                      /*if (!validate(feature, p))
+                        throw new IllegalArgumentException(); */
+                      move(sequence, fromIndex, (Sequence)dataObject.get(property), 0, p);
+                      return;
+                    }
+                    if (property != p || !property.isMany())
+                      throw new IllegalArgumentException();
+                    insert(property, remove(sequence, fromIndex)); // removes containment
+                    return;
+                  }
+                  if (FeatureMapUtil.isFeatureMap(feature))
+                  {
+                    if (validate(feature, p))
+                    {
+                      append(property, p, remove(sequence, fromIndex)); // removes containment
+                      return;
+                    }
+                  }
+                  else if (property == p)
+                  {
+                    set(property, remove(sequence, fromIndex));
+                    return;
+                  }
+                } // iterator.hasNext()
+                break;
+              }
+              size = 1;
+            } // iterator.hasNext()
+            break;
+          } // fromIndex < size
+          toIndex -= size;
+          fromIndex -= size;
+        } // sequence(property)
+        else if (property.isMany())
+        {
+          List list = dataObject.getList(property);
+          int size = list.size();
+          if (toIndex < size)
+          {
+            if (fromIndex < size)
+            {
+              ((EList)list).move(toIndex, fromIndex);
+              return;
+            }
+            while (iterator.hasNext())
+            {
+              Property p = (Property)iterator.next();
+              if (!dataObject.isSet(p))
+                continue;
+              fromIndex -= size;
+              if (isSequenceProperty(p))
+              {
+                Sequence fromSequence = (Sequence)dataObject.get(p);
+                size = fromSequence.size();
+                if (fromIndex >= size)
+                  continue;
+                if (fromSequence.getProperty(fromIndex) != property)
+                  throw new IllegalArgumentException();
+                list.add(toIndex, remove(fromSequence, fromIndex)); // removes containment
+                return;
+              }
+              if (p.isMany())
+              {
+                List l = dataObject.getList(p);
+                size = l.size();
+                if (fromIndex >= size)
+                  continue;
+                /*if (p != property)
+                  throw new IllegalArgumentException(); */
+                list.add(toIndex, l.remove(fromIndex)); // removes containment
+                return;
+              }
+              if (fromIndex == 0)
+              {
+                /*if (p != property)
+                throw new IllegalArgumentException(); */
+                list.add(toIndex, dataObject.get(p)); // removes containment
+                dataObject.unset(p);
+                return;
+              }
+              size = 1;
+            } // iterator.hasNext()
+            break;
+          } // toIndex < size
+          if (fromIndex < size)
+          {
+            while (iterator.hasNext())
+            {
+              Property p = (Property)iterator.next();
+              if (!dataObject.isSet(p))
+                continue;
+              toIndex -= size;
+              if (isSequenceProperty(p))
+              {
+                Sequence toSequence = (Sequence)dataObject.get(p);
+                size = toSequence.size();
+                if (toIndex >= size)
+                  continue;
+                add(property, list.remove(fromIndex), toSequence, toIndex, size);
+                return;
+              }
+              if (p.isMany())
+              {
+                List l = dataObject.getList(p);
+                size = l.size();
+                if (toIndex >= size)
+                  continue;
+                /*if (property != p)
+                  throw new IllegalArgumentException(); */
+                add(list.remove(fromIndex), l, toIndex, size);
+                return;
+              }
+              if (toIndex == 0)
+              {
+                while (iterator.hasNext())
+                {
+                  p = (Property)iterator.next();
+                  EStructuralFeature feature = (EStructuralFeature)p;
+                  if (dataObject.isSet(p))
+                  {
+                    if (FeatureMapUtil.isFeatureMap(feature))
+                    {
+                      /*if (!validate(feature, property))
+                        throw new IllegalArgumentException(); */
+                      insert(p, property, list.remove(fromIndex));
+                      return;
+                    }
+                    if (/*p != property || */!p.isMany())
+                      throw new IllegalArgumentException();
+                    insert(p, list.remove(fromIndex)); // removes containment
+                    return;
+                  }
+                  if (FeatureMapUtil.isFeatureMap(feature))
+                  {
+                    if (!validate(feature, property))
+                      continue;
+                    append(p, property, list.remove(fromIndex)); // removes containment
+                    return;
+                  }
+                  else if (p == property)
+                  {
+                    set(p, list.remove(fromIndex));
+                    return;
+                  }
+                } // iterator.hasNext()
+                break;
+              } // toIndex == 0
+              size = 1;
+            } // iterator.hasNext()
+            break;
+          } // fromIndex < size
+          toIndex -= size;
+          fromIndex -= size;
+        } // property.isMany()
+        else if (toIndex == 0)
+          throw new IllegalArgumentException();
+        else if (fromIndex == 0)
+        {
+          for (int size = 1; iterator.hasNext() ;)
+          {
+            Property p = (Property)iterator.next();
+            if (!dataObject.isSet(p))
+              continue;
+            toIndex -= size;
+            if (isSequenceProperty(p))
+            {
+              Sequence toSequence = (Sequence)dataObject.get(p);
+              size = toSequence.size();
+              if (toIndex >= size)
+                continue;
+              add(property, dataObject.get(property), toSequence, toIndex, size);
+              dataObject.unset(property);
+              return;
+            }
+            if (p.isMany())
+            {
+              List l = dataObject.getList(p);
+              size = l.size();
+              if (toIndex >= size)
+                continue;
+              /*if (property != p)
+                throw new IllegalArgumentException(); */
+              add(dataObject.get(property), l, toIndex, size);
+              dataObject.unset(property);
+              return;
+            }
+            if (toIndex == 0)
+            {
+              while (iterator.hasNext())
+              {
+                p = (Property)iterator.next();
+                EStructuralFeature feature = (EStructuralFeature)p;
+                if (dataObject.isSet(p))
+                  if (FeatureMapUtil.isFeatureMap(feature))
+                    /*if (!validate(feature, property))
+                      throw new IllegalArgumentException(); */
+                    insert(p, property, dataObject.get(property));
+                  else if (/*p == property && */p.isMany())
+                    insert(p, dataObject.get(property)); // removes containment
+                  else
+                    throw new IllegalArgumentException();
+                else if (FeatureMapUtil.isFeatureMap(feature))
+                {
+                  if (!validate(feature, property))
+                    continue;
+                  append(p, property, dataObject.get(property)); // removes containment
+                }
+                else if (p == property)
+                  set(p, dataObject.get(property));
+                else
+                  continue;
+                dataObject.unset(property);
+                return;
+              } // iterator.hasNext()
+              break;
+            } // toIndex == 0
+            size = 1;
+          } // iterator.hasNext()
+          break;
+        } // fromIndex == 0
+        else
+        {
+          --toIndex;
+          --fromIndex;
+        }
+    }
+    throw new IndexOutOfBoundsException();
+  }
+}
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/util/resource/ChangeSummaryStreamDeserializer.java b/impl/src/main/java/org/apache/tuscany/sdo/util/resource/ChangeSummaryStreamDeserializer.java
index 6dc461a..697de1c 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/util/resource/ChangeSummaryStreamDeserializer.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/util/resource/ChangeSummaryStreamDeserializer.java
@@ -1,663 +1,663 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.util.resource;

-

-import java.util.ArrayList;

-import java.util.Collection;

-import java.util.Comparator;

-import java.util.HashMap;

-import java.util.Iterator;

-import java.util.List;

-import java.util.Map;

-

-import javax.xml.namespace.NamespaceContext;

-import javax.xml.stream.XMLStreamException;

-import javax.xml.stream.XMLStreamReader;

-

-import org.apache.tuscany.sdo.SDOFactory;

-import org.apache.tuscany.sdo.helper.SDOAnnotations;

-import org.apache.tuscany.sdo.impl.ChangeSummaryImpl;

-import org.apache.tuscany.sdo.impl.ClassImpl;

-import org.eclipse.emf.ecore.EClass;

-import org.eclipse.emf.ecore.EObject;

-import org.eclipse.emf.ecore.EStructuralFeature;

-import org.eclipse.emf.ecore.ETypedElement;

-import org.eclipse.emf.ecore.change.ChangeDescription;

-import org.eclipse.emf.ecore.change.ChangeFactory;

-import org.eclipse.emf.ecore.change.ChangeKind;

-import org.eclipse.emf.ecore.change.FeatureChange;

-import org.eclipse.emf.ecore.change.FeatureMapEntry;

-import org.eclipse.emf.ecore.change.ListChange;

-import org.eclipse.emf.ecore.util.FeatureMap;

-import org.eclipse.emf.ecore.util.FeatureMapUtil;

-

-import commonj.sdo.ChangeSummary;

-import commonj.sdo.DataObject;

-import commonj.sdo.Property;

-import commonj.sdo.Type;

-import commonj.sdo.helper.HelperContext;

-

-/**

- * ChangeSummary StAX Deserializer whose input conforms to the SDO Java/C++/PHP specifications. The instance isn't thread-safe, however it's safe to

- * use the instance any times on the same thread.

- */

-public class ChangeSummaryStreamDeserializer extends SDODeserializer {

-    static final class ForwardReference extends Ref {

-        final String unset;

-

-        ForwardReference(String ref, NamespaceContext nameSpaces, String u) {

-            super(ref, nameSpaces);

-            unset = u;

-        }

-

-        Collection attributes/* = null */, qualifiedAttributes/* = null */, tags/* = null */; // may be null, never empty

-    }

-

-    protected Collection forwardReferences/* = null */;

-

-    static private final class ElementChange extends Ref {

-        private final Object containing, containment;

-        private ElementChange(String ref, NamespaceContext nameSpaces, Object property, Object propertyInSequence) {

-            super(ref, nameSpaces);

-            containing = property;

-            containment = propertyInSequence;

-        }

-    }

-

-    static private class PropertyMapChanges {

-        Map/* Property,List */lists/* = null */;// may be null

-

-        Collection put(Object property) {

-            Collection list = new ArrayList();

-            lists.put(property, list);

-            return list;

-        }

-

-        protected final Collection get(Object property) {

-            Object list = lists.get(property);

-            return list == null ? put(property) : (Collection) list;

-        }

-

-        protected final Collection newList(Object property) {

-            lists = new HashMap();

-            return put(property);

-        }

-    }

-

-    static final class ObjectChanges extends PropertyMapChanges {

-        Collection elementChanges/* = null */,// may be null, never empty

-                featureChanges;

-

-        protected final void newElementChanges() {

-            elementChanges = new ArrayList();

-        }

-    }

-

-    Collection objectChangesCollection/* = null */, objectMapChanges, deletedDataObjects;

-

-    protected final ObjectChanges newObjectChanges(Collection featureChanges) {

-        ObjectChanges objectChanges = new ObjectChanges();

-        objectChanges.featureChanges = featureChanges;

-        if (objectChangesCollection == null)

-            objectChangesCollection = new ArrayList();

-        objectChangesCollection.add(objectChanges);

-        return objectChanges;

-    }

-

-    private ChangeFactory changeFactory;

-

-    private SDOFactory changeSettingFactory;

-

-    private void logPropertyChange(Collection featureChanges, EStructuralFeature feature, Object value, boolean set) {

-        if (changeSettingFactory == null)

-            featureChanges.add(changeFactory.createFeatureChange(feature, value, set));

-        else

-            featureChanges.add(changeSettingFactory.createChangeSummarySetting(feature, value, set));

-    }

-

-    void unsetProperty(Collection featureChanges, String unset, int begin, int index, Type type) {

-        logPropertyChange(featureChanges, (EStructuralFeature) type.getProperty(unset.substring(begin, index)), null, false);

-    }

-

-    static boolean isWhitespace(String unset, int index) {

-        return Character.isWhitespace(unset.charAt(index));

-    }

-

-    protected final Collection unsetProperties(EObject referent, String unset, Type type) {

-        Map.Entry entry = changeFactory.createEObjectToChangesMapEntry(referent);

-        objectMapChanges.add(entry);

-        Collection featureChanges = (Collection) entry.getValue();

-        if (unset == null)

-            return featureChanges;

-        int end = unset.length();

-        if (end != 0)

-            for (int begin = 0, index = 1;/* true */; ++index) {

-                if (index == end) {

-                    unsetProperty(featureChanges, unset, begin, index, type);

-                    break;

-                }

-                if (isWhitespace(unset, index)) {

-                    unsetProperty(featureChanges, unset, begin, index, type);

-                    while (true) {

-                        if (++index != end)

-                            return featureChanges;

-                        if (!isWhitespace(unset, index)) {

-                            begin = index;

-                            break;

-                        }

-                    }

-                }

-            }

-        return featureChanges;

-    }

-

-    private Object value(EStructuralFeature containing, Object containment, Object value) {

-        return FeatureMapUtil.isFeatureMap(containing) ? changeFactory.createFeatureMapEntry((EStructuralFeature) containment, value) : value;

-    }

-

-    private void logPropertyChange(Collection featureChanges, Object containing, Object containment, Object value) {

-        EStructuralFeature feature = (EStructuralFeature) containing;

-        logPropertyChange(featureChanges, feature, value(feature, containment, value), true);

-    }

-

-    private void logPropertyChange(Collection featureChanges, Object property, Object value) {

-        logPropertyChange(featureChanges, property, propertyInSequence, value);

-    }

-

-    void logAttributeChange(Collection featureChanges, Property property, String literal, NamespaceContext nameSpaces) {

-        logPropertyChange(featureChanges, property, value(property.getType(), literal, nameSpaces));

-    }

-

-    protected final void logAttributeChange(Collection featureChanges, String property, Type type, String value, NamespaceContext nameSpaces) {

-        logAttributeChange(featureChanges, getProperty(type, property), value, nameSpaces);

-    }

-

-    protected final void logAttributeChange(Collection featureChanges, String nameSpace, String name, Type type, String value,

-            NamespaceContext nameSpaces) {

-        logAttributeChange(featureChanges, getProperty(type, nameSpace, name, false), value, nameSpaces);

-    }

-

-    protected final String ref() {

-        return reader.getAttributeValue(SDOAnnotations.COMMONJ_SDO_NS, ChangeSummaryStreamSerializer.REF_ATTRIBUTE);

-    }

-

-    ChangeSummaryImpl changeSummary;

-

-    protected Object load(XMLStreamReader reader, Map options) throws XMLStreamException {

-        Object value = super.load(reader, options);

-        deletedDataObjects.add(value);

-        return value;

-    }

-

-    protected final void getChangeSummary(DataObject rootObject) {

-        changeSummary = (ChangeSummaryImpl) rootObject.getChangeSummary(); // DynamicDataObjectImpl(EClass)

-    }

-

-    static protected final class Tag extends RecordedEventXMLStreamReader.Tag {

-        protected String ref;

-

-        protected Object value;

-

-        protected Tag(XMLStreamReader reader) {

-            super(reader);

-        }

-    }

-

-    protected final void addPropertyChange(Collection list, Object value, Object containing) {

-        list.add(value((EStructuralFeature) containing, propertyInSequence, value));

-    }

-

-    protected boolean logging;

-

-    /**

-     * Imports ChangeSummary 2-1. Forward references will be resolved by {@link #end()}.

-     * 

-     * @param reader

-     *            Never null

-     * @throws XMLStreamException

-     */

-    public final void begin(DataObject rootObject, HelperContext scope, XMLStreamReader reader) throws XMLStreamException {

-        /*

-         * 3-1. Instantiate ChangeSummary input: reader (xsi:type), factory, rootObject output: changeSummary, changeDescription

-         */

-        initialize(reader, scope, rootObject);

-        if (typedXSI()) {

-            changeSummary = (ChangeSummaryImpl) scope.getDataFactory().create(nameSpace, name);

-            if (changeSummary == null)

-                getChangeSummary(rootObject);

-            else {

-                Property csp = ((ClassImpl) rootObject.getType()).getChangeSummaryProperty();

-                rootObject.set(csp, changeSummary);

-                changeSummary.setDataObject(rootObject);

-            }

-        } else

-            getChangeSummary(rootObject);

-        ChangeDescription changeDescription = (ChangeDescription) changeSummary;

-

-        /*

-         * 3-2. "logging" attribute input: reader output: logging

-         */

-        logging = Boolean.valueOf(reader.getAttributeValue(null, "logging")).booleanValue();

-

-        /*

-         * 3-3. Modified DataObjects input: changeDescription

-         */

-        if (forwardReferences != null)

-            forwardReferences.clear();

-        if (objectChangesCollection != null)

-            objectChangesCollection.clear();

-        if (START_ELEMENT == reader.nextTag()) {

-            objectMapChanges = changeDescription.getObjectChanges();

-            deletedDataObjects = changeDescription.getObjectsToAttach();

-            Object factory = changeDescription.eClass().getEPackage().getEFactoryInstance();

-            changeFactory = factory instanceof ChangeFactory ? (ChangeFactory) factory : ChangeFactory.eINSTANCE;

-            changeSettingFactory = factory instanceof SDOFactory ? (SDOFactory) factory : null;

-            do {

-                /*

-                 * Modified DataObject

-                 */

-                String ref = ref(), unset = reader.getAttributeValue(SDOAnnotations.COMMONJ_SDO_NS, ChangeSummaryStreamSerializer.UNSET);

-                int attributes = reader.getAttributeCount();

-                NamespaceContext nameSpaces = reader.getNamespaceContext();

-                EObject referent = referent(ref, nameSpaces);

-                if (referent == null) {

-                    /*

-                     * Forward-referenced(unresolved) modified DataObject

-                     */

-                    ForwardReference forwardReference = new ForwardReference(ref, nameSpaces, unset);

-                    if (forwardReferences == null)

-                        forwardReferences = new ArrayList();

-                    forwardReferences.add(forwardReference);

-                    do // what about xmlns="NS1" a1="qName" xmlns="NS2" a2="qName" ?

-                    {

-                        /*

-                         * Record property old value as attribute for end()

-                         */

-                        String nameSpace = reader.getAttributeNamespace(--attributes), name = reader.getAttributeLocalName(attributes), value = reader

-                                .getAttributeValue(attributes);

-                        if (nameSpace == null) {

-                            /*

-                             * Local attribute

-                             */

-                            Attribute attribute = new Attribute();

-                            attribute.name = name;

-                            attribute.value = value;

-                            if (forwardReference.attributes == null)

-                                forwardReference.attributes = new ArrayList();

-                            forwardReference.attributes.add(attribute);

-                        } else if (!SDOAnnotations.COMMONJ_SDO_NS.equals(nameSpace) || !ChangeSummaryStreamSerializer.REF_ATTRIBUTE.equals(name)

-                                && !ChangeSummaryStreamSerializer.UNSET.equals(name)) {

-                            /*

-                             * Qualified(global) attribute

-                             */

-                            QualifiedAttribute attribute = new QualifiedAttribute();

-                            attribute.name = name;

-                            attribute.value = value;

-                            attribute.nameSpace = nameSpace;

-                            if (forwardReference.qualifiedAttributes == null)

-                                forwardReference.qualifiedAttributes = new ArrayList();

-                            forwardReference.qualifiedAttributes.add(attribute);

-                        }

-                    } while (attributes != 0);

-                    while (START_ELEMENT == reader.nextTag()) {

-                        /*

-                         * Record property old value as element for end()

-                         */

-                        Tag tag = new Tag(reader);

-                        if (forwardReference.tags == null)

-                            forwardReference.tags = new ArrayList();

-                        forwardReference.tags.add(tag);

-                        tag.ref = ref();

-                        if (tag.ref != null)

-                            continue;

-                        Type xsi = typeXSI();

-                        if (xsi == null) {

-                            if (tag.nameSpace != null)

-                                tag.value = value(globalElementType(tag.nameSpace, tag.name.getLocalPart())); // TODO substitutionGroup type if null

-                            else if (tag.record(reader))

-                                break;

-                        } else

-                            tag.value = value(xsi);

-                    }

-                } else {

-                    /*

-                     * Resolved(back-referenced) modified DataObject

-                     */

-                    Type type = ((DataObject) referent).getType();

-                    Collection featureChanges = unsetProperties(referent, unset, type);

-                    do // what about xmlns="NS1" a1="qName" xmlns="NS2" a2="qName" ?

-                    {

-                        /*

-                         * Log property old value as attribute

-                         */

-                        String nameSpace = reader.getAttributeNamespace(--attributes), name = reader.getAttributeLocalName(attributes), value = reader

-                                .getAttributeValue(attributes);

-                        if (nameSpace == null)

-                            logAttributeChange(featureChanges, name, type, value, nameSpaces);

-                        else if (!SDOAnnotations.COMMONJ_SDO_NS.equals(nameSpace) || !ChangeSummaryStreamSerializer.REF_ATTRIBUTE.equals(name)

-                                && !ChangeSummaryStreamSerializer.UNSET.equals(name))

-                            logAttributeChange(featureChanges, nameSpace, name, type, value, nameSpaces);

-                    } while (attributes != 0);

-                    if (START_ELEMENT == reader.nextTag()) {

-                        ObjectChanges objectChanges = null;

-                        do {

-                            /*

-                             * Log property old value as element

-                             */

-                            String nameSpace = reader.getNamespaceURI(), name = reader.getLocalName();

-                            Property property = getProperty(nameSpace, name, type);

-                            boolean many = property.isMany();

-                            Object value;

-                            ref = ref();

-                            if (ref == null) {

-                                /*

-                                 * Contained property old value

-                                 */

-                                Type xsi = typeXSI();

-                                if (xsi != null)

-                                    value = value(xsi);

-                                else if (nameSpace == null)

-                                    value = value(reader);

-                                else {

-                                    xsi = globalElementType(nameSpace, name);

-                                    value = value(xsi == null ? propertyInSequence.getType() : xsi);

-                                }

-                            } else {

-                                /*

-                                 * Referenced child DataObject

-                                 */

-                                nameSpaces = reader.getNamespaceContext();

-                                reader.nextTag()/* END_ELEMENT */;

-                                value = referent(ref, nameSpaces);

-                                if (value == null) {

-                                    /*

-                                     * Forward-referenced(unresolved) child DataObject

-                                     */

-                                    if (!many) {

-                                        ElementChange elementChange = new ElementChange(ref, nameSpaces, property, propertyInSequence);

-                                        if (objectChanges == null) {

-                                            objectChanges = newObjectChanges(featureChanges);

-                                            objectChanges.newElementChanges();

-                                        } else if (objectChanges.elementChanges == null)

-                                            objectChanges.newElementChanges();

-                                        objectChanges.elementChanges.add(elementChange);

-                                        continue;

-                                    }

-                                    value = new Ref(ref, nameSpaces);

-                                }

-                            }

-                            if (many) {

-                                Collection list;

-                                if (objectChanges == null) {

-                                    objectChanges = newObjectChanges(featureChanges);

-                                    list = objectChanges.newList(property);

-                                } else if (objectChanges.lists == null)

-                                    list = objectChanges.newList(property);

-                                else

-                                    list = objectChanges.get(property);

-                                addPropertyChange(list, value, property);

-                            } else

-                                logPropertyChange(featureChanges, property, value);

-                        } while (START_ELEMENT == reader.nextTag());

-                    }

-                }

-            } while (START_ELEMENT == reader.nextTag());

-        }

-    }

-

-    static private boolean sequence(Object listChanges) {

-        return FeatureMapUtil.isFeatureMap(((FeatureChange) ((EStructuralFeature.Setting) listChanges).getEObject()).getFeature());

-    }

-

-    private ListChange createListChange(ChangeKind changeKind, int index, Collection listChanges) {

-        ListChange listChange = changeFactory.createListChange();

-        listChange.setKind(changeKind);

-        listChange.setIndex(index);

-        listChanges.add(listChange);

-        return listChange;

-    }

-

-    Collection add(Collection adds, int change, Collection listChanges, Object value) {

-        if (adds == null) {

-            ListChange listChange = createListChange(ChangeKind.ADD_LITERAL, change, listChanges);

-            adds = sequence(listChanges) ? listChange.getFeatureMapEntryValues() : listChange.getValues();

-        }

-        adds.add(value);

-        return adds;

-    }

-

-    private int remove(int change, Collection listChanges, List list, int begin, int end) {

-        ListChange listChange = createListChange(ChangeKind.REMOVE_LITERAL, change, listChanges);

-        if (sequence(listChanges)) {

-            Collection removes = listChange.getFeatureMapEntryValues();

-            do {

-                FeatureMap.Entry fme = (FeatureMap.Entry) list.get(begin);

-                removes.add(changeFactory.createFeatureMapEntry(fme.getEStructuralFeature(), fme.getValue()));

-            } while (++begin != end);

-            return begin;

-        }

-        Collection removes = listChange.getValues();

-        do

-            removes.add(list.get(begin));

-        while (++begin != end);

-        return begin;

-    }

-

-    int remove(int begin, int end, int change, Collection listChanges, List list) {

-        return begin == end ? begin : remove(change, listChanges, list, begin, end);

-    }

-

-    protected final void logManyChanges(PropertyMapChanges propertyMapChanges, EObject referent, Collection featureChanges) {

-        for (Iterator lists = propertyMapChanges.lists.entrySet().iterator(); lists.hasNext();) {

-            /*

-             * Compute ListChanges out of comparision of old and new list

-             */

-            Map.Entry entry = (Map.Entry) lists.next();

-            EStructuralFeature property = (EStructuralFeature) entry.getKey();

-            Iterator values = ((Collection) entry.getValue()).iterator(); // old list

-            Object value = referent.eGet(property);

-            List list = value instanceof FeatureMap.Internal.Wrapper ? ((FeatureMap.Internal.Wrapper) value).featureMap() : (List) value; // new

-            int change = 0;

-            FeatureChange featureChange = changeSettingFactory == null ? changeFactory.createFeatureChange() : (FeatureChange) changeSettingFactory

-                    .createChangeSummarySetting();

-            featureChange.setFeature(property);

-            Collection listChanges = featureChange.getListChanges(), adds = null;

-            featureChanges.add(featureChange);

-            if (property.getEType() instanceof EClass) {

-                /*

-                 * Log child DataObject changes

-                 */

-                int begin = 0, end = list.size();

-                while (values.hasNext()) {

-                    value = values.next();

-                    if (value.getClass() == Ref.class) {

-                        value = referent((Ref) value);

-                        if (value == null)

-                            continue;// report error?

-                    }

-                    // values.remove();

-                    for (int index = begin;/* true */; ++index)

-                        if (index == end) {

-                            adds = add(adds, change, listChanges, value);

-                            break;

-                        } else if (list.get(index) == value) // List#indexOf uses equals

-                        {

-                            begin = remove(begin, index, change, listChanges, list);

-                            ++begin;

-                            adds = null;

-                            break;

-                        }

-                    ++change;

-                }

-                remove(begin, end, change, listChanges, list);

-            } else if (FeatureMapUtil.isFeatureMap(property)) {

-                /*

-                 * Log Sequence changes

-                 */

-                int begin = 0, end = list.size();

-                while (values.hasNext()) {

-                    FeatureMapEntry featureMapEntry = (FeatureMapEntry) values.next();

-                    value = featureMapEntry.getValue();

-                    if (value.getClass() == Ref.class) {

-                        value = referent((Ref) value);

-                        if (value == null)

-                            continue;// report error?

-                    }

-                    // values.remove();

-                    Comparator equality;

-                    ETypedElement feature = featureMapEntry.getFeature();

-                    if (((Type) feature.getEType()).isDataType())

-                        if (value == null)

-                            equality = EQUAL_NULL;

-                        else

-                            equality = EQUAL;

-                    else

-                        equality = SAME;

-                    for (int index = begin;/* true */; ++index)

-                        if (index == end) {

-                            adds = add(adds, change, listChanges, featureMapEntry);

-                            break;

-                        } else {

-                            FeatureMap.Entry fme = (FeatureMap.Entry) list.get(index);

-                            if (feature == fme.getEStructuralFeature() && equality.compare(fme.getValue(), value) == 0) {

-                                begin = remove(begin, index, change, listChanges, list);

-                                ++begin;

-                                adds = null;

-                                break;

-                            }

-                        }

-                    ++change;

-                }

-                remove(begin, end, change, listChanges, list);

-            } else {

-                /*

-                 * Log simple value changes

-                 */

-                while (values.hasNext()) {

-                    value = values.next();

-                    // values.remove();

-                    int index = list.indexOf(value);

-                    switch (index) {

-                    case -1:

-                        adds = add(adds, change, listChanges, value);

-                        break;

-                    default:

-                        remove(change, listChanges, list, 0, index);

-                    case 0:

-                        list = list.subList(++index, list.size());

-                        adds = null;

-                    }

-                    ++change;

-                }

-                remove(0, list.size(), change, listChanges, list);

-            }

-        }

-    }

-

-    protected PropertyMapChanges propertyMapChanges/* = null */;

-

-    /**

-     * Imports ChangeSummary 2-2. Resolves forward references from {@link #begin} and resumes logging if necessary. If it's invoked from

-     * patching/resolving, try to make it last since logging may be turned on.

-     * 

-     * @see #begin

-     */

-    public final ChangeSummary end() throws XMLStreamException {

-        if (forwardReferences != null)

-            for (Iterator iterator = forwardReferences.iterator(); iterator.hasNext();) {

-                /*

-                 * Forward-referenced(unresolved) modified DataObject from begin(...)

-                 */

-                ForwardReference forwardReference = (ForwardReference) iterator.next();

-                EObject referent = referent(forwardReference);

-                if (referent == null)

-                    continue; // report error?

-                // iterator.remove();

-                Type type = ((DataObject) referent).getType();

-                Collection featureChanges = unsetProperties(referent, forwardReference.unset, type);

-                if (forwardReference.attributes != null)

-                    for (Iterator attributes = forwardReference.attributes.iterator(); attributes.hasNext();) {

-                        /*

-                         * Log property old value as local attribute from begin(...)

-                         */

-                        Attribute attribute = (Attribute) attributes.next();

-                        logAttributeChange(featureChanges, attribute.name, type, attribute.value, forwardReference.nameSpaces);

-                    }

-                if (forwardReference.qualifiedAttributes != null)

-                    for (Iterator attributes = forwardReference.qualifiedAttributes.iterator(); attributes.hasNext();) {

-                        /*

-                         * Log property old value as qualified/global attribute from begin(...)

-                         */

-                        QualifiedAttribute attribute = (QualifiedAttribute) attributes.next();

-                        logAttributeChange(featureChanges, attribute.nameSpace, attribute.name, type, attribute.value, forwardReference.nameSpaces);

-                    }

-                if (forwardReference.tags != null) {

-                    if (propertyMapChanges != null)

-                        propertyMapChanges.lists.clear();

-                    for (Iterator tags = forwardReference.tags.iterator(); tags.hasNext();) {

-                        /*

-                         * Log property old value as element from begin(...)

-                         */

-                        Tag tag = (Tag) tags.next();

-                        Property property = getProperty(tag.nameSpace, tag.name.getLocalPart(), type);

-                        if (tag.ref != null)

-                            tag.value = referent(tag.ref, tag.nameSpaceContext);

-                        // if (tag.value == null) report error?

-                        else if (tag.events != null)

-                            tag.value = value(play(tag));

-                        if (property.isMany()) {

-                            Collection list;

-                            if (propertyMapChanges == null) {

-                                propertyMapChanges = new PropertyMapChanges();

-                                list = propertyMapChanges.newList(property);

-                            } else

-                                list = propertyMapChanges.get(property);

-                            addPropertyChange( list, tag.value, property);

-                        } else

-                            logPropertyChange(featureChanges, property, tag.value);

-                    }

-                    if (propertyMapChanges != null)

-                        logManyChanges(propertyMapChanges, referent, featureChanges);

-                }

-            }

-        if (objectChangesCollection != null)

-            for (Iterator iterator = objectChangesCollection.iterator(); iterator.hasNext();) {

-                /*

-                 * Forward-referenced(unresolved) child DataObject from begin(...)

-                 */

-                ObjectChanges objectChanges = (ObjectChanges) iterator.next();

-                if (objectChanges.elementChanges != null)

-                    for (Iterator elementChanges = objectChanges.elementChanges.iterator(); elementChanges.hasNext();) {

-                        ElementChange elementChange = (ElementChange) elementChanges.next();

-                        Object value = referent(elementChange);

-                        if (value == null)

-                            continue; // report error?

-                        // iterator.remove();

-                        logPropertyChange(objectChanges.featureChanges, elementChange.containing, elementChange.containment, value);

-                    }

-                if (objectChanges.lists != null)

-                    logManyChanges(objectChanges, (EObject) ((Map.Entry) ((EStructuralFeature.Setting) objectChanges.featureChanges).getEObject())

-                            .getKey(), objectChanges.featureChanges);

-            }

-        if (logging)

-            changeSummary.resumeLogging();

-        return changeSummary;

-    }

-}

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.util.resource;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+
+import org.apache.tuscany.sdo.SDOFactory;
+import org.apache.tuscany.sdo.helper.SDOAnnotations;
+import org.apache.tuscany.sdo.impl.ChangeSummaryImpl;
+import org.apache.tuscany.sdo.impl.ClassImpl;
+import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.ETypedElement;
+import org.eclipse.emf.ecore.change.ChangeDescription;
+import org.eclipse.emf.ecore.change.ChangeFactory;
+import org.eclipse.emf.ecore.change.ChangeKind;
+import org.eclipse.emf.ecore.change.FeatureChange;
+import org.eclipse.emf.ecore.change.FeatureMapEntry;
+import org.eclipse.emf.ecore.change.ListChange;
+import org.eclipse.emf.ecore.util.FeatureMap;
+import org.eclipse.emf.ecore.util.FeatureMapUtil;
+
+import commonj.sdo.ChangeSummary;
+import commonj.sdo.DataObject;
+import commonj.sdo.Property;
+import commonj.sdo.Type;
+import commonj.sdo.helper.HelperContext;
+
+/**
+ * ChangeSummary StAX Deserializer whose input conforms to the SDO Java/C++/PHP specifications. The instance isn't thread-safe, however it's safe to
+ * use the instance any times on the same thread.
+ */
+public class ChangeSummaryStreamDeserializer extends SDODeserializer {
+    static final class ForwardReference extends Ref {
+        final String unset;
+
+        ForwardReference(String ref, NamespaceContext nameSpaces, String u) {
+            super(ref, nameSpaces);
+            unset = u;
+        }
+
+        Collection attributes/* = null */, qualifiedAttributes/* = null */, tags/* = null */; // may be null, never empty
+    }
+
+    protected Collection forwardReferences/* = null */;
+
+    static private final class ElementChange extends Ref {
+        private final Object containing, containment;
+        private ElementChange(String ref, NamespaceContext nameSpaces, Object property, Object propertyInSequence) {
+            super(ref, nameSpaces);
+            containing = property;
+            containment = propertyInSequence;
+        }
+    }
+
+    static private class PropertyMapChanges {
+        Map/* Property,List */lists/* = null */;// may be null
+
+        Collection put(Object property) {
+            Collection list = new ArrayList();
+            lists.put(property, list);
+            return list;
+        }
+
+        protected final Collection get(Object property) {
+            Object list = lists.get(property);
+            return list == null ? put(property) : (Collection) list;
+        }
+
+        protected final Collection newList(Object property) {
+            lists = new HashMap();
+            return put(property);
+        }
+    }
+
+    static final class ObjectChanges extends PropertyMapChanges {
+        Collection elementChanges/* = null */,// may be null, never empty
+                featureChanges;
+
+        protected final void newElementChanges() {
+            elementChanges = new ArrayList();
+        }
+    }
+
+    Collection objectChangesCollection/* = null */, objectMapChanges, deletedDataObjects;
+
+    protected final ObjectChanges newObjectChanges(Collection featureChanges) {
+        ObjectChanges objectChanges = new ObjectChanges();
+        objectChanges.featureChanges = featureChanges;
+        if (objectChangesCollection == null)
+            objectChangesCollection = new ArrayList();
+        objectChangesCollection.add(objectChanges);
+        return objectChanges;
+    }
+
+    private ChangeFactory changeFactory;
+
+    private SDOFactory changeSettingFactory;
+
+    private void logPropertyChange(Collection featureChanges, EStructuralFeature feature, Object value, boolean set) {
+        if (changeSettingFactory == null)
+            featureChanges.add(changeFactory.createFeatureChange(feature, value, set));
+        else
+            featureChanges.add(changeSettingFactory.createChangeSummarySetting(feature, value, set));
+    }
+
+    void unsetProperty(Collection featureChanges, String unset, int begin, int index, Type type) {
+        logPropertyChange(featureChanges, (EStructuralFeature) type.getProperty(unset.substring(begin, index)), null, false);
+    }
+
+    static boolean isWhitespace(String unset, int index) {
+        return Character.isWhitespace(unset.charAt(index));
+    }
+
+    protected final Collection unsetProperties(EObject referent, String unset, Type type) {
+        Map.Entry entry = changeFactory.createEObjectToChangesMapEntry(referent);
+        objectMapChanges.add(entry);
+        Collection featureChanges = (Collection) entry.getValue();
+        if (unset == null)
+            return featureChanges;
+        int end = unset.length();
+        if (end != 0)
+            for (int begin = 0, index = 1;/* true */; ++index) {
+                if (index == end) {
+                    unsetProperty(featureChanges, unset, begin, index, type);
+                    break;
+                }
+                if (isWhitespace(unset, index)) {
+                    unsetProperty(featureChanges, unset, begin, index, type);
+                    while (true) {
+                        if (++index != end)
+                            return featureChanges;
+                        if (!isWhitespace(unset, index)) {
+                            begin = index;
+                            break;
+                        }
+                    }
+                }
+            }
+        return featureChanges;
+    }
+
+    private Object value(EStructuralFeature containing, Object containment, Object value) {
+        return FeatureMapUtil.isFeatureMap(containing) ? changeFactory.createFeatureMapEntry((EStructuralFeature) containment, value) : value;
+    }
+
+    private void logPropertyChange(Collection featureChanges, Object containing, Object containment, Object value) {
+        EStructuralFeature feature = (EStructuralFeature) containing;
+        logPropertyChange(featureChanges, feature, value(feature, containment, value), true);
+    }
+
+    private void logPropertyChange(Collection featureChanges, Object property, Object value) {
+        logPropertyChange(featureChanges, property, propertyInSequence, value);
+    }
+
+    void logAttributeChange(Collection featureChanges, Property property, String literal, NamespaceContext nameSpaces) {
+        logPropertyChange(featureChanges, property, value(property.getType(), literal, nameSpaces));
+    }
+
+    protected final void logAttributeChange(Collection featureChanges, String property, Type type, String value, NamespaceContext nameSpaces) {
+        logAttributeChange(featureChanges, getProperty(type, property), value, nameSpaces);
+    }
+
+    protected final void logAttributeChange(Collection featureChanges, String nameSpace, String name, Type type, String value,
+            NamespaceContext nameSpaces) {
+        logAttributeChange(featureChanges, getProperty(type, nameSpace, name, false), value, nameSpaces);
+    }
+
+    protected final String ref() {
+        return reader.getAttributeValue(SDOAnnotations.COMMONJ_SDO_NS, ChangeSummaryStreamSerializer.REF_ATTRIBUTE);
+    }
+
+    ChangeSummaryImpl changeSummary;
+
+    protected Object load(XMLStreamReader reader, Map options) throws XMLStreamException {
+        Object value = super.load(reader, options);
+        deletedDataObjects.add(value);
+        return value;
+    }
+
+    protected final void getChangeSummary(DataObject rootObject) {
+        changeSummary = (ChangeSummaryImpl) rootObject.getChangeSummary(); // DynamicDataObjectImpl(EClass)
+    }
+
+    static protected final class Tag extends RecordedEventXMLStreamReader.Tag {
+        protected String ref;
+
+        protected Object value;
+
+        protected Tag(XMLStreamReader reader) {
+            super(reader);
+        }
+    }
+
+    protected final void addPropertyChange(Collection list, Object value, Object containing) {
+        list.add(value((EStructuralFeature) containing, propertyInSequence, value));
+    }
+
+    protected boolean logging;
+
+    /**
+     * Imports ChangeSummary 2-1. Forward references will be resolved by {@link #end()}.
+     * 
+     * @param reader
+     *            Never null
+     * @throws XMLStreamException
+     */
+    public final void begin(DataObject rootObject, HelperContext scope, XMLStreamReader reader) throws XMLStreamException {
+        /*
+         * 3-1. Instantiate ChangeSummary input: reader (xsi:type), factory, rootObject output: changeSummary, changeDescription
+         */
+        initialize(reader, scope, rootObject);
+        if (typedXSI()) {
+            changeSummary = (ChangeSummaryImpl) scope.getDataFactory().create(nameSpace, name);
+            if (changeSummary == null)
+                getChangeSummary(rootObject);
+            else {
+                Property csp = ((ClassImpl) rootObject.getType()).getChangeSummaryProperty();
+                rootObject.set(csp, changeSummary);
+                changeSummary.setDataObject(rootObject);
+            }
+        } else
+            getChangeSummary(rootObject);
+        ChangeDescription changeDescription = (ChangeDescription) changeSummary;
+
+        /*
+         * 3-2. "logging" attribute input: reader output: logging
+         */
+        logging = Boolean.valueOf(reader.getAttributeValue(null, "logging")).booleanValue();
+
+        /*
+         * 3-3. Modified DataObjects input: changeDescription
+         */
+        if (forwardReferences != null)
+            forwardReferences.clear();
+        if (objectChangesCollection != null)
+            objectChangesCollection.clear();
+        if (START_ELEMENT == reader.nextTag()) {
+            objectMapChanges = changeDescription.getObjectChanges();
+            deletedDataObjects = changeDescription.getObjectsToAttach();
+            Object factory = changeDescription.eClass().getEPackage().getEFactoryInstance();
+            changeFactory = factory instanceof ChangeFactory ? (ChangeFactory) factory : ChangeFactory.eINSTANCE;
+            changeSettingFactory = factory instanceof SDOFactory ? (SDOFactory) factory : null;
+            do {
+                /*
+                 * Modified DataObject
+                 */
+                String ref = ref(), unset = reader.getAttributeValue(SDOAnnotations.COMMONJ_SDO_NS, ChangeSummaryStreamSerializer.UNSET);
+                int attributes = reader.getAttributeCount();
+                NamespaceContext nameSpaces = reader.getNamespaceContext();
+                EObject referent = referent(ref, nameSpaces);
+                if (referent == null) {
+                    /*
+                     * Forward-referenced(unresolved) modified DataObject
+                     */
+                    ForwardReference forwardReference = new ForwardReference(ref, nameSpaces, unset);
+                    if (forwardReferences == null)
+                        forwardReferences = new ArrayList();
+                    forwardReferences.add(forwardReference);
+                    do // what about xmlns="NS1" a1="qName" xmlns="NS2" a2="qName" ?
+                    {
+                        /*
+                         * Record property old value as attribute for end()
+                         */
+                        String nameSpace = reader.getAttributeNamespace(--attributes), name = reader.getAttributeLocalName(attributes), value = reader
+                                .getAttributeValue(attributes);
+                        if (nameSpace == null) {
+                            /*
+                             * Local attribute
+                             */
+                            Attribute attribute = new Attribute();
+                            attribute.name = name;
+                            attribute.value = value;
+                            if (forwardReference.attributes == null)
+                                forwardReference.attributes = new ArrayList();
+                            forwardReference.attributes.add(attribute);
+                        } else if (!SDOAnnotations.COMMONJ_SDO_NS.equals(nameSpace) || !ChangeSummaryStreamSerializer.REF_ATTRIBUTE.equals(name)
+                                && !ChangeSummaryStreamSerializer.UNSET.equals(name)) {
+                            /*
+                             * Qualified(global) attribute
+                             */
+                            QualifiedAttribute attribute = new QualifiedAttribute();
+                            attribute.name = name;
+                            attribute.value = value;
+                            attribute.nameSpace = nameSpace;
+                            if (forwardReference.qualifiedAttributes == null)
+                                forwardReference.qualifiedAttributes = new ArrayList();
+                            forwardReference.qualifiedAttributes.add(attribute);
+                        }
+                    } while (attributes != 0);
+                    while (START_ELEMENT == reader.nextTag()) {
+                        /*
+                         * Record property old value as element for end()
+                         */
+                        Tag tag = new Tag(reader);
+                        if (forwardReference.tags == null)
+                            forwardReference.tags = new ArrayList();
+                        forwardReference.tags.add(tag);
+                        tag.ref = ref();
+                        if (tag.ref != null)
+                            continue;
+                        Type xsi = typeXSI();
+                        if (xsi == null) {
+                            if (tag.nameSpace != null)
+                                tag.value = value(globalElementType(tag.nameSpace, tag.name.getLocalPart())); // TODO substitutionGroup type if null
+                            else if (tag.record(reader))
+                                break;
+                        } else
+                            tag.value = value(xsi);
+                    }
+                } else {
+                    /*
+                     * Resolved(back-referenced) modified DataObject
+                     */
+                    Type type = ((DataObject) referent).getType();
+                    Collection featureChanges = unsetProperties(referent, unset, type);
+                    do // what about xmlns="NS1" a1="qName" xmlns="NS2" a2="qName" ?
+                    {
+                        /*
+                         * Log property old value as attribute
+                         */
+                        String nameSpace = reader.getAttributeNamespace(--attributes), name = reader.getAttributeLocalName(attributes), value = reader
+                                .getAttributeValue(attributes);
+                        if (nameSpace == null)
+                            logAttributeChange(featureChanges, name, type, value, nameSpaces);
+                        else if (!SDOAnnotations.COMMONJ_SDO_NS.equals(nameSpace) || !ChangeSummaryStreamSerializer.REF_ATTRIBUTE.equals(name)
+                                && !ChangeSummaryStreamSerializer.UNSET.equals(name))
+                            logAttributeChange(featureChanges, nameSpace, name, type, value, nameSpaces);
+                    } while (attributes != 0);
+                    if (START_ELEMENT == reader.nextTag()) {
+                        ObjectChanges objectChanges = null;
+                        do {
+                            /*
+                             * Log property old value as element
+                             */
+                            String nameSpace = reader.getNamespaceURI(), name = reader.getLocalName();
+                            Property property = getProperty(nameSpace, name, type);
+                            boolean many = property.isMany();
+                            Object value;
+                            ref = ref();
+                            if (ref == null) {
+                                /*
+                                 * Contained property old value
+                                 */
+                                Type xsi = typeXSI();
+                                if (xsi != null)
+                                    value = value(xsi);
+                                else if (nameSpace == null)
+                                    value = value(reader);
+                                else {
+                                    xsi = globalElementType(nameSpace, name);
+                                    value = value(xsi == null ? propertyInSequence.getType() : xsi);
+                                }
+                            } else {
+                                /*
+                                 * Referenced child DataObject
+                                 */
+                                nameSpaces = reader.getNamespaceContext();
+                                reader.nextTag()/* END_ELEMENT */;
+                                value = referent(ref, nameSpaces);
+                                if (value == null) {
+                                    /*
+                                     * Forward-referenced(unresolved) child DataObject
+                                     */
+                                    if (!many) {
+                                        ElementChange elementChange = new ElementChange(ref, nameSpaces, property, propertyInSequence);
+                                        if (objectChanges == null) {
+                                            objectChanges = newObjectChanges(featureChanges);
+                                            objectChanges.newElementChanges();
+                                        } else if (objectChanges.elementChanges == null)
+                                            objectChanges.newElementChanges();
+                                        objectChanges.elementChanges.add(elementChange);
+                                        continue;
+                                    }
+                                    value = new Ref(ref, nameSpaces);
+                                }
+                            }
+                            if (many) {
+                                Collection list;
+                                if (objectChanges == null) {
+                                    objectChanges = newObjectChanges(featureChanges);
+                                    list = objectChanges.newList(property);
+                                } else if (objectChanges.lists == null)
+                                    list = objectChanges.newList(property);
+                                else
+                                    list = objectChanges.get(property);
+                                addPropertyChange(list, value, property);
+                            } else
+                                logPropertyChange(featureChanges, property, value);
+                        } while (START_ELEMENT == reader.nextTag());
+                    }
+                }
+            } while (START_ELEMENT == reader.nextTag());
+        }
+    }
+
+    static private boolean sequence(Object listChanges) {
+        return FeatureMapUtil.isFeatureMap(((FeatureChange) ((EStructuralFeature.Setting) listChanges).getEObject()).getFeature());
+    }
+
+    private ListChange createListChange(ChangeKind changeKind, int index, Collection listChanges) {
+        ListChange listChange = changeFactory.createListChange();
+        listChange.setKind(changeKind);
+        listChange.setIndex(index);
+        listChanges.add(listChange);
+        return listChange;
+    }
+
+    Collection add(Collection adds, int change, Collection listChanges, Object value) {
+        if (adds == null) {
+            ListChange listChange = createListChange(ChangeKind.ADD_LITERAL, change, listChanges);
+            adds = sequence(listChanges) ? listChange.getFeatureMapEntryValues() : listChange.getValues();
+        }
+        adds.add(value);
+        return adds;
+    }
+
+    private int remove(int change, Collection listChanges, List list, int begin, int end) {
+        ListChange listChange = createListChange(ChangeKind.REMOVE_LITERAL, change, listChanges);
+        if (sequence(listChanges)) {
+            Collection removes = listChange.getFeatureMapEntryValues();
+            do {
+                FeatureMap.Entry fme = (FeatureMap.Entry) list.get(begin);
+                removes.add(changeFactory.createFeatureMapEntry(fme.getEStructuralFeature(), fme.getValue()));
+            } while (++begin != end);
+            return begin;
+        }
+        Collection removes = listChange.getValues();
+        do
+            removes.add(list.get(begin));
+        while (++begin != end);
+        return begin;
+    }
+
+    int remove(int begin, int end, int change, Collection listChanges, List list) {
+        return begin == end ? begin : remove(change, listChanges, list, begin, end);
+    }
+
+    protected final void logManyChanges(PropertyMapChanges propertyMapChanges, EObject referent, Collection featureChanges) {
+        for (Iterator lists = propertyMapChanges.lists.entrySet().iterator(); lists.hasNext();) {
+            /*
+             * Compute ListChanges out of comparision of old and new list
+             */
+            Map.Entry entry = (Map.Entry) lists.next();
+            EStructuralFeature property = (EStructuralFeature) entry.getKey();
+            Iterator values = ((Collection) entry.getValue()).iterator(); // old list
+            Object value = referent.eGet(property);
+            List list = value instanceof FeatureMap.Internal.Wrapper ? ((FeatureMap.Internal.Wrapper) value).featureMap() : (List) value; // new
+            int change = 0;
+            FeatureChange featureChange = changeSettingFactory == null ? changeFactory.createFeatureChange() : (FeatureChange) changeSettingFactory
+                    .createChangeSummarySetting();
+            featureChange.setFeature(property);
+            Collection listChanges = featureChange.getListChanges(), adds = null;
+            featureChanges.add(featureChange);
+            if (property.getEType() instanceof EClass) {
+                /*
+                 * Log child DataObject changes
+                 */
+                int begin = 0, end = list.size();
+                while (values.hasNext()) {
+                    value = values.next();
+                    if (value.getClass() == Ref.class) {
+                        value = referent((Ref) value);
+                        if (value == null)
+                            continue;// report error?
+                    }
+                    // values.remove();
+                    for (int index = begin;/* true */; ++index)
+                        if (index == end) {
+                            adds = add(adds, change, listChanges, value);
+                            break;
+                        } else if (list.get(index) == value) // List#indexOf uses equals
+                        {
+                            begin = remove(begin, index, change, listChanges, list);
+                            ++begin;
+                            adds = null;
+                            break;
+                        }
+                    ++change;
+                }
+                remove(begin, end, change, listChanges, list);
+            } else if (FeatureMapUtil.isFeatureMap(property)) {
+                /*
+                 * Log Sequence changes
+                 */
+                int begin = 0, end = list.size();
+                while (values.hasNext()) {
+                    FeatureMapEntry featureMapEntry = (FeatureMapEntry) values.next();
+                    value = featureMapEntry.getValue();
+                    if (value.getClass() == Ref.class) {
+                        value = referent((Ref) value);
+                        if (value == null)
+                            continue;// report error?
+                    }
+                    // values.remove();
+                    Comparator equality;
+                    ETypedElement feature = featureMapEntry.getFeature();
+                    if (((Type) feature.getEType()).isDataType())
+                        if (value == null)
+                            equality = EQUAL_NULL;
+                        else
+                            equality = EQUAL;
+                    else
+                        equality = SAME;
+                    for (int index = begin;/* true */; ++index)
+                        if (index == end) {
+                            adds = add(adds, change, listChanges, featureMapEntry);
+                            break;
+                        } else {
+                            FeatureMap.Entry fme = (FeatureMap.Entry) list.get(index);
+                            if (feature == fme.getEStructuralFeature() && equality.compare(fme.getValue(), value) == 0) {
+                                begin = remove(begin, index, change, listChanges, list);
+                                ++begin;
+                                adds = null;
+                                break;
+                            }
+                        }
+                    ++change;
+                }
+                remove(begin, end, change, listChanges, list);
+            } else {
+                /*
+                 * Log simple value changes
+                 */
+                while (values.hasNext()) {
+                    value = values.next();
+                    // values.remove();
+                    int index = list.indexOf(value);
+                    switch (index) {
+                    case -1:
+                        adds = add(adds, change, listChanges, value);
+                        break;
+                    default:
+                        remove(change, listChanges, list, 0, index);
+                    case 0:
+                        list = list.subList(++index, list.size());
+                        adds = null;
+                    }
+                    ++change;
+                }
+                remove(0, list.size(), change, listChanges, list);
+            }
+        }
+    }
+
+    protected PropertyMapChanges propertyMapChanges/* = null */;
+
+    /**
+     * Imports ChangeSummary 2-2. Resolves forward references from {@link #begin} and resumes logging if necessary. If it's invoked from
+     * patching/resolving, try to make it last since logging may be turned on.
+     * 
+     * @see #begin
+     */
+    public final ChangeSummary end() throws XMLStreamException {
+        if (forwardReferences != null)
+            for (Iterator iterator = forwardReferences.iterator(); iterator.hasNext();) {
+                /*
+                 * Forward-referenced(unresolved) modified DataObject from begin(...)
+                 */
+                ForwardReference forwardReference = (ForwardReference) iterator.next();
+                EObject referent = referent(forwardReference);
+                if (referent == null)
+                    continue; // report error?
+                // iterator.remove();
+                Type type = ((DataObject) referent).getType();
+                Collection featureChanges = unsetProperties(referent, forwardReference.unset, type);
+                if (forwardReference.attributes != null)
+                    for (Iterator attributes = forwardReference.attributes.iterator(); attributes.hasNext();) {
+                        /*
+                         * Log property old value as local attribute from begin(...)
+                         */
+                        Attribute attribute = (Attribute) attributes.next();
+                        logAttributeChange(featureChanges, attribute.name, type, attribute.value, forwardReference.nameSpaces);
+                    }
+                if (forwardReference.qualifiedAttributes != null)
+                    for (Iterator attributes = forwardReference.qualifiedAttributes.iterator(); attributes.hasNext();) {
+                        /*
+                         * Log property old value as qualified/global attribute from begin(...)
+                         */
+                        QualifiedAttribute attribute = (QualifiedAttribute) attributes.next();
+                        logAttributeChange(featureChanges, attribute.nameSpace, attribute.name, type, attribute.value, forwardReference.nameSpaces);
+                    }
+                if (forwardReference.tags != null) {
+                    if (propertyMapChanges != null)
+                        propertyMapChanges.lists.clear();
+                    for (Iterator tags = forwardReference.tags.iterator(); tags.hasNext();) {
+                        /*
+                         * Log property old value as element from begin(...)
+                         */
+                        Tag tag = (Tag) tags.next();
+                        Property property = getProperty(tag.nameSpace, tag.name.getLocalPart(), type);
+                        if (tag.ref != null)
+                            tag.value = referent(tag.ref, tag.nameSpaceContext);
+                        // if (tag.value == null) report error?
+                        else if (tag.events != null)
+                            tag.value = value(play(tag));
+                        if (property.isMany()) {
+                            Collection list;
+                            if (propertyMapChanges == null) {
+                                propertyMapChanges = new PropertyMapChanges();
+                                list = propertyMapChanges.newList(property);
+                            } else
+                                list = propertyMapChanges.get(property);
+                            addPropertyChange( list, tag.value, property);
+                        } else
+                            logPropertyChange(featureChanges, property, tag.value);
+                    }
+                    if (propertyMapChanges != null)
+                        logManyChanges(propertyMapChanges, referent, featureChanges);
+                }
+            }
+        if (objectChangesCollection != null)
+            for (Iterator iterator = objectChangesCollection.iterator(); iterator.hasNext();) {
+                /*
+                 * Forward-referenced(unresolved) child DataObject from begin(...)
+                 */
+                ObjectChanges objectChanges = (ObjectChanges) iterator.next();
+                if (objectChanges.elementChanges != null)
+                    for (Iterator elementChanges = objectChanges.elementChanges.iterator(); elementChanges.hasNext();) {
+                        ElementChange elementChange = (ElementChange) elementChanges.next();
+                        Object value = referent(elementChange);
+                        if (value == null)
+                            continue; // report error?
+                        // iterator.remove();
+                        logPropertyChange(objectChanges.featureChanges, elementChange.containing, elementChange.containment, value);
+                    }
+                if (objectChanges.lists != null)
+                    logManyChanges(objectChanges, (EObject) ((Map.Entry) ((EStructuralFeature.Setting) objectChanges.featureChanges).getEObject())
+                            .getKey(), objectChanges.featureChanges);
+            }
+        if (logging)
+            changeSummary.resumeLogging();
+        return changeSummary;
+    }
+}
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/util/resource/ChangeSummaryStreamSerializer.java b/impl/src/main/java/org/apache/tuscany/sdo/util/resource/ChangeSummaryStreamSerializer.java
index bb598be..ef5af8a 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/util/resource/ChangeSummaryStreamSerializer.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/util/resource/ChangeSummaryStreamSerializer.java
@@ -1,690 +1,690 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.util.resource;

-

-import java.util.Collection;

-import java.util.Iterator;

-import java.util.List;

-import java.util.Map;

-

-import javax.xml.namespace.NamespaceContext;

-import javax.xml.namespace.QName;

-import javax.xml.stream.XMLOutputFactory;

-import javax.xml.stream.XMLStreamException;

-import javax.xml.stream.XMLStreamReader;

-import javax.xml.stream.XMLStreamWriter;

-

-import org.apache.tuscany.sdo.SDOPackage;

-import org.apache.tuscany.sdo.helper.HelperContextImpl;

-import org.apache.tuscany.sdo.helper.SDOAnnotations;

-import org.apache.tuscany.sdo.helper.XSDHelperImpl;

-import org.apache.tuscany.sdo.impl.ChangeSummaryImpl;

-import org.apache.tuscany.sdo.model.ModelFactory;

-import org.apache.tuscany.sdo.model.impl.ModelFactoryImpl;

-import org.apache.tuscany.sdo.util.SDOUtil;

-import org.eclipse.emf.common.util.EMap;

-import org.eclipse.emf.ecore.EClassifier;

-import org.eclipse.emf.ecore.EDataType;

-import org.eclipse.emf.ecore.EObject;

-import org.eclipse.emf.ecore.EStructuralFeature;

-import org.eclipse.emf.ecore.change.ChangeDescription;

-import org.eclipse.emf.ecore.change.ChangeKind;

-import org.eclipse.emf.ecore.change.FeatureChange;

-import org.eclipse.emf.ecore.change.ListChange;

-import org.eclipse.emf.ecore.util.EcoreUtil;

-import org.eclipse.emf.ecore.util.ExtendedMetaData;

-import org.eclipse.emf.ecore.util.FeatureMap;

-import org.eclipse.emf.ecore.util.FeatureMapUtil;

-import org.eclipse.emf.ecore.xmi.XMLResource;

-

-import commonj.sdo.ChangeSummary;

-import commonj.sdo.DataObject;

-import commonj.sdo.Property;

-import commonj.sdo.helper.XSDHelper;

-

-/**

- * ChangeSummary StAX Serializer whose output conforms to the SDO Java/C++/PHP specifications. The instance isn't thread-safe, however it's safe to

- * use the instance any times on the same thread.

- */

-public class ChangeSummaryStreamSerializer {

-    private XMLStreamWriter writer;

-

-    private String writeNamespace(String prefix, String nameSpace) throws XMLStreamException {

-        writer.writeNamespace(prefix, nameSpace);

-        writer.setPrefix(prefix, nameSpace);

-        return prefix;

-    }

-

-    private int nsPrefixSuffix;

-

-    private String prefix(String nameSpace, String preference) throws XMLStreamException {

-        if (preference != null) {

-            String bound = writer.getNamespaceContext().getNamespaceURI(preference);

-            if (bound == null) {

-                String prefix = writer.getPrefix(nameSpace);

-                return prefix == null ? writeNamespace(preference, nameSpace) : prefix/* or null */;

-            }

-            if (bound.equals(nameSpace))

-                return preference;

-        }

-        Object automaticNsPrefix = writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);

-        if (automaticNsPrefix != null && automaticNsPrefix.getClass() == Boolean.class // faster than instanceof since Boolean is final

-                && ((Boolean) automaticNsPrefix).booleanValue())

-            return null;

-        String prefix = writer.getPrefix(nameSpace);

-        if (prefix != null)

-            return prefix; // or null

-        NamespaceContext nameSpaces = writer.getNamespaceContext();

-        do

-            prefix = "CS" + nsPrefixSuffix++;

-        while (nameSpaces.getNamespaceURI(prefix) != null);

-        return writeNamespace(prefix, nameSpace);

-    }

-

-    void writeGlobalAttribute(String prefix, String nameSpace, String name, String value) throws XMLStreamException {

-        prefix = prefix(nameSpace, prefix);

-        if (prefix == null)

-            writer.writeAttribute(nameSpace, name, value);

-        else

-            writer.writeAttribute(prefix, nameSpace, name, value);

-    }

-    

-    XSDHelper xsdHelper;

-

-    protected final void writeAttribute(Property property, String value) throws XMLStreamException {

-        String name = xsdHelper.getLocalName(property), nameSpace = xsdHelper.getNamespaceURI(property);

-        // TODO "" for no-NameSpace global attribute

-        if (nameSpace == null)

-            writer.writeAttribute(name, value);

-        else

-            writeGlobalAttribute(null, nameSpace, name, value);

-    }

-

-    private String lineBreak, indent, margin;

-

-    private int nest;

-

-    private void breakLine() throws XMLStreamException {

-        writer.writeCharacters(lineBreak);

-

-        if (margin != null)

-            writer.writeCharacters(margin);

-

-        if (indent != null)

-            for (int count = nest; count != 0; --count)

-                writer.writeCharacters(indent);

-    }

-

-    private Map options;

-

-    static private final String STRING_OPTION = "String option";

-

-    void startElement() throws XMLStreamException {

-        if (options == null)

-            return;

-        if (lineBreak == STRING_OPTION)

-            lineBreak = (String) options.get(SDOUtil.XML_SAVE_LineBreak);

-        if (lineBreak == null)

-            return;

-        if (margin == STRING_OPTION)

-            margin = (String) options.get(SDOUtil.XML_SAVE_MARGIN);

-        if (indent == STRING_OPTION)

-            indent = (String) options.get(SDOUtil.XML_SAVE_INDENT);

-        breakLine();

-    }

-

-    void writeStartElement(String prefix, String nameSpace, String name) throws XMLStreamException {

-        startElement();

-        if (nameSpace == null)

-            writer.writeStartElement(name);

-        else {

-            prefix = prefix(nameSpace, prefix);

-            if (prefix == null)

-                writer.writeStartElement(nameSpace, name);

-            else

-                writer.writeStartElement(prefix, name, nameSpace);

-        }

-    }

-

-    void writeStartElement(Property property) throws XMLStreamException {

-        ++nest;

-        writeStartElement(null, xsdHelper.getNamespaceURI(property),// TODO "" for no-NameSpace global element

-                xsdHelper.getLocalName(property));

-    }

-

-    static protected final String CREATE_ATTRIBUTE = "create", DELETE_ATTRIBUTE = "delete", LOGGING_ATTRIBUTE = "logging", REF_ATTRIBUTE = "ref", UNSET = "unset";

-

-    private StringBuffer step(String nameSpace, String name, StringBuffer path) throws XMLStreamException {

-        if (nameSpace != null) {

-            nameSpace = writer.getPrefix(nameSpace);

-            if (nameSpace != null && nameSpace.length() != 0)

-                return path.append(nameSpace).append(':').append(name); // *:name[namespace-uri()='nameSpace']

-        }

-        return path.append(name); 

-    }

-

-    private StringBuffer step(Property containmentProperty, StringBuffer path) throws XMLStreamException {

-        return step(xsdHelper.getNamespaceURI(containmentProperty),// TODO "" for no-NameSpace global element

-                xsdHelper.getLocalName(containmentProperty), path);

-    }

-

-    private StringBuffer step(Property containmentProperty) throws XMLStreamException {

-        return step(containmentProperty, new StringBuffer());

-    }

-

-    private DataObject dataObject;

-

-    private StringBuffer step(Object container) throws XMLStreamException {

-        Property containmentProperty = dataObject.getContainmentProperty();

-        StringBuffer step = step(containmentProperty);

-        if (containmentProperty.isMany() || ((EObject) dataObject).eContainingFeature() != containmentProperty)

-            step.append('[').append(((DataObject) container).getList(containmentProperty).indexOf(dataObject) + 1).append(']');

-        return step;

-    }

-

-    private String pathRootObject;

-    private DataObject rootObject;

-

-    private EObject container(EObject object) {

-        final EObject container = object.eContainer();

-        if (!(container instanceof DataObject))

-            return null;

-        String name = extendedMetaData.getName(container.eClass());

-        return name != null && name.length() == 0 // DocumentRoot

-             ? null : container;

-    }

-

-    private String path() throws XMLStreamException {

-        if (pathRootObject == STRING_OPTION)

-            pathRootObject = options == null ? null : (String) options.get(OPTION_RootObject_PATH);

-        if (pathRootObject != null && dataObject == rootObject)

-            return null;

-        EObject container = container((EObject) dataObject);

-        if (container == null)

-            return null;

-        StringBuffer step = step(container);

-        while (true) {

-            String path = step.toString();

-            dataObject = (DataObject) container;

-            if (pathRootObject != null && container == rootObject)

-                return path;

-            container = container(container);

-            if (container == null)

-                return path;

-            step = step(container).append('/').append(path);

-        }

-    }

-

-    /*

-     * not to support DataGraph 3-1 private org.eclipse.emf.ecore.resource.Resource rootResource;

-     */

-

-    protected String rootElementNS;

-

-    String rootElementName;

-

-    ExtendedMetaData extendedMetaData;

-

-    protected final String rootElementName() {

-        if (rootElementNS != null)

-            return rootElementName;

-        QName rootElement = (QName) options.get(OPTION_ROOT_ELEMENT);

-        if (rootElement != null) {

-            rootElementNS = rootElement.getNamespaceURI();

-            return rootElementName = rootElement.getLocalPart();

-        }

-        EStructuralFeature element = ((EObject) rootObject).eContainingFeature();

-        if (element == null) {

-            rootElementNS = "";

-            return rootElementName = "descendant-or-self::node()";

-        }

-        rootElementNS = extendedMetaData.getNamespace(element);

-        if (rootElementNS == null)

-            rootElementNS = "";

-        return rootElementName = extendedMetaData.getName(element);

-    }

-

-    String ref() throws XMLStreamException {

-        /*

-         * not to support DataGraph 3-2 if (rootResource != null) return rootResource.getURIFragment((EObject) dataObject);

-         */

-        String id = EcoreUtil.getID((EObject) dataObject);

-        if (id != null)

-            return id;

-        id = path();

-        if (pathRootObject == null)

-            return id == null ? "#/" + rootElementName() // descendant-or-self::node()

-            : "#//" + id;

-        return id == null ? pathRootObject/* + "."*/ : pathRootObject + id;

-    }

-

-    void writeRef(String ref) throws XMLStreamException {

-        writer.writeAttribute(SDOAnnotations.COMMONJ_SDO_NS, REF_ATTRIBUTE, ref);

-    }

-

-    void writeRef() throws XMLStreamException {

-        writeRef(ref());

-    }

-

-    void writeEndElement(String lineBreak) throws XMLStreamException {

-        if (lineBreak != null)

-            breakLine();

-        writer.writeEndElement();

-        --nest;

-    }

-

-    private StringBuffer pathDeleted/* = null */;

-

-    private Collection modifiedDataObjects;

-    

-    private int lengthDeleted;

-

-    private String changeSummaryElementNS, changeSummaryElementName;

-

-    private ChangeSummary changeSummary;

-

-    protected boolean skipDeletedModification(DataObject modifiedDataObject) {

-        return changeSummary.isDeleted(modifiedDataObject);

-    }

-

-    String refDeleted() throws XMLStreamException {

-        String id = EcoreUtil.getID((EObject) dataObject);

-        if (id != null)

-            return id;

-        id = path(); // "dataObject" is updated too!!

-        DataObject deletedDataObject = dataObject;

-        

-        /*

-         * construct "#//...changeSummary/"

-         *  output: pathDeleted

-         */

-        if (lengthDeleted == -1) {

-            String path = pathRootObject == null ? "#//" : pathRootObject;

-            if (pathDeleted == null)

-                pathDeleted = new StringBuffer(path);

-            else

-                pathDeleted.replace(0, pathDeleted.length(), path);

-            dataObject = rootObject;

-            path = path();

-            if (path != null)

-                pathDeleted.append(path).append('/');

-            step(changeSummaryElementNS, changeSummaryElementName, pathDeleted).append('/');

-            lengthDeleted = pathDeleted.length();

-        } else

-            pathDeleted.delete(lengthDeleted, pathDeleted.length());

-        

-        dataObject = changeSummary.getOldContainer(deletedDataObject);

-        Property containmentProperty = dataObject.getContainmentProperty();

-        String name = containmentProperty == null ? rootElementName() : xsdHelper.getLocalName(containmentProperty);

-        int index = 1;

-        for (Iterator iterator = modifiedDataObjects.iterator(); iterator.hasNext();) {

-            DataObject modifiedDataObject = (DataObject) iterator.next();

-            if (skipDeletedModification(modifiedDataObject))

-                continue;

-            if (modifiedDataObject == dataObject)

-                break;

-            Property property = modifiedDataObject.getContainmentProperty();

-            if (property == containmentProperty || name.equals(property == null ? rootElementName() : xsdHelper.getLocalName(property)))

-                ++index;

-        }

-        pathDeleted/*.append("*:")*/.append(name).append('[').append(index).append("]/");

-        containmentProperty = changeSummary.getOldContainmentProperty(deletedDataObject);

-        // assert containmentProperty != null;

-        step(containmentProperty, pathDeleted);

-        Object f;

-        if (containmentProperty.isMany()

-                || (f = extendedMetaData.getAffiliation(((EObject) dataObject).eClass(), (EStructuralFeature) containmentProperty)) != null

-                && f != containmentProperty)

-            pathDeleted.append('[').append(

-                    ((List) changeSummary.getOldValue(dataObject, containmentProperty).getValue()).indexOf(deletedDataObject) + 1).append(']');

-        if (id != null)

-            pathDeleted.append('/').append(id);

-        return pathDeleted.toString();

-    }

-

-    static String convertToString(Property property, Object value) {

-        return EcoreUtil.convertToString((EDataType) property.getType(), value);

-    }

-

-    void writeRefDeleted() throws XMLStreamException {

-        writeRef(refDeleted());

-    }

-

-    protected final void writeDeletedObject(Property property) throws XMLStreamException {

-      ++nest;

-      startElement();

-      --nest;

-      DataObject oldDataObject = ((ChangeSummaryImpl)changeSummary).getOldDataObject(dataObject);

-      XMLStreamReader reader = new DataObjectXMLStreamReader(property, oldDataObject, null, xsdHelper);

-      new XMLStreamSerializer().serialize(new XMLDocumentStreamReader(reader), writer);

-    }

-

-    static public final Object ChangeSummary_TYPE = ((ModelFactoryImpl) ModelFactory.INSTANCE).getChangeSummaryType();

-

-    Collection deletedDataObjects;

-

-    protected final void writeElement(Object value, Property property) throws XMLStreamException {

-        if (value == null) {

-            writeStartElement(property);

-            writeGlobalAttribute(ExtendedMetaData.XSI_PREFIX, ExtendedMetaData.XSI_URI, XMLResource.NIL, "true");

-            writeEndElement(null);

-        } else if (value instanceof DataObject) {

-            dataObject = (DataObject) value;

-            if (!changeSummary.isDeleted(dataObject)) {

-                writeStartElement(property);

-                writeRef();

-                writeEndElement(null);

-            } else if (property.isContainment() && deletedDataObjects.contains(dataObject)) {

-                writeDeletedObject(property);

-            } else {

-                writeStartElement(property);

-                writeRefDeleted();

-                writeEndElement(null);

-            }

-        } else {

-            Object type = property.getType();

-            if (type == ChangeSummary_TYPE)

-                return;

-            writeStartElement(property);

-            writer.writeCharacters(EcoreUtil.convertToString((EDataType) type, value));

-            writeEndElement(null);

-        }

-    }

-    

-    protected final void writeElement(Object value) throws XMLStreamException {

-        FeatureMap.Entry entry = (FeatureMap.Entry) value;

-        writeElement(entry.getValue(), (Property)entry.getEStructuralFeature());

-    }

-

-    static protected List optimize(List values, Object featureChange, int size) {

-        int fromIndex = size, toIndex = 0;

-        for (Iterator changes = ((FeatureChange) featureChange).getListChanges().iterator(); changes.hasNext();) {

-            ListChange change = (ListChange) changes.next();

-            Object kind = change.getKind();

-            if (kind == ChangeKind.MOVE_LITERAL)

-                return values;

-            int index = change.getIndex();

-            if (kind == ChangeKind.ADD_LITERAL) {

-                if (index == 0) {

-                    fromIndex = 0;

-                    if (toIndex == 0)

-                        toIndex = 1;

-                } else {

-                    int to = index;

-                    if (--index < fromIndex)

-                        fromIndex = index;

-                    if (++to > toIndex)

-                        toIndex = to;

-                    else if (to < toIndex)

-                        ++toIndex;

-                }

-                ++size;

-            } else {

-                --size;

-                if (index < fromIndex)

-                    fromIndex = index;

-                if (index < toIndex)

-                    --toIndex;

-                else if (index > toIndex && index != size)

-                    toIndex = index;

-            }

-        }

-        return values.subList(fromIndex, toIndex);

-    }

-    

-    static protected final Object CHANGE_SUMMARY = SDOPackage.eINSTANCE.getChangeSummary();

-

-    /**

-     * Root Object path String such as "#", etc. Absent/null is the default (automatic computation)

-     */

-    static public final String OPTION_RootObject_PATH = "RootObject path",

-    /**

-     * Boolean to optimize sequence/list/array. Absent/null/Boolean.FALSE is the default (no optimization)

-     */

-    OPTION_OPTIMIZE_LIST = "optimize sequence/list/array",

-    /**

-     * Element QName if the changeSummary Root Object is a XML root; the NameSpace can be empty, never null; the prefix is ignored.

-     * Absent/null is the default (automatic computation from DocumentRoot if any)

-     */

-    OPTION_ROOT_ELEMENT = "Root Element";

-

-    /**

-     * Exports ChangeSummary

-     * 

-     * @param changeSummary

-     *            Never null

-     * @param changeSummaryElement

-     *            changeSummary element; the NameSpace can be empty if no NameSpace, or null if local element; the prefix can be null(no preference)

-     * @param writer

-     *            Never null

-     * @param options

-     *            {@link SDOUtil#XML_SAVE_LineBreak} (absence/null is the default i.e. no Line Breaking), {@link SDOUtil#XML_SAVE_INDENT} (absence/null is the default i.e. no indentation), {@link SDOUtil#XML_SAVE_MARGIN}, {@link #OPTION_RootObject_PATH}, {@link #OPTION_OPTIMIZE_LIST} and XMLResource.OPTION_EXTENDED_META_DATA; can be null or empty

-     */

-    public final void saveChangeSummary(ChangeSummary changeSummary, QName changeSummaryElement, XMLStreamWriter writer, Map options)

-            throws XMLStreamException {

-        /*

-         * 6-1. Group created, deleted and modified DataObjects

-         *  input: changeSummary output: createdDataObjects, deletedDataObjects & modifiedDataObjects

-         *  implement: careful if compute from changeSummary.getChangedDataObjects() since it also includes children of deleted objects (thank Frank)

-         */

-        if (changeSummary.isLogging())

-            ((ChangeSummaryImpl) changeSummary).summarize();

-        ChangeDescription changeDescription = (ChangeDescription) changeSummary;

-        Iterator createdDataObjects = changeDescription.getObjectsToDetach().iterator();

-        deletedDataObjects = changeDescription.getObjectsToAttach();

-        EMap objectChanges = changeDescription.getObjectChanges();

-        modifiedDataObjects = objectChanges.keySet(); // may contain DO(s) from createdDataObjects and/or deletedDataObjects

-

-        /*

-         * 6-2. Prepare to compute (X)Path

-         *  input: changeSummary

-         *  output: rootResource

-         */

-        /*not to support DataGraph 3-3

-        Object dataGraph = changeSummary.getDataGraph();

-        if (dataGraph == null) {

-            DataObject rootObject = changeSummary.getRootObject();

-            // assert rootObject != null;

-            rootResource = rootObject.getContainer() == null ? ((EObject) rootObject).eResource() // Can be null since this *StAX* writer does NOT

-                    // require rootObject contained by an *EMF* Resource

-                    : null; // eResource() direct content may not necessarily always be the XML document

-        } else

-            // assert dataGraph instanceof DataGraphImpl;

-            rootResource = ((org.apache.tuscany.sdo.impl.DataGraphImpl) dataGraph).getRootResource(); */

-

-        /*

-         * 6-2. Start ChangeSummary element

-         *  input: writer, options, elementCS, changeSummary & changeDescription (6-1)

-         */

-        nsPrefixSuffix = 0;

-        this.writer = writer;

-        this.options = options;

-        lineBreak = "";

-        indent = margin = pathRootObject = STRING_OPTION;

-        nest = 0;

-        changeSummaryElementNS = changeSummaryElement.getNamespaceURI();

-        changeSummaryElementName = changeSummaryElement.getLocalPart();

-        writeStartElement(changeSummaryElement.getPrefix(), changeSummaryElementNS, changeSummaryElementName);

-        lineBreak = STRING_OPTION;

-        rootObject = changeSummary.getRootObject();

-        extendedMetaData = (ExtendedMetaData) options.get(XMLResource.OPTION_EXTENDED_META_DATA);

-        if (extendedMetaData == null)

-        {

-            extendedMetaData = ExtendedMetaData.INSTANCE;

-            xsdHelper = XSDHelper.INSTANCE;

-        }

-        else{

-        	xsdHelper = (new HelperContextImpl(extendedMetaData, false)).getXSDHelper();

-        }

-        Property declaration = changeSummaryElementNS == null

-                             ? rootObject.getType().getProperty(changeSummaryElementName)

-                             : xsdHelper.getGlobalProperty(changeSummaryElementNS, changeSummaryElementName, true);

-        if (declaration != null)

-        {

-            EClassifier type = changeDescription.eClass();

-            if (type != declaration.getType() && type != CHANGE_SUMMARY)

-                writeGlobalAttribute(ExtendedMetaData.XSI_PREFIX, ExtendedMetaData.XSI_URI, XMLResource.TYPE, new StringBuffer(prefix(extendedMetaData.getNamespace(type), null))

-                        .append(':').append(extendedMetaData.getName(type)).toString());

-        }

-        

-        /*

-         * 6-3. "create" attribute

-         *  input: createdDataObjects (6-1), rootResource (6-2), changeSummary & writer

-         */

-        rootElementNS = null;

-        this.changeSummary = changeSummary;

-        if (createdDataObjects.hasNext()) {

-            StringBuffer buffer = new StringBuffer();

-            while (true) {

-                dataObject = (DataObject) createdDataObjects.next();

-                buffer.append(ref());

-                if (!createdDataObjects.hasNext())

-                    break;

-                buffer.append(' ');

-            }

-            writer.writeAttribute(CREATE_ATTRIBUTE, buffer.toString());

-        }

-

-        /*

-         * 6-4. "delete" attribute

-         *  input: deletedDataObjects (6-1), modifiedDataObjects (6-1) & writer

-         */

-        Iterator iterator = deletedDataObjects.iterator();

-        if (iterator.hasNext()) {

-            lengthDeleted = -1;

-            StringBuffer buffer = null;

-            do {

-                dataObject = (DataObject) iterator.next();

-                if (skipDeletedModification(changeSummary.getOldContainer(dataObject)))

-                    continue;

-                if (buffer == null)

-                    buffer = new StringBuffer();

-                else

-                    buffer.append(' ');

-                buffer.append(refDeleted());

-            } while (iterator.hasNext());

-            writer.writeAttribute(DELETE_ATTRIBUTE, buffer.toString());

-        }

-

-        /*

-         * 6-5. "logging" attribute

-         *  input: changeSummary & writer

-         */

-        writer.writeAttribute(LOGGING_ATTRIBUTE, changeSummary.isLogging() ? "true" : "false");

-

-        /*

-         * 6-6. Modified DataObjects

-         *  input: modifiedDataObjects (6-1), rootResource (6-2), changeSummary & writer

-         */

-        iterator = modifiedDataObjects.iterator();

-        if (iterator.hasNext()) {

-            boolean optimizeList;

-            if (options == null)

-                optimizeList = false;

-            else

-            {

-                Object option = options.get(OPTION_OPTIMIZE_LIST);

-                optimizeList = option == null ? false : ((Boolean)option).booleanValue();

-            }

-            prefix(SDOAnnotations.COMMONJ_SDO_NS, SDOPackage.eNS_PREFIX);

-            do {

-                DataObject dataObject = (DataObject) iterator.next();

-                if (skipDeletedModification(dataObject))

-                    continue;

-                Property containmentProperty = dataObject.getContainmentProperty();

-                if (containmentProperty == null) {

-                    ++nest;

-                    startElement();

-                    rootElementName();

-                    writer.writeStartElement(rootElementNS, rootElementName);

-                } else

-                    writeStartElement(containmentProperty);

-                this.dataObject = dataObject;

-                writeRef();

-

-                String lineBreak = null;

-                Collection oldValues = (Collection) objectChanges.get(dataObject); // changeSummary.getOldValues repeats Sequence changes

-                Iterator settings = oldValues.iterator();

-                if (settings.hasNext()) {

-                    do {

-                        ChangeSummary.Setting oldValue = (ChangeSummary.Setting) settings.next();

-                        if (oldValue.isSet())

-                            continue;

-                        StringBuffer unset = step(oldValue.getProperty());

-                        while (settings.hasNext()) {

-                            oldValue = (ChangeSummary.Setting) settings.next();

-                            if (!oldValue.isSet())

-                                step(oldValue.getProperty(), unset.append(' '));

-                        }

-                        writer.writeAttribute(SDOAnnotations.COMMONJ_SDO_NS, UNSET, unset.toString());

-                        break;

-                    } while (settings.hasNext());

-                    for (settings = oldValues.iterator(); settings.hasNext();) {

-                        ChangeSummary.Setting oldValue = (ChangeSummary.Setting) settings.next();

-                        Property property = oldValue.getProperty();

-                        if (oldValue.isSet() && xsdHelper.isAttribute(property))

-                            // assert ! property.isMany();

-                            writeAttribute(property, convertToString(property, oldValue.getValue()));

-                    }

-                    for (settings = oldValues.iterator(); settings.hasNext();) {

-                        ChangeSummary.Setting oldValue = (ChangeSummary.Setting) settings.next();

-                        Property property = oldValue.getProperty();

-                        if (!xsdHelper.isAttribute(property))

-                            if (property.isMany()) {

-                                Object value = oldValue.getValue();

-                                List list = (List) value;

-                                if (FeatureMapUtil.isFeatureMap((EStructuralFeature) property)) {

-                                    if (optimizeList)

-                                        list = optimize(list, oldValue, dataObject.getSequence(property).size());

-                                    Iterator values = list.iterator();

-                                    if (!values.hasNext())

-                                        continue;

-                                    do

-                                        writeElement(values.next());

-                                    while (values.hasNext());

-                                } else {

-                                    if (optimizeList)

-                                        list = optimize(list, oldValue, dataObject.getList(property).size());

-                                    Iterator values = list.iterator();

-                                    if (!values.hasNext())

-                                        continue;

-                                    do

-                                        writeElement(values.next(), property);

-                                    while (values.hasNext());

-                                }

-                                lineBreak = this.lineBreak;

-                            } else if (oldValue.isSet()) {

-                                Object value = oldValue.getValue();

-                                if (value instanceof FeatureMap.Entry)

-                                    writeElement(value);

-                                else

-                                    writeElement(value, property);

-                                lineBreak = this.lineBreak;

-                            }

-                    }

-                }

-                writeEndElement(lineBreak);

-            } while (iterator.hasNext());

-            writeEndElement(lineBreak);

-        } else

-            writeEndElement(null);

-        writer.flush();

-    }

-}

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.util.resource;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.apache.tuscany.sdo.SDOPackage;
+import org.apache.tuscany.sdo.helper.HelperContextImpl;
+import org.apache.tuscany.sdo.helper.SDOAnnotations;
+import org.apache.tuscany.sdo.helper.XSDHelperImpl;
+import org.apache.tuscany.sdo.impl.ChangeSummaryImpl;
+import org.apache.tuscany.sdo.model.ModelFactory;
+import org.apache.tuscany.sdo.model.impl.ModelFactoryImpl;
+import org.apache.tuscany.sdo.util.SDOUtil;
+import org.eclipse.emf.common.util.EMap;
+import org.eclipse.emf.ecore.EClassifier;
+import org.eclipse.emf.ecore.EDataType;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.change.ChangeDescription;
+import org.eclipse.emf.ecore.change.ChangeKind;
+import org.eclipse.emf.ecore.change.FeatureChange;
+import org.eclipse.emf.ecore.change.ListChange;
+import org.eclipse.emf.ecore.util.EcoreUtil;
+import org.eclipse.emf.ecore.util.ExtendedMetaData;
+import org.eclipse.emf.ecore.util.FeatureMap;
+import org.eclipse.emf.ecore.util.FeatureMapUtil;
+import org.eclipse.emf.ecore.xmi.XMLResource;
+
+import commonj.sdo.ChangeSummary;
+import commonj.sdo.DataObject;
+import commonj.sdo.Property;
+import commonj.sdo.helper.XSDHelper;
+
+/**
+ * ChangeSummary StAX Serializer whose output conforms to the SDO Java/C++/PHP specifications. The instance isn't thread-safe, however it's safe to
+ * use the instance any times on the same thread.
+ */
+public class ChangeSummaryStreamSerializer {
+    private XMLStreamWriter writer;
+
+    private String writeNamespace(String prefix, String nameSpace) throws XMLStreamException {
+        writer.writeNamespace(prefix, nameSpace);
+        writer.setPrefix(prefix, nameSpace);
+        return prefix;
+    }
+
+    private int nsPrefixSuffix;
+
+    private String prefix(String nameSpace, String preference) throws XMLStreamException {
+        if (preference != null) {
+            String bound = writer.getNamespaceContext().getNamespaceURI(preference);
+            if (bound == null) {
+                String prefix = writer.getPrefix(nameSpace);
+                return prefix == null ? writeNamespace(preference, nameSpace) : prefix/* or null */;
+            }
+            if (bound.equals(nameSpace))
+                return preference;
+        }
+        Object automaticNsPrefix = writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
+        if (automaticNsPrefix != null && automaticNsPrefix.getClass() == Boolean.class // faster than instanceof since Boolean is final
+                && ((Boolean) automaticNsPrefix).booleanValue())
+            return null;
+        String prefix = writer.getPrefix(nameSpace);
+        if (prefix != null)
+            return prefix; // or null
+        NamespaceContext nameSpaces = writer.getNamespaceContext();
+        do
+            prefix = "CS" + nsPrefixSuffix++;
+        while (nameSpaces.getNamespaceURI(prefix) != null);
+        return writeNamespace(prefix, nameSpace);
+    }
+
+    void writeGlobalAttribute(String prefix, String nameSpace, String name, String value) throws XMLStreamException {
+        prefix = prefix(nameSpace, prefix);
+        if (prefix == null)
+            writer.writeAttribute(nameSpace, name, value);
+        else
+            writer.writeAttribute(prefix, nameSpace, name, value);
+    }
+    
+    XSDHelper xsdHelper;
+
+    protected final void writeAttribute(Property property, String value) throws XMLStreamException {
+        String name = xsdHelper.getLocalName(property), nameSpace = xsdHelper.getNamespaceURI(property);
+        // TODO "" for no-NameSpace global attribute
+        if (nameSpace == null)
+            writer.writeAttribute(name, value);
+        else
+            writeGlobalAttribute(null, nameSpace, name, value);
+    }
+
+    private String lineBreak, indent, margin;
+
+    private int nest;
+
+    private void breakLine() throws XMLStreamException {
+        writer.writeCharacters(lineBreak);
+
+        if (margin != null)
+            writer.writeCharacters(margin);
+
+        if (indent != null)
+            for (int count = nest; count != 0; --count)
+                writer.writeCharacters(indent);
+    }
+
+    private Map options;
+
+    static private final String STRING_OPTION = "String option";
+
+    void startElement() throws XMLStreamException {
+        if (options == null)
+            return;
+        if (lineBreak == STRING_OPTION)
+            lineBreak = (String) options.get(SDOUtil.XML_SAVE_LineBreak);
+        if (lineBreak == null)
+            return;
+        if (margin == STRING_OPTION)
+            margin = (String) options.get(SDOUtil.XML_SAVE_MARGIN);
+        if (indent == STRING_OPTION)
+            indent = (String) options.get(SDOUtil.XML_SAVE_INDENT);
+        breakLine();
+    }
+
+    void writeStartElement(String prefix, String nameSpace, String name) throws XMLStreamException {
+        startElement();
+        if (nameSpace == null)
+            writer.writeStartElement(name);
+        else {
+            prefix = prefix(nameSpace, prefix);
+            if (prefix == null)
+                writer.writeStartElement(nameSpace, name);
+            else
+                writer.writeStartElement(prefix, name, nameSpace);
+        }
+    }
+
+    void writeStartElement(Property property) throws XMLStreamException {
+        ++nest;
+        writeStartElement(null, xsdHelper.getNamespaceURI(property),// TODO "" for no-NameSpace global element
+                xsdHelper.getLocalName(property));
+    }
+
+    static protected final String CREATE_ATTRIBUTE = "create", DELETE_ATTRIBUTE = "delete", LOGGING_ATTRIBUTE = "logging", REF_ATTRIBUTE = "ref", UNSET = "unset";
+
+    private StringBuffer step(String nameSpace, String name, StringBuffer path) throws XMLStreamException {
+        if (nameSpace != null) {
+            nameSpace = writer.getPrefix(nameSpace);
+            if (nameSpace != null && nameSpace.length() != 0)
+                return path.append(nameSpace).append(':').append(name); // *:name[namespace-uri()='nameSpace']
+        }
+        return path.append(name); 
+    }
+
+    private StringBuffer step(Property containmentProperty, StringBuffer path) throws XMLStreamException {
+        return step(xsdHelper.getNamespaceURI(containmentProperty),// TODO "" for no-NameSpace global element
+                xsdHelper.getLocalName(containmentProperty), path);
+    }
+
+    private StringBuffer step(Property containmentProperty) throws XMLStreamException {
+        return step(containmentProperty, new StringBuffer());
+    }
+
+    private DataObject dataObject;
+
+    private StringBuffer step(Object container) throws XMLStreamException {
+        Property containmentProperty = dataObject.getContainmentProperty();
+        StringBuffer step = step(containmentProperty);
+        if (containmentProperty.isMany() || ((EObject) dataObject).eContainingFeature() != containmentProperty)
+            step.append('[').append(((DataObject) container).getList(containmentProperty).indexOf(dataObject) + 1).append(']');
+        return step;
+    }
+
+    private String pathRootObject;
+    private DataObject rootObject;
+
+    private EObject container(EObject object) {
+        final EObject container = object.eContainer();
+        if (!(container instanceof DataObject))
+            return null;
+        String name = extendedMetaData.getName(container.eClass());
+        return name != null && name.length() == 0 // DocumentRoot
+             ? null : container;
+    }
+
+    private String path() throws XMLStreamException {
+        if (pathRootObject == STRING_OPTION)
+            pathRootObject = options == null ? null : (String) options.get(OPTION_RootObject_PATH);
+        if (pathRootObject != null && dataObject == rootObject)
+            return null;
+        EObject container = container((EObject) dataObject);
+        if (container == null)
+            return null;
+        StringBuffer step = step(container);
+        while (true) {
+            String path = step.toString();
+            dataObject = (DataObject) container;
+            if (pathRootObject != null && container == rootObject)
+                return path;
+            container = container(container);
+            if (container == null)
+                return path;
+            step = step(container).append('/').append(path);
+        }
+    }
+
+    /*
+     * not to support DataGraph 3-1 private org.eclipse.emf.ecore.resource.Resource rootResource;
+     */
+
+    protected String rootElementNS;
+
+    String rootElementName;
+
+    ExtendedMetaData extendedMetaData;
+
+    protected final String rootElementName() {
+        if (rootElementNS != null)
+            return rootElementName;
+        QName rootElement = (QName) options.get(OPTION_ROOT_ELEMENT);
+        if (rootElement != null) {
+            rootElementNS = rootElement.getNamespaceURI();
+            return rootElementName = rootElement.getLocalPart();
+        }
+        EStructuralFeature element = ((EObject) rootObject).eContainingFeature();
+        if (element == null) {
+            rootElementNS = "";
+            return rootElementName = "descendant-or-self::node()";
+        }
+        rootElementNS = extendedMetaData.getNamespace(element);
+        if (rootElementNS == null)
+            rootElementNS = "";
+        return rootElementName = extendedMetaData.getName(element);
+    }
+
+    String ref() throws XMLStreamException {
+        /*
+         * not to support DataGraph 3-2 if (rootResource != null) return rootResource.getURIFragment((EObject) dataObject);
+         */
+        String id = EcoreUtil.getID((EObject) dataObject);
+        if (id != null)
+            return id;
+        id = path();
+        if (pathRootObject == null)
+            return id == null ? "#/" + rootElementName() // descendant-or-self::node()
+            : "#//" + id;
+        return id == null ? pathRootObject/* + "."*/ : pathRootObject + id;
+    }
+
+    void writeRef(String ref) throws XMLStreamException {
+        writer.writeAttribute(SDOAnnotations.COMMONJ_SDO_NS, REF_ATTRIBUTE, ref);
+    }
+
+    void writeRef() throws XMLStreamException {
+        writeRef(ref());
+    }
+
+    void writeEndElement(String lineBreak) throws XMLStreamException {
+        if (lineBreak != null)
+            breakLine();
+        writer.writeEndElement();
+        --nest;
+    }
+
+    private StringBuffer pathDeleted/* = null */;
+
+    private Collection modifiedDataObjects;
+    
+    private int lengthDeleted;
+
+    private String changeSummaryElementNS, changeSummaryElementName;
+
+    private ChangeSummary changeSummary;
+
+    protected boolean skipDeletedModification(DataObject modifiedDataObject) {
+        return changeSummary.isDeleted(modifiedDataObject);
+    }
+
+    String refDeleted() throws XMLStreamException {
+        String id = EcoreUtil.getID((EObject) dataObject);
+        if (id != null)
+            return id;
+        id = path(); // "dataObject" is updated too!!
+        DataObject deletedDataObject = dataObject;
+        
+        /*
+         * construct "#//...changeSummary/"
+         *  output: pathDeleted
+         */
+        if (lengthDeleted == -1) {
+            String path = pathRootObject == null ? "#//" : pathRootObject;
+            if (pathDeleted == null)
+                pathDeleted = new StringBuffer(path);
+            else
+                pathDeleted.replace(0, pathDeleted.length(), path);
+            dataObject = rootObject;
+            path = path();
+            if (path != null)
+                pathDeleted.append(path).append('/');
+            step(changeSummaryElementNS, changeSummaryElementName, pathDeleted).append('/');
+            lengthDeleted = pathDeleted.length();
+        } else
+            pathDeleted.delete(lengthDeleted, pathDeleted.length());
+        
+        dataObject = changeSummary.getOldContainer(deletedDataObject);
+        Property containmentProperty = dataObject.getContainmentProperty();
+        String name = containmentProperty == null ? rootElementName() : xsdHelper.getLocalName(containmentProperty);
+        int index = 1;
+        for (Iterator iterator = modifiedDataObjects.iterator(); iterator.hasNext();) {
+            DataObject modifiedDataObject = (DataObject) iterator.next();
+            if (skipDeletedModification(modifiedDataObject))
+                continue;
+            if (modifiedDataObject == dataObject)
+                break;
+            Property property = modifiedDataObject.getContainmentProperty();
+            if (property == containmentProperty || name.equals(property == null ? rootElementName() : xsdHelper.getLocalName(property)))
+                ++index;
+        }
+        pathDeleted/*.append("*:")*/.append(name).append('[').append(index).append("]/");
+        containmentProperty = changeSummary.getOldContainmentProperty(deletedDataObject);
+        // assert containmentProperty != null;
+        step(containmentProperty, pathDeleted);
+        Object f;
+        if (containmentProperty.isMany()
+                || (f = extendedMetaData.getAffiliation(((EObject) dataObject).eClass(), (EStructuralFeature) containmentProperty)) != null
+                && f != containmentProperty)
+            pathDeleted.append('[').append(
+                    ((List) changeSummary.getOldValue(dataObject, containmentProperty).getValue()).indexOf(deletedDataObject) + 1).append(']');
+        if (id != null)
+            pathDeleted.append('/').append(id);
+        return pathDeleted.toString();
+    }
+
+    static String convertToString(Property property, Object value) {
+        return EcoreUtil.convertToString((EDataType) property.getType(), value);
+    }
+
+    void writeRefDeleted() throws XMLStreamException {
+        writeRef(refDeleted());
+    }
+
+    protected final void writeDeletedObject(Property property) throws XMLStreamException {
+      ++nest;
+      startElement();
+      --nest;
+      DataObject oldDataObject = ((ChangeSummaryImpl)changeSummary).getOldDataObject(dataObject);
+      XMLStreamReader reader = new DataObjectXMLStreamReader(property, oldDataObject, null, xsdHelper);
+      new XMLStreamSerializer().serialize(new XMLDocumentStreamReader(reader), writer);
+    }
+
+    static public final Object ChangeSummary_TYPE = ((ModelFactoryImpl) ModelFactory.INSTANCE).getChangeSummaryType();
+
+    Collection deletedDataObjects;
+
+    protected final void writeElement(Object value, Property property) throws XMLStreamException {
+        if (value == null) {
+            writeStartElement(property);
+            writeGlobalAttribute(ExtendedMetaData.XSI_PREFIX, ExtendedMetaData.XSI_URI, XMLResource.NIL, "true");
+            writeEndElement(null);
+        } else if (value instanceof DataObject) {
+            dataObject = (DataObject) value;
+            if (!changeSummary.isDeleted(dataObject)) {
+                writeStartElement(property);
+                writeRef();
+                writeEndElement(null);
+            } else if (property.isContainment() && deletedDataObjects.contains(dataObject)) {
+                writeDeletedObject(property);
+            } else {
+                writeStartElement(property);
+                writeRefDeleted();
+                writeEndElement(null);
+            }
+        } else {
+            Object type = property.getType();
+            if (type == ChangeSummary_TYPE)
+                return;
+            writeStartElement(property);
+            writer.writeCharacters(EcoreUtil.convertToString((EDataType) type, value));
+            writeEndElement(null);
+        }
+    }
+    
+    protected final void writeElement(Object value) throws XMLStreamException {
+        FeatureMap.Entry entry = (FeatureMap.Entry) value;
+        writeElement(entry.getValue(), (Property)entry.getEStructuralFeature());
+    }
+
+    static protected List optimize(List values, Object featureChange, int size) {
+        int fromIndex = size, toIndex = 0;
+        for (Iterator changes = ((FeatureChange) featureChange).getListChanges().iterator(); changes.hasNext();) {
+            ListChange change = (ListChange) changes.next();
+            Object kind = change.getKind();
+            if (kind == ChangeKind.MOVE_LITERAL)
+                return values;
+            int index = change.getIndex();
+            if (kind == ChangeKind.ADD_LITERAL) {
+                if (index == 0) {
+                    fromIndex = 0;
+                    if (toIndex == 0)
+                        toIndex = 1;
+                } else {
+                    int to = index;
+                    if (--index < fromIndex)
+                        fromIndex = index;
+                    if (++to > toIndex)
+                        toIndex = to;
+                    else if (to < toIndex)
+                        ++toIndex;
+                }
+                ++size;
+            } else {
+                --size;
+                if (index < fromIndex)
+                    fromIndex = index;
+                if (index < toIndex)
+                    --toIndex;
+                else if (index > toIndex && index != size)
+                    toIndex = index;
+            }
+        }
+        return values.subList(fromIndex, toIndex);
+    }
+    
+    static protected final Object CHANGE_SUMMARY = SDOPackage.eINSTANCE.getChangeSummary();
+
+    /**
+     * Root Object path String such as "#", etc. Absent/null is the default (automatic computation)
+     */
+    static public final String OPTION_RootObject_PATH = "RootObject path",
+    /**
+     * Boolean to optimize sequence/list/array. Absent/null/Boolean.FALSE is the default (no optimization)
+     */
+    OPTION_OPTIMIZE_LIST = "optimize sequence/list/array",
+    /**
+     * Element QName if the changeSummary Root Object is a XML root; the NameSpace can be empty, never null; the prefix is ignored.
+     * Absent/null is the default (automatic computation from DocumentRoot if any)
+     */
+    OPTION_ROOT_ELEMENT = "Root Element";
+
+    /**
+     * Exports ChangeSummary
+     * 
+     * @param changeSummary
+     *            Never null
+     * @param changeSummaryElement
+     *            changeSummary element; the NameSpace can be empty if no NameSpace, or null if local element; the prefix can be null(no preference)
+     * @param writer
+     *            Never null
+     * @param options
+     *            {@link SDOUtil#XML_SAVE_LineBreak} (absence/null is the default i.e. no Line Breaking), {@link SDOUtil#XML_SAVE_INDENT} (absence/null is the default i.e. no indentation), {@link SDOUtil#XML_SAVE_MARGIN}, {@link #OPTION_RootObject_PATH}, {@link #OPTION_OPTIMIZE_LIST} and XMLResource.OPTION_EXTENDED_META_DATA; can be null or empty
+     */
+    public final void saveChangeSummary(ChangeSummary changeSummary, QName changeSummaryElement, XMLStreamWriter writer, Map options)
+            throws XMLStreamException {
+        /*
+         * 6-1. Group created, deleted and modified DataObjects
+         *  input: changeSummary output: createdDataObjects, deletedDataObjects & modifiedDataObjects
+         *  implement: careful if compute from changeSummary.getChangedDataObjects() since it also includes children of deleted objects (thank Frank)
+         */
+        if (changeSummary.isLogging())
+            ((ChangeSummaryImpl) changeSummary).summarize();
+        ChangeDescription changeDescription = (ChangeDescription) changeSummary;
+        Iterator createdDataObjects = changeDescription.getObjectsToDetach().iterator();
+        deletedDataObjects = changeDescription.getObjectsToAttach();
+        EMap objectChanges = changeDescription.getObjectChanges();
+        modifiedDataObjects = objectChanges.keySet(); // may contain DO(s) from createdDataObjects and/or deletedDataObjects
+
+        /*
+         * 6-2. Prepare to compute (X)Path
+         *  input: changeSummary
+         *  output: rootResource
+         */
+        /*not to support DataGraph 3-3
+        Object dataGraph = changeSummary.getDataGraph();
+        if (dataGraph == null) {
+            DataObject rootObject = changeSummary.getRootObject();
+            // assert rootObject != null;
+            rootResource = rootObject.getContainer() == null ? ((EObject) rootObject).eResource() // Can be null since this *StAX* writer does NOT
+                    // require rootObject contained by an *EMF* Resource
+                    : null; // eResource() direct content may not necessarily always be the XML document
+        } else
+            // assert dataGraph instanceof DataGraphImpl;
+            rootResource = ((org.apache.tuscany.sdo.impl.DataGraphImpl) dataGraph).getRootResource(); */
+
+        /*
+         * 6-2. Start ChangeSummary element
+         *  input: writer, options, elementCS, changeSummary & changeDescription (6-1)
+         */
+        nsPrefixSuffix = 0;
+        this.writer = writer;
+        this.options = options;
+        lineBreak = "";
+        indent = margin = pathRootObject = STRING_OPTION;
+        nest = 0;
+        changeSummaryElementNS = changeSummaryElement.getNamespaceURI();
+        changeSummaryElementName = changeSummaryElement.getLocalPart();
+        writeStartElement(changeSummaryElement.getPrefix(), changeSummaryElementNS, changeSummaryElementName);
+        lineBreak = STRING_OPTION;
+        rootObject = changeSummary.getRootObject();
+        extendedMetaData = (ExtendedMetaData) options.get(XMLResource.OPTION_EXTENDED_META_DATA);
+        if (extendedMetaData == null)
+        {
+            extendedMetaData = ExtendedMetaData.INSTANCE;
+            xsdHelper = XSDHelper.INSTANCE;
+        }
+        else{
+        	xsdHelper = (new HelperContextImpl(extendedMetaData, false)).getXSDHelper();
+        }
+        Property declaration = changeSummaryElementNS == null
+                             ? rootObject.getType().getProperty(changeSummaryElementName)
+                             : xsdHelper.getGlobalProperty(changeSummaryElementNS, changeSummaryElementName, true);
+        if (declaration != null)
+        {
+            EClassifier type = changeDescription.eClass();
+            if (type != declaration.getType() && type != CHANGE_SUMMARY)
+                writeGlobalAttribute(ExtendedMetaData.XSI_PREFIX, ExtendedMetaData.XSI_URI, XMLResource.TYPE, new StringBuffer(prefix(extendedMetaData.getNamespace(type), null))
+                        .append(':').append(extendedMetaData.getName(type)).toString());
+        }
+        
+        /*
+         * 6-3. "create" attribute
+         *  input: createdDataObjects (6-1), rootResource (6-2), changeSummary & writer
+         */
+        rootElementNS = null;
+        this.changeSummary = changeSummary;
+        if (createdDataObjects.hasNext()) {
+            StringBuffer buffer = new StringBuffer();
+            while (true) {
+                dataObject = (DataObject) createdDataObjects.next();
+                buffer.append(ref());
+                if (!createdDataObjects.hasNext())
+                    break;
+                buffer.append(' ');
+            }
+            writer.writeAttribute(CREATE_ATTRIBUTE, buffer.toString());
+        }
+
+        /*
+         * 6-4. "delete" attribute
+         *  input: deletedDataObjects (6-1), modifiedDataObjects (6-1) & writer
+         */
+        Iterator iterator = deletedDataObjects.iterator();
+        if (iterator.hasNext()) {
+            lengthDeleted = -1;
+            StringBuffer buffer = null;
+            do {
+                dataObject = (DataObject) iterator.next();
+                if (skipDeletedModification(changeSummary.getOldContainer(dataObject)))
+                    continue;
+                if (buffer == null)
+                    buffer = new StringBuffer();
+                else
+                    buffer.append(' ');
+                buffer.append(refDeleted());
+            } while (iterator.hasNext());
+            writer.writeAttribute(DELETE_ATTRIBUTE, buffer.toString());
+        }
+
+        /*
+         * 6-5. "logging" attribute
+         *  input: changeSummary & writer
+         */
+        writer.writeAttribute(LOGGING_ATTRIBUTE, changeSummary.isLogging() ? "true" : "false");
+
+        /*
+         * 6-6. Modified DataObjects
+         *  input: modifiedDataObjects (6-1), rootResource (6-2), changeSummary & writer
+         */
+        iterator = modifiedDataObjects.iterator();
+        if (iterator.hasNext()) {
+            boolean optimizeList;
+            if (options == null)
+                optimizeList = false;
+            else
+            {
+                Object option = options.get(OPTION_OPTIMIZE_LIST);
+                optimizeList = option == null ? false : ((Boolean)option).booleanValue();
+            }
+            prefix(SDOAnnotations.COMMONJ_SDO_NS, SDOPackage.eNS_PREFIX);
+            do {
+                DataObject dataObject = (DataObject) iterator.next();
+                if (skipDeletedModification(dataObject))
+                    continue;
+                Property containmentProperty = dataObject.getContainmentProperty();
+                if (containmentProperty == null) {
+                    ++nest;
+                    startElement();
+                    rootElementName();
+                    writer.writeStartElement(rootElementNS, rootElementName);
+                } else
+                    writeStartElement(containmentProperty);
+                this.dataObject = dataObject;
+                writeRef();
+
+                String lineBreak = null;
+                Collection oldValues = (Collection) objectChanges.get(dataObject); // changeSummary.getOldValues repeats Sequence changes
+                Iterator settings = oldValues.iterator();
+                if (settings.hasNext()) {
+                    do {
+                        ChangeSummary.Setting oldValue = (ChangeSummary.Setting) settings.next();
+                        if (oldValue.isSet())
+                            continue;
+                        StringBuffer unset = step(oldValue.getProperty());
+                        while (settings.hasNext()) {
+                            oldValue = (ChangeSummary.Setting) settings.next();
+                            if (!oldValue.isSet())
+                                step(oldValue.getProperty(), unset.append(' '));
+                        }
+                        writer.writeAttribute(SDOAnnotations.COMMONJ_SDO_NS, UNSET, unset.toString());
+                        break;
+                    } while (settings.hasNext());
+                    for (settings = oldValues.iterator(); settings.hasNext();) {
+                        ChangeSummary.Setting oldValue = (ChangeSummary.Setting) settings.next();
+                        Property property = oldValue.getProperty();
+                        if (oldValue.isSet() && xsdHelper.isAttribute(property))
+                            // assert ! property.isMany();
+                            writeAttribute(property, convertToString(property, oldValue.getValue()));
+                    }
+                    for (settings = oldValues.iterator(); settings.hasNext();) {
+                        ChangeSummary.Setting oldValue = (ChangeSummary.Setting) settings.next();
+                        Property property = oldValue.getProperty();
+                        if (!xsdHelper.isAttribute(property))
+                            if (property.isMany()) {
+                                Object value = oldValue.getValue();
+                                List list = (List) value;
+                                if (FeatureMapUtil.isFeatureMap((EStructuralFeature) property)) {
+                                    if (optimizeList)
+                                        list = optimize(list, oldValue, dataObject.getSequence(property).size());
+                                    Iterator values = list.iterator();
+                                    if (!values.hasNext())
+                                        continue;
+                                    do
+                                        writeElement(values.next());
+                                    while (values.hasNext());
+                                } else {
+                                    if (optimizeList)
+                                        list = optimize(list, oldValue, dataObject.getList(property).size());
+                                    Iterator values = list.iterator();
+                                    if (!values.hasNext())
+                                        continue;
+                                    do
+                                        writeElement(values.next(), property);
+                                    while (values.hasNext());
+                                }
+                                lineBreak = this.lineBreak;
+                            } else if (oldValue.isSet()) {
+                                Object value = oldValue.getValue();
+                                if (value instanceof FeatureMap.Entry)
+                                    writeElement(value);
+                                else
+                                    writeElement(value, property);
+                                lineBreak = this.lineBreak;
+                            }
+                    }
+                }
+                writeEndElement(lineBreak);
+            } while (iterator.hasNext());
+            writeEndElement(lineBreak);
+        } else
+            writeEndElement(null);
+        writer.flush();
+    }
+}
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/util/resource/RecordedEventXMLStreamReader.java b/impl/src/main/java/org/apache/tuscany/sdo/util/resource/RecordedEventXMLStreamReader.java
index b2b3036..a0da5d2 100644
--- a/impl/src/main/java/org/apache/tuscany/sdo/util/resource/RecordedEventXMLStreamReader.java
+++ b/impl/src/main/java/org/apache/tuscany/sdo/util/resource/RecordedEventXMLStreamReader.java
@@ -1,868 +1,868 @@
-/**

- *

- *  Licensed to the Apache Software Foundation (ASF) under one

- *  or more contributor license agreements.  See the NOTICE file

- *  distributed with this work for additional information

- *  regarding copyright ownership.  The ASF licenses this file

- *  to you 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.apache.tuscany.sdo.util.resource;

-

-import java.util.ArrayList;

-import java.util.Collection;

-import java.util.Iterator;

-import java.util.List;

-import java.util.NoSuchElementException;

-

-import javax.xml.XMLConstants;

-import javax.xml.namespace.NamespaceContext;

-import javax.xml.namespace.QName;

-import javax.xml.stream.Location;

-import javax.xml.stream.XMLStreamException;

-import javax.xml.stream.XMLStreamReader;

-

-import org.eclipse.emf.ecore.xmi.XMLResource;

-import org.xml.sax.Attributes;

-import org.xml.sax.Locator;

-

-/**

- * This special purpose XMLStreamReader is used to produce a StAX event stream corresponding to a list of events 

- * recorded earlier. The recorded events are generated by the inner class RecordedEventXMLStreamReader.Tag, 

- * which records the events in either of 2 ways:

- * 

- * 1) in conjunction with class SDOXMLLoadImpl, it records events corresponding to the SAX events being

- *    handled by the SDOXMLLoadImpl when loading XML using SDOXMLResourceImpl.

- * 2) when Tag.record() is called (see class ChangeSummaryStreamDeserializer), it walks through and records 

- *    the StAX events produced by another XMLStreamReader.

- * 

- * This class is used by the SDO StAX-based ChangeSummaryType-property loader, class

- * ChangeSummaryStreamDeserializer, which is inoked by and uses (for loading deleted object XML fragments)

- * the SAX-based loader class XMLResourceImpl.

- */

-public abstract class RecordedEventXMLStreamReader implements XMLStreamReader {

-

-    static private class Event {

-        int type;

-

-        public NamespaceContext nameSpaceContext;

-

-        Location location;

-

-        protected final void initialize(XMLStreamReader reader) {

-            nameSpaceContext = reader.getNamespaceContext();

-            location = reader.getLocation();

-        }

-

-        protected final void location(final Locator locator) {

-            location = new Location() {

-                public int getCharacterOffset() {

-                    return -1;

-                }

-

-                public int getColumnNumber() {

-                    return locator.getColumnNumber();

-                }

-

-                public int getLineNumber() {

-                    return locator.getLineNumber();

-                }

-

-                public String getPublicId() {

-                    return locator.getPublicId();

-                }

-

-                public String getSystemId() {

-                    return locator.getSystemId();

-                }

-            };

-        }

-    }

-

-    static class ValueEvent extends Event {

-        final String value;

-

-        protected ValueEvent(String v) {

-            value = v;

-        }

-    }

-

-    static protected class Reference extends ValueEvent {

-        final String target;

-

-        protected Reference(String name, String data) {

-            super(data);

-            target = name;

-        }

-    }

-

-    static protected final class AttributeEvent extends Reference {

-        final QName name;

-

-        final String nameSpace, prefix;

-

-        int attributes;

-

-        final boolean specified;

-

-        protected AttributeEvent(XMLStreamReader reader) {

-            super(reader.getAttributeType(0), reader.getAttributeValue(0));

-            attributes = reader.getAttributeCount();

-            name = reader.getAttributeName(0);

-            nameSpace = reader.getAttributeNamespace(0);

-            prefix = reader.getAttributePrefix(0);

-            specified = reader.isAttributeSpecified(0);

-        }

-    }

-

-    static protected final class NameSpaceEvent extends Reference {

-        int nameSpaces;

-

-        protected NameSpaceEvent(XMLStreamReader reader) {

-            super(reader.getNamespacePrefix(0), reader.getNamespaceURI(0));

-            nameSpaces = reader.getNamespaceCount();

-        }

-    }

-

-    static protected String prefix(String qName, String nameSpace) {

-        int delimiter = qName.indexOf(':');

-        if (delimiter != -1)

-            return qName.substring(0, delimiter);

-        if (nameSpace.length() != 0)

-            return XMLConstants.DEFAULT_NS_PREFIX;

-        // if (nameSpaceContext.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX) != null || xsdHelper.getGlobalProperty(null, name, element) == null)

-        return null;

-    }

-

-    static class EndElement extends Event {

-        List nameSpaces/* = null */;

-

-        public final QName name;

-

-        public final String nameSpace;

-

-        final String prefix;

-

-        protected EndElement(XMLStreamReader reader) {

-            name = reader.getName();

-            nameSpace = reader.getNamespaceURI();

-            prefix = reader.getPrefix();

-            int count = reader.getNamespaceCount();

-            if (count == 0)

-                return;

-            nameSpaces = new ArrayList(count);

-            int index = 0;

-            do

-                Tag.bind(reader.getNamespacePrefix(index), reader.getNamespaceURI(index), nameSpaces);

-            while (++index != count);

-        }

-

-        protected EndElement(String uri, String local, String p, Locator locator) {

-            if (p == null) {

-                name = new QName(uri, local, XMLConstants.DEFAULT_NS_PREFIX);

-                nameSpace = null;

-            } else {

-                name = new QName(uri, local, p);

-                nameSpace = uri;

-            }

-            prefix = p;

-            location(locator);

-        }

-    }

-

-    static class NameSpace {

-        final String prefix, uri;

-

-        protected NameSpace(String p, String nameSpace) {

-            prefix = p;

-            uri = nameSpace;

-        }

-    }

-

-    static final class Attribute extends NameSpace {

-        final String type, value;

-

-        final QName qName;

-

-        boolean specified/* = false */;

-

-        protected Attribute(String t, String v, QName name, String prefix, String nameSpace) {

-            super(prefix, nameSpace);

-            type = t;

-            value = v;

-            qName = name;

-        }

-    }

-

-    static final class AttributeList /* implements Attributes */{// TODO exclude XMLConstants.XMLNS_ATTRIBUTE

-        final List attributes;

-

-        protected AttributeList(int size) {

-            attributes = new ArrayList(size);

-        }

-

-        /*

-         * @param uri Never null

-         */

-        public final int getIndex(String uri, String localName) {

-            for (int index = getLength(); index != 0;)

-                if (getLocalName(--index).equals(localName) && uri.equals(getURI(index)))

-                    return index;

-            return -1;

-        }

-

-        public final int getLength() {

-            return attributes.size();

-        }

-

-        protected final Attribute attribute(int index) {

-            return (Attribute) attributes.get(index);

-        }

-

-        public final String getLocalName(int index) {

-            return attribute(index).qName.getLocalPart();

-        }

-

-        public final String getType(int index) {

-            return attribute(index).type;

-        }

-

-        /*public String getType(String uri, String localName) {

-            int index = getIndex(uri, localName);

-            return index == -1 ? null: getType(index);

-         } */

-

-        public final String getURI(int index) {

-            return attribute(index).uri;

-        }

-

-        public final String getValue(int index) {

-            return attribute(index).value;

-        }

-

-        /*

-         * @param uri Never null

-         */

-        public final String getValue(String uri, String localName) {

-            int index = getIndex(uri, localName);

-            return index == -1 ? null : getValue(index);

-        }

-    }

-

-    static protected class StartElement extends EndElement {

-        final AttributeList attributes;

-

-        protected StartElement(XMLStreamReader reader) {

-            super(reader);

-            int count = reader.getAttributeCount();

-            if (count == 0)

-                attributes = null;

-            else {

-                attributes = new AttributeList(count);

-                int index = 0;

-                do {

-                    Attribute attribute = new Attribute(reader.getAttributeType(index), reader.getAttributeValue(index), reader

-                            .getAttributeName(index), reader.getAttributePrefix(index), reader.getAttributeNamespace(index));

-                    attribute.specified = reader.isAttributeSpecified(index);

-                    attributes.attributes.add(attribute);

-                } while (++index != count);

-            }

-        }

-

-        protected StartElement(String nameSpace, String local, String prefix, Attributes attributeArray, Locator locator, List bindings,

-                final NamespaceContext context) {

-            super(nameSpace, local, prefix, locator);

-            nameSpaces = bindings;

-            nameSpaceContext = bindings == null || bindings.isEmpty() ? context : new NamespaceContext() {

-                public String getNamespaceURI(String prefix) {

-                    for (int index = nameSpaces.size(); index != 0;) {

-                        NameSpace binding = (NameSpace) nameSpaces.get(--index);

-                        if (binding.prefix.equals(prefix))

-                            return binding.uri;

-                    }

-                    return context.getNamespaceURI(prefix);

-                }

-

-                public String getPrefix(String namespaceURI) {

-                    for (int index = nameSpaces.size(); index != 0;) {

-                        NameSpace binding = (NameSpace) nameSpaces.get(--index);

-                        if (binding.uri.equals(namespaceURI))

-                            return binding.prefix;

-                    }

-                    return context.getPrefix(namespaceURI);

-                }

-

-                public Iterator getPrefixes(final String namespaceURI) {

-                    final Iterator iterator = context.getPrefixes(namespaceURI);

-                    return new Iterator() {

-                        Iterator bindings = nameSpaces.iterator();

-

-                        NameSpace binding/* = null */;

-

-                        protected final boolean prefix() {

-                            while (bindings.hasNext()) {

-                                binding = (NameSpace) bindings.next();

-                                if (binding.uri.equals(namespaceURI))

-                                    return true;

-                            }

-                            bindings = null;

-                            return false;

-                        }

-

-                        public boolean hasNext() {

-                            return bindings != null && prefix() || iterator.hasNext();

-                        }

-

-                        protected NameSpace nameSpace;

-

-                        public Object next() {

-                            if (bindings == null || binding == null && !prefix())

-                                return iterator.next();

-                            nameSpace = binding;

-                            binding = null;

-                            return nameSpace.prefix;

-                        }

-

-                        public void remove() {

-                            if (bindings == null)

-                                iterator.remove();

-                            else

-                                nameSpaces.remove(nameSpace);

-                        }

-                    };

-                }

-            };

-            int count = attributeArray.getLength();

-            if (count == 0)

-                attributes = null;

-            else {

-                attributes = new AttributeList(count);

-                int index = 0;

-                do {

-                    QName name;

-                    nameSpace = attributeArray.getURI(index);

-                    local = attributeArray.getLocalName(index);

-                    prefix = prefix(attributeArray.getQName(index), nameSpace);

-                    if (prefix == null) {

-                        name = new QName(nameSpace, local, XMLConstants.DEFAULT_NS_PREFIX);

-                        nameSpace = null;

-                    } else

-                        name = new QName(nameSpace, local, prefix);

-                    attributes.attributes.add(new Attribute(attributeArray.getType(index), attributeArray.getValue(index), name, prefix, nameSpace));

-                } while (++index != count);

-            }

-        }

-    }

-

-    static public class Tag extends StartElement {

-        public Tag(XMLStreamReader reader) {

-            super(reader);

-            initialize(reader);

-        }

-

-        public List events/* = null */; // may be empty

-

-        protected final void events() {

-            events = new ArrayList();

-        }

-

-        public Tag(String nameSpace, String local, String prefix, Attributes attributes, Locator locator, NamespaceContext context, List bindings) {

-            super(nameSpace, local, prefix, attributes, locator, bindings, context);

-            events();

-        }

-

-        static public void bind(String prefix, String nameSpace, Collection nameSpaces) {

-            nameSpaces.add(new NameSpace(prefix, nameSpace));

-        }

-

-        protected int nest/* = 0 */;

-

-        public final void start(String nameSpace, String local, String qName, Attributes attributes, Locator locator, List bindings) {

-            Event event;

-            for (int index = events.size();/* true */;) {

-                if (index == 0) {

-                    event = this;

-                    break;

-                }

-                event = (Event) events.get(--index);

-                if (event.type != END_ELEMENT)

-                    break;

-                siblings: for (int nest = 0;/* true */;)

-                    switch (((Event) events.get(--index)).type) {

-                    case START_ELEMENT:

-                        if (nest == 0)

-                            break siblings;

-                        --nest;

-                        break;

-                    case END_ELEMENT:

-                        ++nest;

-                    }

-            }

-            Event start = new StartElement(nameSpace, local, prefix(qName, nameSpace), attributes, locator, bindings, event.nameSpaceContext);

-            start.type = START_ELEMENT;

-            events.add(start);

-            ++nest;

-        }

-

-        protected final void  add (Event event)

-        {

-            int index = events.size();

-            event.nameSpaceContext = index == 0 ? nameSpaceContext : ((Event) events.get(--index)).nameSpaceContext;

-            events.add(event);

-        }

-

-        public final void text(int type, String value, Locator locator) {

-            Event event = new ValueEvent(value);

-            event.type = type;

-            event.location(locator);

-            //int index = events.size();

-            add(event);

-        }

-

-        public final boolean end(String nameSpace, String local, String qName, Locator locator) {

-            Event end = new EndElement(nameSpace, local, prefix(qName, nameSpace), locator);

-            end.type = END_ELEMENT;

-            add(end);

-            if (nest == 0)

-                return true;

-            --nest;

-            return false;

-        }

-

-        public final XMLStreamReader play(final XMLResource resource) {

-            return new RecordedEventXMLStreamReader(this) {

-                public void close() {

-                }

-

-                public String getCharacterEncodingScheme() {

-                    return null; // TODO

-                }

-

-                public String getEncoding() {

-                    return resource.getEncoding();

-                }

-

-                public Object getProperty(String property) {

-                    return null; // TODO javax.xml.stream.notations & javax.xml.stream.entities for DTD

-                }

-

-                public String getVersion() {

-                    return resource.getXMLVersion();

-                }

-

-                public boolean isStandalone() {

-                    return false; // TODO

-                }

-

-                public boolean standaloneSet() {

-                    return false; // TODO

-                }

-            };

-        }

-

-        protected final void add(Event event, int type, XMLStreamReader reader) {

-            event.type = type;

-            event.initialize(reader);

-            events.add(event);

-        }

-

-        public final boolean record(XMLStreamReader reader) throws XMLStreamException {

-            events();

-            for (int nest = 0; reader.hasNext();) {

-                Event event;

-                int type = reader.next();

-                switch (type) {

-                case CHARACTERS:

-                case CDATA:

-                case COMMENT:

-                case SPACE:

-                case DTD:

-                    event = new ValueEvent(reader.getText());

-                    break;

-                case ENTITY_REFERENCE:

-                    event = new Reference(reader.getLocalName(), reader.getText());

-                    break;

-                case PROCESSING_INSTRUCTION:

-                    event = new Reference(reader.getPITarget(), reader.getPIData());

-                    break;

-                case ATTRIBUTE:

-                    event = new AttributeEvent(reader);

-                    break;

-                case NAMESPACE:

-                    event = new NameSpaceEvent(reader);

-                    break;

-                case START_ELEMENT:

-                    ++nest;

-                    event = new StartElement(reader);

-                    break;

-                case END_ELEMENT:

-                    add(new EndElement(reader), type, reader);

-                    if (nest == 0)

-                        return false;

-                    --nest;

-                    continue;

-                case END_DOCUMENT:

-                    return true; // report error?

-                default: // new type

-                    event = new Event();

-                }

-                add(event, type, reader);

-            }

-            return true; // report error?

-        }

-

-        public final XMLStreamReader play(final XMLStreamReader reader) {

-            return new RecordedEventXMLStreamReader(this) {

-                public void close() throws XMLStreamException {

-                    reader.close();

-                }

-

-                public String getCharacterEncodingScheme() {

-                    return reader.getCharacterEncodingScheme();

-                }

-

-                public String getEncoding() {

-                    return reader.getEncoding();

-                }

-

-                public Object getProperty(String property) {

-                    return reader.getProperty(property); // TODO javax.xml.stream.notations & javax.xml.stream.entities for DTD

-                }

-

-                public String getVersion() {

-                    return reader.getVersion();

-                }

-

-                public boolean isStandalone() {

-                    return reader.isStandalone();

-                }

-

-                public boolean standaloneSet() {

-                    return reader.standaloneSet();

-                }

-            };

-        }

-    }

-

-    Event event;

-

-    final List events;

-

-    final int size;

-

-    protected RecordedEventXMLStreamReader(Tag tag) {

-        event = tag;

-        tag.type = START_ELEMENT;

-        events = tag.events;

-        size = events.size();

-    }

-

-    public int getAttributeCount() {

-        switch (getEventType()) {

-        case START_ELEMENT:

-            AttributeList attributes = ((StartElement) event).attributes;

-            return attributes == null ? 0 : attributes.getLength();

-        case ATTRIBUTE:

-            return ((AttributeEvent) event).attributes;

-        }

-        throw new IllegalStateException("Neither START_ELEMENT nor ATTRIBUTE");

-    }

-

-    protected final AttributeList attributes() {

-        if (getEventType() == START_ELEMENT)

-            return ((StartElement) event).attributes;

-        throw new IllegalStateException("Neither START_ELEMENT nor ATTRIBUTE");

-    }

-

-    public String getAttributeLocalName(int index) {

-        return attributes().getLocalName(index);

-    }

-

-    static Attribute attribute(AttributeList attributes, int index) {

-        return (Attribute) attributes.attributes.get(index);

-    }

-

-    public QName getAttributeName(int index) {

-        return getEventType() == ATTRIBUTE ? ((AttributeEvent) event).name : attribute(attributes(), index).qName;

-    }

-

-    public String getAttributeNamespace(int index) {

-        return getEventType() == ATTRIBUTE ? ((AttributeEvent) event).nameSpace : attributes().getURI(index);

-    }

-

-    public String getAttributePrefix(int index) {

-        return getEventType() == ATTRIBUTE ? ((AttributeEvent) event).prefix : attribute(attributes(), index).prefix;

-    }

-

-    public String getAttributeType(int index) {

-        return getEventType() == ATTRIBUTE ? ((Reference) event).target : attributes().getType(index);

-    }

-

-    public String getAttributeValue(int index) {

-        return getEventType() == ATTRIBUTE ? ((ValueEvent) event).value : attributes().getValue(index);

-    }

-

-    public boolean isAttributeSpecified(int index) {

-        if (getEventType() == ATTRIBUTE)

-            return ((AttributeEvent) event).specified;

-        AttributeList attributes = attributes();

-        return attribute(attributes, index).specified;

-    }

-

-    public String getAttributeValue(String nameSpace, String name) {

-        if (getEventType() == ATTRIBUTE) {

-            AttributeEvent attribute = (AttributeEvent) event;

-            return !attribute.name.getLocalPart().equals(name) ? null : nameSpace == null ? (attribute.nameSpace == null ? attribute.value : null)

-                    : nameSpace.equals(attribute.nameSpace) ? attribute.value : null;

-        }

-        AttributeList attributes = attributes();

-        return attributes == null ? null : attributes.getValue(nameSpace == null ? "" : nameSpace, name);

-    }

-

-    protected StringBuffer buffer/* = null */;

-

-    public String getElementText() {

-        if (buffer != null)

-            buffer.delete(0, buffer.length());

-        for (;;)

-            switch (next()) {

-            case END_ELEMENT:

-                return buffer == null ? null : buffer.toString();

-            default:

-                if (buffer == null)

-                    buffer = new StringBuffer();

-                buffer.append(getText());

-            case PROCESSING_INSTRUCTION:

-            case COMMENT:

-            }

-    }

-

-    public final int getEventType() {

-        return event.type;

-    }

-

-    public String getLocalName() {

-        if (getEventType() == ENTITY_REFERENCE)

-            return ((Reference) event).target;

-        if (event instanceof EndElement)

-            return ((EndElement) event).name.getLocalPart();

-        throw new IllegalStateException("Neither START_ELEMENT, END_ELEMENT nor ENTITY_REFERENCE");

-    }

-

-    public final Location getLocation() {

-        return event.location;

-    }

-

-    public QName getName() {

-        if (hasName())

-            return ((EndElement) event).name;

-        throw new IllegalStateException("Neither START_ELEMENT nor END_ELEMENT");

-    }

-

-    public final NamespaceContext getNamespaceContext() {

-        return event.nameSpaceContext;

-    }

-

-    public int getNamespaceCount() {

-        if (getEventType() == NAMESPACE)

-            return ((NameSpaceEvent) event).nameSpaces;

-        if (!(event instanceof EndElement))

-            throw new IllegalStateException("Neither START_ELEMENT, END_ELEMENT nor NAMESPACE");

-        Collection nameSpaces = ((EndElement) event).nameSpaces;

-        return nameSpaces == null ? 0 : nameSpaces.size();

-    }

-

-    protected final NameSpace getNameSpace(int index) {

-        if (event instanceof EndElement)

-            return (NameSpace) ((EndElement) event).nameSpaces.get(index);

-        throw new IllegalStateException("Neither START_ELEMENT, END_ELEMENT nor NAMESPACE");

-    }

-

-    public String getNamespacePrefix(int index) {

-        return getEventType() == NAMESPACE ? ((Reference) event).target : getNameSpace(index).prefix;

-    }

-

-    public final String getNamespaceURI() {

-        switch (getEventType()) {

-        case ATTRIBUTE:

-            return ((AttributeEvent) event).nameSpace;

-        case NAMESPACE:

-            return ((ValueEvent) event).value;

-        }

-        return event instanceof EndElement ? ((EndElement) event).nameSpace : null;

-    }

-

-    public String getNamespaceURI(String prefix) {

-        return getNamespaceContext().getNamespaceURI(prefix);

-    }

-

-    public String getNamespaceURI(int index) {

-        return getEventType() == NAMESPACE ? ((ValueEvent) event).value : getNameSpace(index).uri;

-    }

-

-    public String getPIData() {

-        return getEventType() == PROCESSING_INSTRUCTION ? ((ValueEvent) event).value : null;

-    }

-

-    public String getPITarget() {

-        return getEventType() == PROCESSING_INSTRUCTION ? ((Reference) event).target : null;

-    }

-

-    public String getPrefix() {

-        switch (getEventType()) {

-        case ATTRIBUTE:

-            return ((AttributeEvent) event).prefix;

-        case NAMESPACE:

-            return ((Reference) event).target;

-        }

-        return event instanceof EndElement ? ((EndElement) event).prefix : null;

-    }

-

-    public final String getText() {

-        if (hasText())

-            return ((ValueEvent) event).value;

-        throw new IllegalStateException("Neither CHARACTERS, CDATA, COMMENT, SPACE, ENTITY_REFERENCE nor DTD");

-    }

-

-    public final char[] getTextCharacters() {

-        switch (getEventType()) {

-        case CHARACTERS:

-        case CDATA:

-        case COMMENT:

-        case SPACE:

-            return ((ValueEvent) event).value.toCharArray();

-        }

-        throw new IllegalStateException("Neither CHARACTERS, CDATA, COMMENT nor SPACE");

-    }

-

-    public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length) {

-        char[] source = getTextCharacters();

-        if (sourceStart > source.length)

-            throw new IndexOutOfBoundsException("source start > source length");

-        int sourceLen = source.length - sourceStart;

-        if (length > sourceLen)

-            length = sourceLen;

-        System.arraycopy(source, sourceStart, target, targetStart, length);

-        return sourceLen;

-    }

-

-    public int getTextLength() {

-        return getTextCharacters().length;

-    }

-

-    public int getTextStart() {

-        return 0;

-    }

-

-    public final boolean hasName() {

-        return event instanceof EndElement;

-    }

-

-    protected int next/* = 0 */;

-

-    public final boolean hasNext() {

-        return next != size;

-    }

-

-    public final boolean hasText() {

-        switch (getEventType()) {

-        case CHARACTERS:

-        case CDATA:

-        case COMMENT:

-        case SPACE:

-        case ENTITY_REFERENCE:

-        case DTD:

-            return true;

-        }

-        return false;

-    }

-

-    public boolean isCharacters() {

-        switch (getEventType()) {

-        case CHARACTERS:

-        case CDATA:

-        case SPACE:

-            return true;

-        }

-        return false;

-    }

-

-    public boolean isEndElement() {

-        return getEventType() == END_ELEMENT;

-    }

-

-    public boolean isStartElement() {

-        return getEventType() == START_ELEMENT;

-    }

-

-    protected final boolean areWhiteSpace() {

-        String text = getText();

-        for (int index = text.length(); index != 0;)

-            if (!Character.isWhitespace(text.charAt(--index)))

-                return false;

-        return true;

-    }

-

-    public boolean isWhiteSpace() {

-        switch (getEventType()) {

-        case CHARACTERS:

-        case CDATA:

-            return areWhiteSpace();

-        case SPACE:

-            return true;

-        }

-        return false;

-    }

-

-    public final int next() {

-        if (!hasNext())

-            throw new NoSuchElementException();

-        event = (Event) events.get(next++);

-        return event.type;

-    }

-

-    protected final void throwXMLStreamException(String message) throws XMLStreamException {

-        throw new XMLStreamException(message, getLocation());

-    }

-

-    public int nextTag() throws XMLStreamException {

-        for (;;) {

-            int type = next();

-            switch (type) {

-            case CHARACTERS:

-            case CDATA:

-                if (!areWhiteSpace())

-                    break;

-            case SPACE:

-            case PROCESSING_INSTRUCTION:

-            case COMMENT:

-                continue;

-            case START_ELEMENT:

-            case END_ELEMENT:

-                return type;

-            }

-            throwXMLStreamException("expected start or end tag");

-        }

-    }

-

-    public void require(int type, String nameSpace, String name) throws XMLStreamException {

-        if (getEventType() != type)

-            throwXMLStreamException("type not matched");

-        if (nameSpace != null && !nameSpace.equals(getNamespaceURI()))

-            throwXMLStreamException("Name Space not matched");

-        if (name != null

-                && !(getEventType() == ATTRIBUTE ? name.equals(((AttributeEvent) event).name.getLocalPart()) : event instanceof EndElement

-                        && name.equals(((EndElement) event).name.getLocalPart())))

-            throwXMLStreamException("name not matched");

-    }

-}

+/**
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.apache.tuscany.sdo.util.resource;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.namespace.QName;
+import javax.xml.stream.Location;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+
+import org.eclipse.emf.ecore.xmi.XMLResource;
+import org.xml.sax.Attributes;
+import org.xml.sax.Locator;
+
+/**
+ * This special purpose XMLStreamReader is used to produce a StAX event stream corresponding to a list of events 
+ * recorded earlier. The recorded events are generated by the inner class RecordedEventXMLStreamReader.Tag, 
+ * which records the events in either of 2 ways:
+ * 
+ * 1) in conjunction with class SDOXMLLoadImpl, it records events corresponding to the SAX events being
+ *    handled by the SDOXMLLoadImpl when loading XML using SDOXMLResourceImpl.
+ * 2) when Tag.record() is called (see class ChangeSummaryStreamDeserializer), it walks through and records 
+ *    the StAX events produced by another XMLStreamReader.
+ * 
+ * This class is used by the SDO StAX-based ChangeSummaryType-property loader, class
+ * ChangeSummaryStreamDeserializer, which is inoked by and uses (for loading deleted object XML fragments)
+ * the SAX-based loader class XMLResourceImpl.
+ */
+public abstract class RecordedEventXMLStreamReader implements XMLStreamReader {
+
+    static private class Event {
+        int type;
+
+        public NamespaceContext nameSpaceContext;
+
+        Location location;
+
+        protected final void initialize(XMLStreamReader reader) {
+            nameSpaceContext = reader.getNamespaceContext();
+            location = reader.getLocation();
+        }
+
+        protected final void location(final Locator locator) {
+            location = new Location() {
+                public int getCharacterOffset() {
+                    return -1;
+                }
+
+                public int getColumnNumber() {
+                    return locator.getColumnNumber();
+                }
+
+                public int getLineNumber() {
+                    return locator.getLineNumber();
+                }
+
+                public String getPublicId() {
+                    return locator.getPublicId();
+                }
+
+                public String getSystemId() {
+                    return locator.getSystemId();
+                }
+            };
+        }
+    }
+
+    static class ValueEvent extends Event {
+        final String value;
+
+        protected ValueEvent(String v) {
+            value = v;
+        }
+    }
+
+    static protected class Reference extends ValueEvent {
+        final String target;
+
+        protected Reference(String name, String data) {
+            super(data);
+            target = name;
+        }
+    }
+
+    static protected final class AttributeEvent extends Reference {
+        final QName name;
+
+        final String nameSpace, prefix;
+
+        int attributes;
+
+        final boolean specified;
+
+        protected AttributeEvent(XMLStreamReader reader) {
+            super(reader.getAttributeType(0), reader.getAttributeValue(0));
+            attributes = reader.getAttributeCount();
+            name = reader.getAttributeName(0);
+            nameSpace = reader.getAttributeNamespace(0);
+            prefix = reader.getAttributePrefix(0);
+            specified = reader.isAttributeSpecified(0);
+        }
+    }
+
+    static protected final class NameSpaceEvent extends Reference {
+        int nameSpaces;
+
+        protected NameSpaceEvent(XMLStreamReader reader) {
+            super(reader.getNamespacePrefix(0), reader.getNamespaceURI(0));
+            nameSpaces = reader.getNamespaceCount();
+        }
+    }
+
+    static protected String prefix(String qName, String nameSpace) {
+        int delimiter = qName.indexOf(':');
+        if (delimiter != -1)
+            return qName.substring(0, delimiter);
+        if (nameSpace.length() != 0)
+            return XMLConstants.DEFAULT_NS_PREFIX;
+        // if (nameSpaceContext.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX) != null || xsdHelper.getGlobalProperty(null, name, element) == null)
+        return null;
+    }
+
+    static class EndElement extends Event {
+        List nameSpaces/* = null */;
+
+        public final QName name;
+
+        public final String nameSpace;
+
+        final String prefix;
+
+        protected EndElement(XMLStreamReader reader) {
+            name = reader.getName();
+            nameSpace = reader.getNamespaceURI();
+            prefix = reader.getPrefix();
+            int count = reader.getNamespaceCount();
+            if (count == 0)
+                return;
+            nameSpaces = new ArrayList(count);
+            int index = 0;
+            do
+                Tag.bind(reader.getNamespacePrefix(index), reader.getNamespaceURI(index), nameSpaces);
+            while (++index != count);
+        }
+
+        protected EndElement(String uri, String local, String p, Locator locator) {
+            if (p == null) {
+                name = new QName(uri, local, XMLConstants.DEFAULT_NS_PREFIX);
+                nameSpace = null;
+            } else {
+                name = new QName(uri, local, p);
+                nameSpace = uri;
+            }
+            prefix = p;
+            location(locator);
+        }
+    }
+
+    static class NameSpace {
+        final String prefix, uri;
+
+        protected NameSpace(String p, String nameSpace) {
+            prefix = p;
+            uri = nameSpace;
+        }
+    }
+
+    static final class Attribute extends NameSpace {
+        final String type, value;
+
+        final QName qName;
+
+        boolean specified/* = false */;
+
+        protected Attribute(String t, String v, QName name, String prefix, String nameSpace) {
+            super(prefix, nameSpace);
+            type = t;
+            value = v;
+            qName = name;
+        }
+    }
+
+    static final class AttributeList /* implements Attributes */{// TODO exclude XMLConstants.XMLNS_ATTRIBUTE
+        final List attributes;
+
+        protected AttributeList(int size) {
+            attributes = new ArrayList(size);
+        }
+
+        /*
+         * @param uri Never null
+         */
+        public final int getIndex(String uri, String localName) {
+            for (int index = getLength(); index != 0;)
+                if (getLocalName(--index).equals(localName) && uri.equals(getURI(index)))
+                    return index;
+            return -1;
+        }
+
+        public final int getLength() {
+            return attributes.size();
+        }
+
+        protected final Attribute attribute(int index) {
+            return (Attribute) attributes.get(index);
+        }
+
+        public final String getLocalName(int index) {
+            return attribute(index).qName.getLocalPart();
+        }
+
+        public final String getType(int index) {
+            return attribute(index).type;
+        }
+
+        /*public String getType(String uri, String localName) {
+            int index = getIndex(uri, localName);
+            return index == -1 ? null: getType(index);
+         } */
+
+        public final String getURI(int index) {
+            return attribute(index).uri;
+        }
+
+        public final String getValue(int index) {
+            return attribute(index).value;
+        }
+
+        /*
+         * @param uri Never null
+         */
+        public final String getValue(String uri, String localName) {
+            int index = getIndex(uri, localName);
+            return index == -1 ? null : getValue(index);
+        }
+    }
+
+    static protected class StartElement extends EndElement {
+        final AttributeList attributes;
+
+        protected StartElement(XMLStreamReader reader) {
+            super(reader);
+            int count = reader.getAttributeCount();
+            if (count == 0)
+                attributes = null;
+            else {
+                attributes = new AttributeList(count);
+                int index = 0;
+                do {
+                    Attribute attribute = new Attribute(reader.getAttributeType(index), reader.getAttributeValue(index), reader
+                            .getAttributeName(index), reader.getAttributePrefix(index), reader.getAttributeNamespace(index));
+                    attribute.specified = reader.isAttributeSpecified(index);
+                    attributes.attributes.add(attribute);
+                } while (++index != count);
+            }
+        }
+
+        protected StartElement(String nameSpace, String local, String prefix, Attributes attributeArray, Locator locator, List bindings,
+                final NamespaceContext context) {
+            super(nameSpace, local, prefix, locator);
+            nameSpaces = bindings;
+            nameSpaceContext = bindings == null || bindings.isEmpty() ? context : new NamespaceContext() {
+                public String getNamespaceURI(String prefix) {
+                    for (int index = nameSpaces.size(); index != 0;) {
+                        NameSpace binding = (NameSpace) nameSpaces.get(--index);
+                        if (binding.prefix.equals(prefix))
+                            return binding.uri;
+                    }
+                    return context.getNamespaceURI(prefix);
+                }
+
+                public String getPrefix(String namespaceURI) {
+                    for (int index = nameSpaces.size(); index != 0;) {
+                        NameSpace binding = (NameSpace) nameSpaces.get(--index);
+                        if (binding.uri.equals(namespaceURI))
+                            return binding.prefix;
+                    }
+                    return context.getPrefix(namespaceURI);
+                }
+
+                public Iterator getPrefixes(final String namespaceURI) {
+                    final Iterator iterator = context.getPrefixes(namespaceURI);
+                    return new Iterator() {
+                        Iterator bindings = nameSpaces.iterator();
+
+                        NameSpace binding/* = null */;
+
+                        protected final boolean prefix() {
+                            while (bindings.hasNext()) {
+                                binding = (NameSpace) bindings.next();
+                                if (binding.uri.equals(namespaceURI))
+                                    return true;
+                            }
+                            bindings = null;
+                            return false;
+                        }
+
+                        public boolean hasNext() {
+                            return bindings != null && prefix() || iterator.hasNext();
+                        }
+
+                        protected NameSpace nameSpace;
+
+                        public Object next() {
+                            if (bindings == null || binding == null && !prefix())
+                                return iterator.next();
+                            nameSpace = binding;
+                            binding = null;
+                            return nameSpace.prefix;
+                        }
+
+                        public void remove() {
+                            if (bindings == null)
+                                iterator.remove();
+                            else
+                                nameSpaces.remove(nameSpace);
+                        }
+                    };
+                }
+            };
+            int count = attributeArray.getLength();
+            if (count == 0)
+                attributes = null;
+            else {
+                attributes = new AttributeList(count);
+                int index = 0;
+                do {
+                    QName name;
+                    nameSpace = attributeArray.getURI(index);
+                    local = attributeArray.getLocalName(index);
+                    prefix = prefix(attributeArray.getQName(index), nameSpace);
+                    if (prefix == null) {
+                        name = new QName(nameSpace, local, XMLConstants.DEFAULT_NS_PREFIX);
+                        nameSpace = null;
+                    } else
+                        name = new QName(nameSpace, local, prefix);
+                    attributes.attributes.add(new Attribute(attributeArray.getType(index), attributeArray.getValue(index), name, prefix, nameSpace));
+                } while (++index != count);
+            }
+        }
+    }
+
+    static public class Tag extends StartElement {
+        public Tag(XMLStreamReader reader) {
+            super(reader);
+            initialize(reader);
+        }
+
+        public List events/* = null */; // may be empty
+
+        protected final void events() {
+            events = new ArrayList();
+        }
+
+        public Tag(String nameSpace, String local, String prefix, Attributes attributes, Locator locator, NamespaceContext context, List bindings) {
+            super(nameSpace, local, prefix, attributes, locator, bindings, context);
+            events();
+        }
+
+        static public void bind(String prefix, String nameSpace, Collection nameSpaces) {
+            nameSpaces.add(new NameSpace(prefix, nameSpace));
+        }
+
+        protected int nest/* = 0 */;
+
+        public final void start(String nameSpace, String local, String qName, Attributes attributes, Locator locator, List bindings) {
+            Event event;
+            for (int index = events.size();/* true */;) {
+                if (index == 0) {
+                    event = this;
+                    break;
+                }
+                event = (Event) events.get(--index);
+                if (event.type != END_ELEMENT)
+                    break;
+                siblings: for (int nest = 0;/* true */;)
+                    switch (((Event) events.get(--index)).type) {
+                    case START_ELEMENT:
+                        if (nest == 0)
+                            break siblings;
+                        --nest;
+                        break;
+                    case END_ELEMENT:
+                        ++nest;
+                    }
+            }
+            Event start = new StartElement(nameSpace, local, prefix(qName, nameSpace), attributes, locator, bindings, event.nameSpaceContext);
+            start.type = START_ELEMENT;
+            events.add(start);
+            ++nest;
+        }
+
+        protected final void  add (Event event)
+        {
+            int index = events.size();
+            event.nameSpaceContext = index == 0 ? nameSpaceContext : ((Event) events.get(--index)).nameSpaceContext;
+            events.add(event);
+        }
+
+        public final void text(int type, String value, Locator locator) {
+            Event event = new ValueEvent(value);
+            event.type = type;
+            event.location(locator);
+            //int index = events.size();
+            add(event);
+        }
+
+        public final boolean end(String nameSpace, String local, String qName, Locator locator) {
+            Event end = new EndElement(nameSpace, local, prefix(qName, nameSpace), locator);
+            end.type = END_ELEMENT;
+            add(end);
+            if (nest == 0)
+                return true;
+            --nest;
+            return false;
+        }
+
+        public final XMLStreamReader play(final XMLResource resource) {
+            return new RecordedEventXMLStreamReader(this) {
+                public void close() {
+                }
+
+                public String getCharacterEncodingScheme() {
+                    return null; // TODO
+                }
+
+                public String getEncoding() {
+                    return resource.getEncoding();
+                }
+
+                public Object getProperty(String property) {
+                    return null; // TODO javax.xml.stream.notations & javax.xml.stream.entities for DTD
+                }
+
+                public String getVersion() {
+                    return resource.getXMLVersion();
+                }
+
+                public boolean isStandalone() {
+                    return false; // TODO
+                }
+
+                public boolean standaloneSet() {
+                    return false; // TODO
+                }
+            };
+        }
+
+        protected final void add(Event event, int type, XMLStreamReader reader) {
+            event.type = type;
+            event.initialize(reader);
+            events.add(event);
+        }
+
+        public final boolean record(XMLStreamReader reader) throws XMLStreamException {
+            events();
+            for (int nest = 0; reader.hasNext();) {
+                Event event;
+                int type = reader.next();
+                switch (type) {
+                case CHARACTERS:
+                case CDATA:
+                case COMMENT:
+                case SPACE:
+                case DTD:
+                    event = new ValueEvent(reader.getText());
+                    break;
+                case ENTITY_REFERENCE:
+                    event = new Reference(reader.getLocalName(), reader.getText());
+                    break;
+                case PROCESSING_INSTRUCTION:
+                    event = new Reference(reader.getPITarget(), reader.getPIData());
+                    break;
+                case ATTRIBUTE:
+                    event = new AttributeEvent(reader);
+                    break;
+                case NAMESPACE:
+                    event = new NameSpaceEvent(reader);
+                    break;
+                case START_ELEMENT:
+                    ++nest;
+                    event = new StartElement(reader);
+                    break;
+                case END_ELEMENT:
+                    add(new EndElement(reader), type, reader);
+                    if (nest == 0)
+                        return false;
+                    --nest;
+                    continue;
+                case END_DOCUMENT:
+                    return true; // report error?
+                default: // new type
+                    event = new Event();
+                }
+                add(event, type, reader);
+            }
+            return true; // report error?
+        }
+
+        public final XMLStreamReader play(final XMLStreamReader reader) {
+            return new RecordedEventXMLStreamReader(this) {
+                public void close() throws XMLStreamException {
+                    reader.close();
+                }
+
+                public String getCharacterEncodingScheme() {
+                    return reader.getCharacterEncodingScheme();
+                }
+
+                public String getEncoding() {
+                    return reader.getEncoding();
+                }
+
+                public Object getProperty(String property) {
+                    return reader.getProperty(property); // TODO javax.xml.stream.notations & javax.xml.stream.entities for DTD
+                }
+
+                public String getVersion() {
+                    return reader.getVersion();
+                }
+
+                public boolean isStandalone() {
+                    return reader.isStandalone();
+                }
+
+                public boolean standaloneSet() {
+                    return reader.standaloneSet();
+                }
+            };
+        }
+    }
+
+    Event event;
+
+    final List events;
+
+    final int size;
+
+    protected RecordedEventXMLStreamReader(Tag tag) {
+        event = tag;
+        tag.type = START_ELEMENT;
+        events = tag.events;
+        size = events.size();
+    }
+
+    public int getAttributeCount() {
+        switch (getEventType()) {
+        case START_ELEMENT:
+            AttributeList attributes = ((StartElement) event).attributes;
+            return attributes == null ? 0 : attributes.getLength();
+        case ATTRIBUTE:
+            return ((AttributeEvent) event).attributes;
+        }
+        throw new IllegalStateException("Neither START_ELEMENT nor ATTRIBUTE");
+    }
+
+    protected final AttributeList attributes() {
+        if (getEventType() == START_ELEMENT)
+            return ((StartElement) event).attributes;
+        throw new IllegalStateException("Neither START_ELEMENT nor ATTRIBUTE");
+    }
+
+    public String getAttributeLocalName(int index) {
+        return attributes().getLocalName(index);
+    }
+
+    static Attribute attribute(AttributeList attributes, int index) {
+        return (Attribute) attributes.attributes.get(index);
+    }
+
+    public QName getAttributeName(int index) {
+        return getEventType() == ATTRIBUTE ? ((AttributeEvent) event).name : attribute(attributes(), index).qName;
+    }
+
+    public String getAttributeNamespace(int index) {
+        return getEventType() == ATTRIBUTE ? ((AttributeEvent) event).nameSpace : attributes().getURI(index);
+    }
+
+    public String getAttributePrefix(int index) {
+        return getEventType() == ATTRIBUTE ? ((AttributeEvent) event).prefix : attribute(attributes(), index).prefix;
+    }
+
+    public String getAttributeType(int index) {
+        return getEventType() == ATTRIBUTE ? ((Reference) event).target : attributes().getType(index);
+    }
+
+    public String getAttributeValue(int index) {
+        return getEventType() == ATTRIBUTE ? ((ValueEvent) event).value : attributes().getValue(index);
+    }
+
+    public boolean isAttributeSpecified(int index) {
+        if (getEventType() == ATTRIBUTE)
+            return ((AttributeEvent) event).specified;
+        AttributeList attributes = attributes();
+        return attribute(attributes, index).specified;
+    }
+
+    public String getAttributeValue(String nameSpace, String name) {
+        if (getEventType() == ATTRIBUTE) {
+            AttributeEvent attribute = (AttributeEvent) event;
+            return !attribute.name.getLocalPart().equals(name) ? null : nameSpace == null ? (attribute.nameSpace == null ? attribute.value : null)
+                    : nameSpace.equals(attribute.nameSpace) ? attribute.value : null;
+        }
+        AttributeList attributes = attributes();
+        return attributes == null ? null : attributes.getValue(nameSpace == null ? "" : nameSpace, name);
+    }
+
+    protected StringBuffer buffer/* = null */;
+
+    public String getElementText() {
+        if (buffer != null)
+            buffer.delete(0, buffer.length());
+        for (;;)
+            switch (next()) {
+            case END_ELEMENT:
+                return buffer == null ? null : buffer.toString();
+            default:
+                if (buffer == null)
+                    buffer = new StringBuffer();
+                buffer.append(getText());
+            case PROCESSING_INSTRUCTION:
+            case COMMENT:
+            }
+    }
+
+    public final int getEventType() {
+        return event.type;
+    }
+
+    public String getLocalName() {
+        if (getEventType() == ENTITY_REFERENCE)
+            return ((Reference) event).target;
+        if (event instanceof EndElement)
+            return ((EndElement) event).name.getLocalPart();
+        throw new IllegalStateException("Neither START_ELEMENT, END_ELEMENT nor ENTITY_REFERENCE");
+    }
+
+    public final Location getLocation() {
+        return event.location;
+    }
+
+    public QName getName() {
+        if (hasName())
+            return ((EndElement) event).name;
+        throw new IllegalStateException("Neither START_ELEMENT nor END_ELEMENT");
+    }
+
+    public final NamespaceContext getNamespaceContext() {
+        return event.nameSpaceContext;
+    }
+
+    public int getNamespaceCount() {
+        if (getEventType() == NAMESPACE)
+            return ((NameSpaceEvent) event).nameSpaces;
+        if (!(event instanceof EndElement))
+            throw new IllegalStateException("Neither START_ELEMENT, END_ELEMENT nor NAMESPACE");
+        Collection nameSpaces = ((EndElement) event).nameSpaces;
+        return nameSpaces == null ? 0 : nameSpaces.size();
+    }
+
+    protected final NameSpace getNameSpace(int index) {
+        if (event instanceof EndElement)
+            return (NameSpace) ((EndElement) event).nameSpaces.get(index);
+        throw new IllegalStateException("Neither START_ELEMENT, END_ELEMENT nor NAMESPACE");
+    }
+
+    public String getNamespacePrefix(int index) {
+        return getEventType() == NAMESPACE ? ((Reference) event).target : getNameSpace(index).prefix;
+    }
+
+    public final String getNamespaceURI() {
+        switch (getEventType()) {
+        case ATTRIBUTE:
+            return ((AttributeEvent) event).nameSpace;
+        case NAMESPACE:
+            return ((ValueEvent) event).value;
+        }
+        return event instanceof EndElement ? ((EndElement) event).nameSpace : null;
+    }
+
+    public String getNamespaceURI(String prefix) {
+        return getNamespaceContext().getNamespaceURI(prefix);
+    }
+
+    public String getNamespaceURI(int index) {
+        return getEventType() == NAMESPACE ? ((ValueEvent) event).value : getNameSpace(index).uri;
+    }
+
+    public String getPIData() {
+        return getEventType() == PROCESSING_INSTRUCTION ? ((ValueEvent) event).value : null;
+    }
+
+    public String getPITarget() {
+        return getEventType() == PROCESSING_INSTRUCTION ? ((Reference) event).target : null;
+    }
+
+    public String getPrefix() {
+        switch (getEventType()) {
+        case ATTRIBUTE:
+            return ((AttributeEvent) event).prefix;
+        case NAMESPACE:
+            return ((Reference) event).target;
+        }
+        return event instanceof EndElement ? ((EndElement) event).prefix : null;
+    }
+
+    public final String getText() {
+        if (hasText())
+            return ((ValueEvent) event).value;
+        throw new IllegalStateException("Neither CHARACTERS, CDATA, COMMENT, SPACE, ENTITY_REFERENCE nor DTD");
+    }
+
+    public final char[] getTextCharacters() {
+        switch (getEventType()) {
+        case CHARACTERS:
+        case CDATA:
+        case COMMENT:
+        case SPACE:
+            return ((ValueEvent) event).value.toCharArray();
+        }
+        throw new IllegalStateException("Neither CHARACTERS, CDATA, COMMENT nor SPACE");
+    }
+
+    public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length) {
+        char[] source = getTextCharacters();
+        if (sourceStart > source.length)
+            throw new IndexOutOfBoundsException("source start > source length");
+        int sourceLen = source.length - sourceStart;
+        if (length > sourceLen)
+            length = sourceLen;
+        System.arraycopy(source, sourceStart, target, targetStart, length);
+        return sourceLen;
+    }
+
+    public int getTextLength() {
+        return getTextCharacters().length;
+    }
+
+    public int getTextStart() {
+        return 0;
+    }
+
+    public final boolean hasName() {
+        return event instanceof EndElement;
+    }
+
+    protected int next/* = 0 */;
+
+    public final boolean hasNext() {
+        return next != size;
+    }
+
+    public final boolean hasText() {
+        switch (getEventType()) {
+        case CHARACTERS:
+        case CDATA:
+        case COMMENT:
+        case SPACE:
+        case ENTITY_REFERENCE:
+        case DTD:
+            return true;
+        }
+        return false;
+    }
+
+    public boolean isCharacters() {
+        switch (getEventType()) {
+        case CHARACTERS:
+        case CDATA:
+        case SPACE:
+            return true;
+        }
+        return false;
+    }
+
+    public boolean isEndElement() {
+        return getEventType() == END_ELEMENT;
+    }
+
+    public boolean isStartElement() {
+        return getEventType() == START_ELEMENT;
+    }
+
+    protected final boolean areWhiteSpace() {
+        String text = getText();
+        for (int index = text.length(); index != 0;)
+            if (!Character.isWhitespace(text.charAt(--index)))
+                return false;
+        return true;
+    }
+
+    public boolean isWhiteSpace() {
+        switch (getEventType()) {
+        case CHARACTERS:
+        case CDATA:
+            return areWhiteSpace();
+        case SPACE:
+            return true;
+        }
+        return false;
+    }
+
+    public final int next() {
+        if (!hasNext())
+            throw new NoSuchElementException();
+        event = (Event) events.get(next++);
+        return event.type;
+    }
+
+    protected final void throwXMLStreamException(String message) throws XMLStreamException {
+        throw new XMLStreamException(message, getLocation());
+    }
+
+    public int nextTag() throws XMLStreamException {
+        for (;;) {
+            int type = next();
+            switch (type) {
+            case CHARACTERS:
+            case CDATA:
+                if (!areWhiteSpace())
+                    break;
+            case SPACE:
+            case PROCESSING_INSTRUCTION:
+            case COMMENT:
+                continue;
+            case START_ELEMENT:
+            case END_ELEMENT:
+                return type;
+            }
+            throwXMLStreamException("expected start or end tag");
+        }
+    }
+
+    public void require(int type, String nameSpace, String name) throws XMLStreamException {
+        if (getEventType() != type)
+            throwXMLStreamException("type not matched");
+        if (nameSpace != null && !nameSpace.equals(getNamespaceURI()))
+            throwXMLStreamException("Name Space not matched");
+        if (name != null
+                && !(getEventType() == ATTRIBUTE ? name.equals(((AttributeEvent) event).name.getLocalPart()) : event instanceof EndElement
+                        && name.equals(((EndElement) event).name.getLocalPart())))
+            throwXMLStreamException("name not matched");
+    }
+}
diff --git a/impl/src/main/java/org/apache/tuscany/sdo/util/resource/SDODeserializer.java b/impl/src/main/java/org/apache/tuscany/sdo/util/resource/SDODeserializer.java
index af14f13..01c043b 100644
--- a/impl/src/main/java/org/ap