View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements. See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership. The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License. You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied. See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.ws.commons.schema;
21  
22  import org.apache.ws.commons.schema.constants.Constants;
23  import org.apache.ws.commons.schema.extensions.ExtensionRegistry;
24  import org.apache.ws.commons.schema.utils.NamespacePrefixList;
25  import org.w3c.dom.*;
26  
27  import javax.xml.namespace.QName;
28  import javax.xml.parsers.DocumentBuilder;
29  import javax.xml.parsers.DocumentBuilderFactory;
30  import javax.xml.parsers.ParserConfigurationException;
31  import java.util.*;
32  public class XmlSchemaSerializer {
33  
34      /**
35       * Extension registry for the serializer
36       *  */
37  
38      private ExtensionRegistry extReg;
39  
40      public ExtensionRegistry getExtReg() {
41          return extReg;
42      }
43  
44      public void setExtReg(ExtensionRegistry extReg) {
45          this.extReg = extReg;
46      }
47  
48  
49      private Hashtable schema_ns;
50  
51      static String xsdPrefix = "xs";
52      public static final String xsdNamespace = "http://www.w3.org/2001/XMLSchema";
53      ArrayList docs;
54      Element schemaElement;
55  
56      private static final String XMLNS_NAMESPACE_URI = "http://www.w3.org/2000/xmlns/";
57  
58      XmlSchemaSerializer() {
59          docs = new ArrayList();
60          schema_ns = new Hashtable();
61      }
62  
63      /**
64       * *********************************************************************
65       * Document[]  serializeSchema(XmlSchema schemaObj,
66       * boolean serializeIncluded)
67       * <p/>
68       * Serialize XmlSchema object pass back the document containing a schema
69       * element as its root.
70       * <p/>
71       * Parameter:
72       * schemaObj - Schema object to serialize.
73       * serialzeIncluded - whether to serialize the included(imported)
74       * schema or not. pass true for serialize all included
75       * schema.
76       * <p/>
77       * Return:
78       * Array of Documents that include/imported.
79       * **********************************************************************
80       */
81      public Document[] serializeSchema(XmlSchema schemaObj,
82                                               boolean serializeIncluded) throws XmlSchemaSerializerException {
83          return serializeSchemaElement(schemaObj, serializeIncluded);
84      }
85  
86      Document[] serializeSchemaElement(XmlSchema schemaObj,
87                                        boolean serializeIncluded) throws XmlSchemaSerializerException {
88  
89          XmlSchemaObjectCollection items = schemaObj.getItems();
90          Document serializedSchemaDocs;
91          try {
92              DocumentBuilderFactory docFac = DocumentBuilderFactory.newInstance();
93              docFac.setNamespaceAware(true);
94              DocumentBuilder builder = docFac.newDocumentBuilder();
95              serializedSchemaDocs = builder.newDocument();
96          } catch (ParserConfigurationException e) {
97              throw new XmlSchemaException(e.getMessage());
98          }
99  
100         Element serializedSchema;
101 
102         serializedSchema = setupNamespaces(serializedSchemaDocs, schemaObj);
103         schemaElement = serializedSchema;
104 
105         if (schemaObj.syntacticalTargetNamespace != null) {
106             serializedSchema.setAttribute("targetNamespace", schemaObj.syntacticalTargetNamespace);
107 
108             Object targetNS =
109                     schema_ns.get(schemaObj.syntacticalTargetNamespace);
110 
111             //if the namespace is not entered then add 
112             //the targetNamespace as its
113             if (targetNS == null) {
114                 if(!Constants.XMLNS_URI.equals(schemaObj.syntacticalTargetNamespace)){
115                     serializedSchema.setAttributeNS(XMLNS_NAMESPACE_URI,
116                             "xmlns", schemaObj.syntacticalTargetNamespace);
117                 }
118                 String prefix = null;
119                 if(schemaObj.getNamespaceContext() != null) {
120                     prefix = schemaObj.getNamespaceContext().getPrefix(schemaObj.syntacticalTargetNamespace);
121                 }
122                 if(prefix == null && schemaObj.parent != null && schemaObj.parent.getNamespaceContext() != null) {
123                     prefix = schemaObj.parent.getNamespaceContext().getPrefix(schemaObj.syntacticalTargetNamespace);
124                 }
125                 if(prefix == null) {
126                     prefix = "";
127                 }
128                 schema_ns.put(schemaObj.syntacticalTargetNamespace, prefix);
129             }
130         }
131 
132 
133         //todo: implement xml:lang, 
134         if (schemaObj.attributeFormDefault != null) {
135             String formQualified = schemaObj.attributeFormDefault.getValue();
136 
137             if (!formQualified.equals(XmlSchemaForm.NONE))
138                 serializedSchema.setAttribute("attributeFormDefault", convertString(formQualified));
139         }
140 
141         if (schemaObj.elementFormDefault != null) {
142             String formQualified = schemaObj.elementFormDefault.getValue();
143 
144             if (!formQualified.equals(XmlSchemaForm.NONE))
145                 serializedSchema.setAttribute("elementFormDefault", convertString(formQualified));
146         }
147 
148 
149         if (schemaObj.annotation != null) {
150             Element annotation = serializeAnnotation(serializedSchemaDocs,
151                     schemaObj.annotation, schemaObj);
152             serializedSchema.appendChild(annotation);
153         }
154         if (schemaObj.id != null) {
155             serializedSchema.setAttribute("id",
156                     schemaObj.id);
157         }
158         if (schemaObj.blockDefault != null) {
159             String blockDefault = schemaObj.blockDefault.getValue();
160             if (!blockDefault.equals(Constants.BlockConstants.NONE)) {
161                 blockDefault = convertString(blockDefault);
162                 serializedSchema.setAttribute("blockDefault", blockDefault);
163             }
164         }
165         if (schemaObj.finalDefault != null) {
166             String finalDefault = schemaObj.finalDefault.getValue();
167             if (!finalDefault.equals(Constants.BlockConstants.NONE)) {
168                 finalDefault = convertString(finalDefault);
169                 serializedSchema.setAttribute("finalDefault", finalDefault);
170             }
171         }
172 
173         if (schemaObj.version != null) {
174             serializedSchema.setAttribute("version", schemaObj.version);
175         }
176 
177         //add the extra namespace decalarations if any are available
178         NamespacePrefixList ctx = schemaObj.getNamespaceContext();
179         String[] prefixes = ctx.getDeclaredPrefixes();
180         for (int i = 0;  i < prefixes.length;  i++) {
181             String prefix = prefixes[i];
182             String uri = ctx.getNamespaceURI(prefix);
183             if (!Constants.DEFAULT_NS_PREFIX.equals(prefix)) {
184                 serializedSchema.setAttributeNS(Constants.XMLNS_ATTRIBUTE_NS_URI,
185                         Constants.XMLNS_ATTRIBUTE + ":" + prefix, uri);
186             }
187         }
188 
189         //after serialize the schema add into documentation
190         //and add to document collection array  which at the end 
191         //returned
192         serializeSchemaChild(items, serializedSchema, serializedSchemaDocs,
193                 schemaObj, serializeIncluded);
194 
195         //process extension elements/attributes
196         processExtensibilityComponents(schemaObj,serializedSchema);
197 
198 
199         serializedSchemaDocs.appendChild(serializedSchema);
200         docs.add(serializedSchemaDocs);
201 
202 
203         Document[] serializedDocs = new Document[docs.size()];
204         docs.toArray(serializedDocs);
205 
206         return serializedDocs;
207     }
208 
209     private void serializeSchemaChild(XmlSchemaObjectCollection items,
210                                       Element serializedSchema, Document serializedSchemaDocs,
211                                       XmlSchema schemaObj, boolean serializeIncluded)
212             throws XmlSchemaSerializerException {
213 
214         int itemsLength = items.getCount();
215         /**
216          * For each of the items that belong to this schema, 
217          * serialize each member found.  
218          * Permittable member is: element, simpleType, complexType,
219          * group, attrributeGroup, Attribute, include, import and redefine.
220          * if any of the member found then serialize the component.
221          */
222 
223         // Since imports and includes need to be the first items of the
224         // serialized schema. So this loop does the serialization of the
225         // imports and includes
226 
227         for (int i = 0; i < itemsLength; i++) {
228             XmlSchemaObject obj = items.getItem(i);
229             if (obj instanceof XmlSchemaInclude) {
230                 Element e = serializeInclude(serializedSchemaDocs,
231                         (XmlSchemaInclude) obj, schemaObj, serializeIncluded);
232                 serializedSchema.appendChild(e);
233             } else if (obj instanceof XmlSchemaImport) {
234                 Element e = serializeImport(serializedSchemaDocs,
235                         (XmlSchemaImport) obj, schemaObj, serializeIncluded);
236                 serializedSchema.appendChild(e);
237             }
238         }
239 
240         // reloop to serialize the others
241         for (int i = 0; i < itemsLength; i++) {
242             XmlSchemaObject obj = items.getItem(i);
243 
244             if (obj instanceof XmlSchemaElement) {
245                 Element e = serializeElement(serializedSchemaDocs,
246                         (XmlSchemaElement) obj, schemaObj);
247                 serializedSchema.appendChild(e);
248 
249             } else if (obj instanceof XmlSchemaSimpleType) {
250                 Element e = serializeSimpleType(serializedSchemaDocs,
251                         (XmlSchemaSimpleType) obj, schemaObj);
252                 serializedSchema.appendChild(e);
253             } else if (obj instanceof XmlSchemaComplexType) {
254                 Element e = serializeComplexType(serializedSchemaDocs,
255                         (XmlSchemaComplexType) obj, schemaObj);
256                 serializedSchema.appendChild(e);
257             } else if (obj instanceof XmlSchemaGroup) {
258                 Element e = serializeGroup(serializedSchemaDocs,
259                         (XmlSchemaGroup) obj, schemaObj);
260                 serializedSchema.appendChild(e);
261             } else if (obj instanceof XmlSchemaAttributeGroup) {
262                 Element e = serializeAttributeGroup(serializedSchemaDocs,
263                         (XmlSchemaAttributeGroup) obj, schemaObj);
264                 serializedSchema.appendChild(e);
265             } else if (obj instanceof XmlSchemaAttribute) {
266                 Element e = serializeAttribute(serializedSchemaDocs,
267                         (XmlSchemaAttribute) obj, schemaObj);
268                 serializedSchema.appendChild(e);
269             } else if (obj instanceof XmlSchemaRedefine) {
270                 Element e = serializeRedefine(serializedSchemaDocs,
271                         (XmlSchemaRedefine) obj, schemaObj);
272                 serializedSchema.appendChild(e);
273             }
274         }
275     }
276 
277     /**
278      * Set up <schema> namespaces appropriately and append that attr
279      * into specified element
280      */
281     private Element setupNamespaces(Document schemaDocs, XmlSchema schemaObj) {
282         NamespacePrefixList ctx = schemaObj.getNamespaceContext();
283         schemaObj.schema_ns_prefix = xsdPrefix = ctx.getPrefix(xsdNamespace);
284         if(xsdPrefix == null) {
285             schemaObj.schema_ns_prefix = xsdPrefix = "";
286         }
287         String[] prefixes = ctx.getDeclaredPrefixes();
288         for (int i = 0;  i < prefixes.length;  i++) {
289             String prefix = prefixes[i];
290             String uri = ctx.getNamespaceURI(prefix);
291             if(uri != null && prefix != null) {
292                 schema_ns.put(uri, prefix);
293             }
294         }
295         //for schema that not set the xmlns attrib member
296         if (schema_ns.get(xsdNamespace) == null) {
297             schema_ns.put(xsdNamespace, xsdPrefix);
298             schemaObj.schema_ns_prefix = xsdPrefix;
299         }
300 
301         Element schemaEl = createNewElement(schemaDocs, "schema",
302                 schemaObj.schema_ns_prefix, XmlSchema.SCHEMA_NS);
303 
304         Iterator entries = schema_ns.entrySet().iterator();
305 
306         while (entries.hasNext()) {
307             //let it crash for null pointer because then either the schema
308             //is wrong(namespace not set properly or bug in setting ns)
309             Map.Entry entry = (Map.Entry) entries.next();
310             String key = entry.getKey().toString();
311             String value = entry.getValue().toString();
312             value = (value.length() > 0) ? "xmlns:" + value : "xmlns";
313             schemaEl.setAttributeNS(XMLNS_NAMESPACE_URI,
314                     value, key);
315         }
316         return schemaEl;
317     }
318 
319     /**
320      * *********************************************************************
321      * Element serializeInclude(Document doc, XmlSchemaInclude includeObj,
322      * XmlSchema schema)throws XmlSchemaSerializerException
323      * <p/>
324      * set appropriate attribute as per this object attribute availability.
325      * Call included schema to append to this schema document collection.
326      * Then add the document created into document pool.
327      * <p/>
328      * Parameter:
329      * doc          - Document the parent use.
330      * includeObj   - XmlSchemaInclude that will be serialized.
331      * schema       - Schema Document object of the parent.
332      * <p/>
333      * Return:
334      * Element object representation of XmlSchemaInclude
335      * **********************************************************************
336      */
337     Element serializeInclude(Document doc, XmlSchemaInclude includeObj,
338                              XmlSchema schema, boolean serializeIncluded)
339             throws XmlSchemaSerializerException {
340 
341         Element includeEl = createNewElement(doc, "include",
342                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
343 
344         if (includeObj.schemaLocation != null) {
345             includeEl.setAttribute("schemaLocation",
346                     includeObj.schemaLocation);
347         }
348 
349         if (includeObj.id != null)
350             includeEl.setAttribute("id", includeObj.id);
351 
352         if (includeObj.annotation != null) {
353             Element annotation = serializeAnnotation(doc,
354                     includeObj.annotation, schema);
355             includeEl.appendChild(annotation);
356         }
357 
358         //Get the XmlSchema obj and append that to the content
359         XmlSchema includedSchemaObj = includeObj.getSchema();
360         if (includedSchemaObj != null && serializeIncluded) {
361             XmlSchemaSerializer includeSeri = new XmlSchemaSerializer();
362             includeSeri.serializeSchemaElement(includedSchemaObj, true);
363 //            XmlSchemaObjectCollection ii = includedSchemaObj.getItems();
364             docs.addAll(includeSeri.docs);
365         }
366 
367         //process includes
368         processExtensibilityComponents(includeObj,includeEl);
369 
370         return includeEl;
371     }
372 
373     /**
374      * *********************************************************************
375      * Element serializeImport(Document doc, XmlSchemaImport importObj,
376      * XmlSchema schema)throws XmlSchemaSerializerException
377      * <p/>
378      * Add each of the attribute of XmlSchemaImport obj into import Element
379      * Then serialize schema that is included by this import.  Include the
380      * serialized schema into document pool.
381      * <p/>
382      * Parameter:
383      * doc          - Document the parent use.
384      * includeObj   - XmlSchemaInclude that will be serialized.
385      * schema       - Schema Document object of the parent.
386      * <p/>
387      * Return:
388      * Element object representation of XmlSchemaImport
389      * **********************************************************************
390      */
391     Element serializeImport(Document doc, XmlSchemaImport importObj,
392                             XmlSchema schema, boolean serializeIncluded)
393             throws XmlSchemaSerializerException {
394 
395         Element importEl = createNewElement(doc, "import",
396                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
397 
398         if (importObj.namespace != null)
399             importEl.setAttribute("namespace",
400                     importObj.namespace);
401 
402         if (importObj.schemaLocation != null && !importObj.schemaLocation.trim().equals(""))
403             importEl.setAttribute("schemaLocation",
404                     importObj.schemaLocation);
405 
406         if (importObj.id != null)
407             importEl.setAttribute("id", importObj.id);
408 
409         if (importObj.annotation != null) {
410             Element annotation = serializeAnnotation(doc,
411                     importObj.annotation, schema);
412 
413             importEl.appendChild(annotation);
414         }
415 
416         if (importObj.schema != null && serializeIncluded) {
417 
418 
419             XmlSchemaSerializer importSeri = new XmlSchemaSerializer();
420             importSeri.serializeSchemaElement(importObj.schema, serializeIncluded);
421             docs.addAll(importSeri.docs);
422         }
423 
424          //process extension
425         processExtensibilityComponents(importObj,importEl);
426 
427         return importEl;
428     }
429 
430     /**
431      * *********************************************************************
432      * Element serializeRedefine(Document doc, XmlSchemaRedefine redefineObj,
433      * XmlSchema schema)throws XmlSchemaSerializerException
434      * <p/>
435      * Add each of the attribute of XmlSchemaImport obj into import Element
436      * Then serialize schema that is included by this import.  Include the
437      * serialized schema into document pool.
438      * <p/>
439      * Parameter:
440      * doc           - Document the parent use.
441      * redefineObj   - XmlSchemaInclude that will be serialized.
442      * schema        - Schema Document object of the parent.
443      * <p/>
444      * Return:
445      * Element object representation of XmlSchemaRedefine
446      * **********************************************************************
447      */
448     Element serializeRedefine(Document doc, XmlSchemaRedefine redefineObj,
449                               XmlSchema schema) throws XmlSchemaSerializerException {
450 
451         Element redefine = createNewElement(doc, "redefine",
452                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
453 
454         if (redefineObj.schemaLocation != null)
455             redefine.setAttribute("schemaLocation",
456                     redefineObj.schemaLocation);
457         else
458             throw new XmlSchemaSerializerException("redefine must have "
459                     + "schemaLocation fields fill");
460 
461         if (redefineObj.id != null)
462             redefine.setAttribute("id", redefineObj.id);
463 
464         if (redefineObj.annotation != null) {
465             Element annotation = serializeAnnotation(doc,
466                     redefineObj.annotation, schema);
467             redefine.appendChild(annotation);
468         }
469         int itemsLength = redefineObj.items.getCount();
470         for (int i = 0; i < itemsLength; i++) {
471             XmlSchemaObject obj = redefineObj.items.getItem(i);
472             if (obj instanceof XmlSchemaSimpleType) {
473                 Element simpleType = serializeSimpleType(doc,
474                         (XmlSchemaSimpleType) obj, schema);
475                 redefine.appendChild(simpleType);
476             } else if (obj instanceof XmlSchemaComplexType) {
477                 Element complexType = serializeComplexType(doc,
478                         (XmlSchemaComplexType) obj, schema);
479                 redefine.appendChild(complexType);
480             } else if (obj instanceof XmlSchemaGroupRef) {
481                 Element groupRef = serializeGroupRef(doc,
482                         (XmlSchemaGroupRef) obj, schema);
483                 redefine.appendChild(groupRef);
484             } else if (obj instanceof XmlSchemaGroup) {
485                 Element group = serializeGroup(doc,
486                         (XmlSchemaGroup) obj, schema);
487                 redefine.appendChild(group);
488             } else if (obj instanceof XmlSchemaAttributeGroup) {
489                 Element attributeGroup = serializeAttributeGroup(doc,
490                         (XmlSchemaAttributeGroup) obj, schema);
491                 redefine.appendChild(attributeGroup);
492             } else if (obj instanceof XmlSchemaAttributeGroupRef) {
493                 Element attributeGroupRef = serializeAttributeGroupRef(doc,
494                         (XmlSchemaAttributeGroupRef) obj, schema);
495                 redefine.appendChild(attributeGroupRef);
496             }
497         }
498 
499             //process extension
500         processExtensibilityComponents(redefineObj,redefine);
501 
502         return redefine;
503     }
504 
505     /**
506      * *********************************************************************
507      * Element serializeElement(Document doc, XmlSchemaElement elementObj,
508      * XmlSchema schema) throws XmlSchemaSerializerException
509      * <p/>
510      * Each member of Element will be appended and pass the element
511      * created.  Element processed according to w3c Recommendation
512      * May 2 2001.
513      * <p/>
514      * Parameter:
515      * doc           - Document the parent use.
516      * elementObj   - XmlSchemaInclude that will be serialized.
517      * schema        - Schema Document object of the parent.
518      * <p/>
519      * Return:
520      * Element object of element.
521      * **********************************************************************
522      */
523     Element serializeElement(Document doc, XmlSchemaElement elementObj,
524                              XmlSchema schema) throws XmlSchemaSerializerException {
525         Element serializedEl = createNewElement(doc, "element",
526                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
527 
528 
529         if (elementObj.refName != null) {
530 
531             String resolvedName = resolveQName(elementObj.refName, schema);
532             serializedEl.setAttribute("ref", resolvedName);
533         } else if (elementObj.name != null && elementObj.name.length() > 0) {
534             serializedEl.setAttribute("name",
535                     elementObj.name);
536         }
537 
538         if (elementObj.isAbstract)
539             serializedEl.setAttribute("abstract", "true");
540 
541         String block = elementObj.block.getValue();
542         if (!block.equals(Constants.BlockConstants.NONE)) {
543             block = convertString(block);
544             serializedEl.setAttribute("block", block);
545         }
546         if (elementObj.defaultValue != null)
547             serializedEl.setAttribute("default",
548                     elementObj.defaultValue);
549 
550         String finalDerivation = elementObj.finalDerivation.getValue();
551         if (!finalDerivation.equals(Constants.BlockConstants.NONE)) {
552             finalDerivation = convertString(finalDerivation);
553             serializedEl.setAttribute("final",
554                     finalDerivation);
555         }
556         if (elementObj.fixedValue != null)
557             serializedEl.setAttribute("fixed",
558                     elementObj.fixedValue);
559 
560         String formDef = elementObj.form.getValue();
561         if (!formDef.equals(XmlSchemaForm.NONE)) {
562             formDef = convertString(formDef);
563             serializedEl.setAttribute("form", formDef);
564         }
565         if (elementObj.id != null)
566             serializedEl.setAttribute("id", elementObj.id);
567 
568         
569         serializeMaxMinOccurs(elementObj, serializedEl);
570         
571         
572         if (elementObj.substitutionGroup != null) {
573             String resolvedQName = resolveQName(elementObj.substitutionGroup, schema);
574             serializedEl.setAttribute("substitutionGroup",
575                     resolvedQName);
576         }
577         if (elementObj.schemaTypeName != null) {
578             String resolvedName = resolveQName(elementObj.schemaTypeName, schema);
579             serializedEl.setAttribute("type", resolvedName);
580         }
581         if (elementObj.annotation != null) {
582             Element annotationEl = serializeAnnotation(doc,
583                     elementObj.annotation, schema);
584             serializedEl.appendChild(annotationEl);
585         }
586         if (elementObj.schemaType != null && elementObj.schemaTypeName == null) {
587             if (elementObj.schemaType instanceof XmlSchemaComplexType) {
588 
589                 Element complexType = serializeComplexType(doc,
590                         (XmlSchemaComplexType) elementObj.schemaType, schema);
591                 serializedEl.appendChild(complexType);
592             } else if (elementObj.schemaType instanceof XmlSchemaSimpleType) {
593                 Element simpleType = serializeSimpleType(doc,
594                         (XmlSchemaSimpleType) elementObj.schemaType, schema);
595                 serializedEl.appendChild(simpleType);
596             }
597         }
598         if (elementObj.constraints.getCount() > 0) {
599             for (int i = 0; i < elementObj.constraints.getCount(); i++) {
600                 Element constraint = serializeIdentityConstraint(doc,
601                         (XmlSchemaIdentityConstraint) elementObj.constraints.getItem(i),
602                         schema);
603                 serializedEl.appendChild(constraint);
604             }
605         }
606         if (elementObj.isNillable) {
607             serializedEl.setAttribute("nillable", "true");
608         }
609 
610             //process extension
611         processExtensibilityComponents(elementObj,serializedEl);
612 
613         return serializedEl;
614     }
615 
616     /**
617      * *********************************************************************
618      * Element serializeSimpleType(Document doc,
619      * XmlSchemaSimpleType simpleTypeObj, XmlSchema schema)
620      * throws XmlSchemaSerializerException{
621      * <p/>
622      * Each member of simple type will be appended and pass the element
623      * created.  Simple type processed according to w3c Recommendation
624      * May 2 2001.
625      * <p/>
626      * Parameter:
627      * doc               - Document the parent use.
628      * simpleTypeObj     - XmlSchemaSimpleType that will be serialized.
629      * schema            - Schema Document object of the parent.
630      * <p/>
631      * Return:
632      * Element object of SimpleType
633      * **********************************************************************
634      */
635     Element serializeSimpleType(Document doc, XmlSchemaSimpleType simpleTypeObj,
636                                 XmlSchema schema) throws XmlSchemaSerializerException {
637 
638         Element serializedSimpleType = createNewElement(doc, "simpleType",
639                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
640 
641 
642         String tmp;
643         tmp = simpleTypeObj.finalDerivation.getValue();
644         if (!tmp.equals(Constants.BlockConstants.NONE)) {
645 
646             tmp = convertString(tmp);
647             serializedSimpleType.setAttribute("final", tmp);
648         }
649         if (simpleTypeObj.id != null)
650             serializedSimpleType.setAttribute("id",
651                     simpleTypeObj.id);
652         if ((simpleTypeObj.name != null) && (!simpleTypeObj.name.equals("")))
653             serializedSimpleType.setAttribute("name",
654                     simpleTypeObj.name);
655         if (simpleTypeObj.annotation != null) {
656             Element annotationEl = serializeAnnotation(doc,
657                     simpleTypeObj.annotation, schema);
658             serializedSimpleType.appendChild(annotationEl);
659         }
660         if (simpleTypeObj.content != null) {
661             if (simpleTypeObj.content instanceof XmlSchemaSimpleTypeRestriction) {
662                 Element restEl = serializeSimpleTypeRestriction(doc,
663                         (XmlSchemaSimpleTypeRestriction) simpleTypeObj.content,
664                         schema);
665                 serializedSimpleType.appendChild(restEl);
666             } else if (simpleTypeObj.content instanceof XmlSchemaSimpleTypeList) {
667                 Element listEl = serializeSimpleTypeList(doc,
668                         (XmlSchemaSimpleTypeList) simpleTypeObj.content, schema);
669                 serializedSimpleType.appendChild(listEl);
670             } else if (simpleTypeObj.content instanceof XmlSchemaSimpleTypeUnion) {
671                 Element unionEl = serializeSimpleTypeUnion(doc,
672                         (XmlSchemaSimpleTypeUnion) simpleTypeObj.content, schema);
673                 serializedSimpleType.appendChild(unionEl);
674             }/*else 
675 			   throw new XmlSchemaSerializerException("Invalid type inserted "
676 			   + "in simpleType content, the content is: " 
677 			   + simpleTypeObj.content.getClass().getName()
678 			   + " valid content should be XmlSchemaSimpleTypeunion, "
679 			   + "XmlSchemaSimpleTyperestriction or list");*/
680         }/*else
681 		   throw new XmlSchemaSerializerException("simple type must be set "
682 		   + "with content, either union, restriction or list");*/
683 
684             //process extension
685         processExtensibilityComponents(simpleTypeObj,serializedSimpleType);
686 
687         return serializedSimpleType;
688     }
689 
690     /**
691      * *********************************************************************
692      * Element serializeSimpleTypeRestriction(Document doc,
693      * XmlSchemaSimpleTypeRestriction restrictionObj, XmlSchema schema)
694      * throws XmlSchemaSerializerException{
695      * <p/>
696      * Each member of simple type will be appended and pass the element
697      * created.  Simple type's <restriction> processed according to w3c
698      * Recommendation May 2 2001.
699      * <p/>
700      * Parameter:
701      * doc               - Document the parent use.
702      * restrictionObj    - XmlSchemaRestriction that will be serialized.
703      * schema            - Schema Document object of the parent.
704      * <p/>
705      * Return:
706      * Element of simple type restriction and its child.
707      * **********************************************************************
708      */
709     Element serializeSimpleTypeRestriction(Document doc,
710                                            XmlSchemaSimpleTypeRestriction restrictionObj, XmlSchema schema)
711             throws XmlSchemaSerializerException {
712         //todo: need to implement any attribute that related to non schema namespace
713         Element serializedRestriction = createNewElement(doc, "restriction",
714                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
715 
716         if (schema.schema_ns_prefix.length() > 0)
717             serializedRestriction.setPrefix(schema.schema_ns_prefix);
718         if (restrictionObj.baseTypeName != null) {
719             String baseType = resolveQName(restrictionObj.baseTypeName, schema);
720             serializedRestriction.setAttribute("base", baseType);
721         } else if (restrictionObj.baseType != null && restrictionObj.baseType
722                 instanceof XmlSchemaSimpleType) {
723             Element inlineSimpleType = serializeSimpleType(doc,
724                     restrictionObj.baseType, schema);
725             serializedRestriction.appendChild(inlineSimpleType);
726         } else
727             throw new XmlSchemaSerializerException("restriction must be define "
728                     + "with specifying base or inline simpleType");
729 
730         if (restrictionObj.id != null)
731             serializedRestriction.setAttribute("id",
732                     restrictionObj.id);
733 
734         if (restrictionObj.annotation != null) {
735             Element annotation = serializeAnnotation(doc,
736                     restrictionObj.annotation, schema);
737             serializedRestriction.appendChild(annotation);
738         }
739         if (restrictionObj.facets.getCount() > 0) {
740             int facetsNum = restrictionObj.facets.getCount();
741             for (int i = 0; i < facetsNum; i++) {
742                 Element facetEl = serializeFacet(doc,
743                         (XmlSchemaFacet) restrictionObj.facets.getItem(i), schema);
744                 serializedRestriction.appendChild(facetEl);
745             }
746         }
747 
748             //process extension
749         processExtensibilityComponents(restrictionObj,serializedRestriction);
750 
751         return serializedRestriction;
752     }
753 
754     /**
755      * *********************************************************************
756      * Element serializeFacet(Document doc, XmlSchemaFacet facetObj,
757      * XmlSchema schema) throws XmlSchemaSerializerException{
758      * <p/>
759      * detect what type of facet and cass appropriatelly,
760      * construct the element and pass it.
761      * <p/>
762      * Parameter:
763      * doc       - Document the parent use.
764      * facetObj  - XmlSchemaFacet that will be serialized.
765      * schema    - Schema Document object of the parent.
766      * <p/>
767      * Return:
768      * Element of simple type with facet.
769      * **********************************************************************
770      */
771     Element serializeFacet(Document doc, XmlSchemaFacet facetObj,
772                            XmlSchema schema) throws XmlSchemaSerializerException {
773 
774         Element serializedFacet;
775 
776         if (facetObj instanceof XmlSchemaMinExclusiveFacet)
777             serializedFacet = constructFacet(facetObj, doc, schema,
778                     "minExclusive");
779         else if (facetObj instanceof XmlSchemaMinInclusiveFacet)
780             serializedFacet = constructFacet(facetObj, doc, schema,
781                     "minInclusive");
782         else if (facetObj instanceof XmlSchemaMaxExclusiveFacet)
783             serializedFacet = constructFacet(facetObj, doc, schema,
784                     "maxExclusive");
785         else if (facetObj instanceof XmlSchemaMaxInclusiveFacet)
786             serializedFacet = constructFacet(facetObj, doc, schema,
787                     "maxInclusive");
788         else if (facetObj instanceof XmlSchemaTotalDigitsFacet)
789             serializedFacet = constructFacet(facetObj, doc, schema,
790                     "totalDigits");
791         else if (facetObj instanceof XmlSchemaFractionDigitsFacet)
792             serializedFacet = constructFacet(facetObj, doc, schema,
793                     "fractionDigits");
794         else if (facetObj instanceof XmlSchemaLengthFacet)
795             serializedFacet = constructFacet(facetObj, doc, schema,
796                     "length");
797         else if (facetObj instanceof XmlSchemaMinLengthFacet)
798             serializedFacet = constructFacet(facetObj, doc, schema,
799                     "minLength");
800         else if (facetObj instanceof XmlSchemaMaxLengthFacet)
801             serializedFacet = constructFacet(facetObj, doc, schema,
802                     "maxLength");
803         else if (facetObj instanceof XmlSchemaEnumerationFacet)
804             serializedFacet = constructFacet(facetObj, doc, schema,
805                     "enumeration");
806         else if (facetObj instanceof XmlSchemaWhiteSpaceFacet)
807             serializedFacet = constructFacet(facetObj, doc, schema,
808                     "whiteSpace");
809         else if (facetObj instanceof XmlSchemaPatternFacet)
810             serializedFacet = constructFacet(facetObj, doc, schema,
811                     "pattern");
812         else
813             throw new XmlSchemaSerializerException("facet not exist "
814                     + facetObj.getClass().getName());
815 
816         if (facetObj.id != null)
817             serializedFacet.setAttribute("id", facetObj.id);
818 //        if (facetObj.annotation != null) {
819 //            Element annotation = serializeAnnotation(doc, facetObj.annotation,
820 //                                                     schema);
821 //            serializedFacet.appendChild(annotation);
822 //        }
823 
824             //process extension
825         processExtensibilityComponents(facetObj,serializedFacet);
826 
827         return serializedFacet;
828     }
829 
830     private Element constructFacet(XmlSchemaFacet facetObj, Document doc,
831                                    XmlSchema schema, String tagName) {
832 
833         Element facetEl = createNewElement(doc, tagName,
834                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
835 
836         facetEl.setAttribute("value",
837                 facetObj.value.toString());
838         if (facetObj.fixed)
839             facetEl.setAttribute("fixed", "true");
840 
841         if (facetObj.annotation != null) {
842             Element annotation = serializeAnnotation(doc,
843                     facetObj.annotation, schema);
844             facetEl.appendChild(annotation);
845         }
846         return facetEl;
847     }
848 
849     /**
850      * *********************************************************************
851      * Element serializeComplexType(Document doc,
852      * XmlSchemaComplexType complexTypeObj, XmlSchema schema)
853      * throws XmlSchemaSerializerException{
854      * <p/>
855      * Each member of complex type will be appended and pass the element
856      * created.  Complex type processed according to w3c Recommendation
857      * May 2 2001.
858      * <p/>
859      * Parameter:
860      * doc             - Document the parent use.
861      * complexTypeObj  - XmlSchemaFacet that will be serialized.
862      * schema          - Schema Document object of the parent.
863      * <p/>
864      * Return:
865      * Element of complexType.
866      * **********************************************************************
867      */
868     Element serializeComplexType(Document doc,
869                                  XmlSchemaComplexType complexTypeObj, XmlSchema schema)
870             throws XmlSchemaSerializerException {
871 
872         //todo: need to implement abstract, id, mixed
873         Element serializedComplexType = createNewElement(doc,
874                 "complexType", schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
875 
876         if ((complexTypeObj.name != null) && (!complexTypeObj.name.equals("")))
877             serializedComplexType.setAttribute("name",
878                     complexTypeObj.name);
879         /*if(complexTypeObj.annotation != null){
880 		  Element annotationEl = serializeAnnotation(doc, 
881 		  complexTypeObj.annotation, schema);
882 		  serializedComplexType.appendChild(annotationEl);
883 		  }*/
884 
885         if (complexTypeObj.isMixed)
886             serializedComplexType.setAttribute("mixed", "true");
887         if (complexTypeObj.isAbstract)
888             serializedComplexType.setAttribute(
889                     "abstract", "true");
890         if (complexTypeObj.id != null)
891             serializedComplexType.setAttribute("id",
892                     complexTypeObj.id);
893         
894         if (complexTypeObj.annotation != null) {
895             Element annotationEl = serializeAnnotation(doc,
896                     complexTypeObj.annotation, schema);
897             serializedComplexType.appendChild(annotationEl);
898         }
899 
900         if (complexTypeObj.contentModel instanceof XmlSchemaSimpleContent) {
901             Element simpleContent = serializeSimpleContent(doc,
902                     (XmlSchemaSimpleContent) complexTypeObj.contentModel, schema);
903             serializedComplexType.appendChild(simpleContent);
904         } else if (complexTypeObj.contentModel instanceof
905                 XmlSchemaComplexContent) {
906 
907             Element complexContent = serializeComplexContent(doc,
908                     (XmlSchemaComplexContent) complexTypeObj.contentModel, schema);
909             serializedComplexType.appendChild(complexContent);
910         }
911 
912         if (complexTypeObj.particle instanceof XmlSchemaSequence) {
913             Element sequence = serializeSequence(doc,
914                     (XmlSchemaSequence) complexTypeObj.particle, schema);
915             serializedComplexType.appendChild(sequence);
916         } else if (complexTypeObj.particle instanceof XmlSchemaChoice) {
917             Element choice = serializeChoice(doc,
918                     (XmlSchemaChoice) complexTypeObj.particle, schema);
919             serializedComplexType.appendChild(choice);
920         } else if (complexTypeObj.particle instanceof XmlSchemaAll) {
921             Element all = serializeAll(doc,
922                     (XmlSchemaAll) complexTypeObj.particle, schema);
923             serializedComplexType.appendChild(all);
924         } else if (complexTypeObj.particle instanceof XmlSchemaGroupRef) {
925             Element group = serializeGroupRef(doc,
926                     (XmlSchemaGroupRef) complexTypeObj.particle, schema);
927             serializedComplexType.appendChild(group);
928         }
929 
930         String block = complexTypeObj.block.getValue();
931         if (!block.equals(Constants.BlockConstants.NONE)) {
932             block = convertString(block);
933             serializedComplexType.setAttribute(
934                     "block", block);
935         }
936         String finalDerivation = complexTypeObj.finalDerivation.getValue();
937         if (!finalDerivation.equals(Constants.BlockConstants.NONE)) {
938             finalDerivation = convertString(finalDerivation);
939             serializedComplexType.setAttribute("final",
940                     finalDerivation);
941         }
942 
943         XmlSchemaObjectCollection attrColl = complexTypeObj.attributes;
944         if (attrColl.getCount() > 0)
945             setupAttr(doc, attrColl, schema, serializedComplexType);
946 
947             //process extension
948         processExtensibilityComponents(complexTypeObj,serializedComplexType);
949 
950         return serializedComplexType;
951     }
952 
953     /**
954      * *********************************************************************
955      * Element serializeSequence(Document doc, XmlSchemaSequence sequenceObj,
956      * XmlSchema schema)throws XmlSchemaSerializerException{
957      * <p/>
958      * Each member of complex type will be appended and pass the element
959      * created.  `Complex type processed according to w3c Recommendation
960      * May 2 2001.
961      * <p/>
962      * Parameter:
963      * doc             - Document the parent use.
964      * sequenceObj  - XmlSchemaFacet that will be serialized.
965      * schema          - Schema Document object of the parent.
966      * <p/>
967      * Return:
968      * Element of sequence particle.
969      * **********************************************************************
970      */
971     Element serializeSequence(Document doc, XmlSchemaSequence sequenceObj,
972                               XmlSchema schema) throws XmlSchemaSerializerException {
973 
974         Element sequence = createNewElement(doc, "sequence",
975                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
976 
977 
978         if (sequenceObj.id != null)
979             sequence.setAttribute("id", sequenceObj.id);
980 
981 
982         serializeMaxMinOccurs(sequenceObj, sequence);
983 
984         XmlSchemaObjectCollection seqColl = sequenceObj.items;
985         int containLength = seqColl.getCount();
986         for (int i = 0; i < containLength; i++) {
987             XmlSchemaObject obj = seqColl.getItem(i);
988             if (obj instanceof XmlSchemaElement) {
989                 Element el = serializeElement(doc,
990                         (XmlSchemaElement) obj, schema);
991                 sequence.appendChild(el);
992             } else if (obj instanceof XmlSchemaGroupRef) {
993                 Element group = serializeGroupRef(doc,
994                         (XmlSchemaGroupRef) obj, schema);
995                 sequence.appendChild(group);
996             } else if (obj instanceof XmlSchemaChoice) {
997                 Element choice = serializeChoice(doc,
998                         (XmlSchemaChoice) obj, schema);
999                 sequence.appendChild(choice);
1000             } else if (obj instanceof XmlSchemaSequence) {
1001                 Element sequenceChild = serializeSequence(doc,
1002                         (XmlSchemaSequence) obj, schema);
1003                 sequence.appendChild(sequenceChild);
1004             } else if (obj instanceof XmlSchemaAny) {
1005                 Element any = serializeAny(doc, (XmlSchemaAny) obj, schema);
1006                 sequence.appendChild(any);
1007             }
1008         }
1009 
1010             //process extension
1011         processExtensibilityComponents(sequenceObj,sequence);
1012 
1013         return sequence;
1014     }
1015 
1016     /**
1017      * A common method to serialize the max/min occurs
1018      * @param particle
1019      * @param element
1020      */
1021 	private void serializeMaxMinOccurs(XmlSchemaParticle particle,
1022 			Element element) {
1023 		if (particle.maxOccurs < Long.MAX_VALUE &&
1024                 (particle.maxOccurs > 1 || particle.maxOccurs == 0))
1025             element.setAttribute("maxOccurs",
1026                     particle.maxOccurs + "");
1027         else if (particle.maxOccurs == Long.MAX_VALUE)
1028             element.setAttribute("maxOccurs",
1029                     "unbounded");
1030         //else not serialized
1031 
1032         //1 is the default and hence not serialized
1033         //there is no valid case where min occurs can be unbounded!
1034         if (particle.minOccurs > 1 || particle.minOccurs == 0)
1035             element.setAttribute("minOccurs",
1036                     particle.minOccurs + "");
1037 	}
1038 
1039     /**
1040      * *********************************************************************
1041      * Element serializeAttribute(Document doc, XmlSchemaAttribute attributeObj,
1042      * XmlSchema schema) throws XmlSchemaSerializerException{
1043      * <p/>
1044      * Each member of complex type will be appended and pass the element
1045      * created.  `Complex type processed according to w3c Recommendation
1046      * May 2 2001.
1047      * <p/>
1048      * Parameter:
1049      * doc             - Document the parent use.
1050      * attributeObj    - XmlSchemaAttribute that will be serialized.
1051      * schema          - Schema Document object of the parent.
1052      * <p/>
1053      * Return:
1054      * Element of attribute.
1055      * **********************************************************************
1056      */
1057     Element serializeAttribute(Document doc, XmlSchemaAttribute attributeObj,
1058                                XmlSchema schema) throws XmlSchemaSerializerException {
1059 
1060         Element attribute = createNewElement(doc, "attribute",
1061                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1062         if (attributeObj.refName != null) {
1063             String refName =
1064                     resolveQName(attributeObj.refName, schema);
1065             attribute.setAttribute("ref", refName);
1066         } else if (attributeObj.name != null)
1067             attribute.setAttribute("name",
1068                     attributeObj.name);
1069 
1070         if (attributeObj.schemaTypeName != null) {
1071             String typeName =
1072                     resolveQName(attributeObj.schemaTypeName, schema);
1073             attribute.setAttribute("type", typeName);
1074         }
1075 
1076         if (attributeObj.defaultValue != null)
1077             attribute.setAttribute("default",
1078                     attributeObj.defaultValue);
1079         if (attributeObj.fixedValue != null)
1080             attribute.setAttribute("fixed",
1081                     attributeObj.fixedValue);
1082 
1083         String formType = attributeObj.form.getValue();
1084         if (!formType.equals(XmlSchemaForm.NONE)) {
1085             formType = convertString(formType);
1086             attribute.setAttribute("form", formType);
1087         }
1088         if (attributeObj.id != null)
1089             attribute.setAttribute("id", attributeObj.id);
1090 
1091         String useType = attributeObj.use.getValue();
1092         if (!useType.equals(Constants.BlockConstants.NONE)) {
1093             useType = convertString(useType);
1094             attribute.setAttribute("use", useType);
1095         }
1096         if (attributeObj.annotation != null) {
1097             Element annotation = serializeAnnotation(doc,
1098                     attributeObj.annotation, schema);
1099             attribute.appendChild(annotation);
1100         }
1101 
1102 
1103         if (attributeObj.schemaType != null) {
1104             try {
1105                 XmlSchemaSimpleType simpleType =
1106                         attributeObj.schemaType;
1107                 Element simpleTypeEl = serializeSimpleType(doc,
1108                         simpleType, schema);
1109                 attribute.appendChild(simpleTypeEl);
1110             } catch (ClassCastException e) {
1111                 throw new XmlSchemaSerializerException("only inline simple type allow as attribute's inline type");
1112             }
1113         }
1114 
1115         Attr[] unhandled = attributeObj.getUnhandledAttributes();
1116 
1117         Hashtable namespaces = new Hashtable();
1118 
1119         if (unhandled != null) {
1120 
1121             // this is to make the wsdl:arrayType work 
1122             // since unhandles attributes are not handled this is a special case
1123             // but the basic idea is to see if there is any attibute whose value has ":"
1124             // if it is present then it is likely that it is a namespace prefix
1125             // do what is neccesary to get the real namespace for it and make 
1126             // required changes to the prefix 
1127 
1128             for (int i = 0; i < unhandled.length; i++) {
1129                 String name = unhandled[i].getNodeName();
1130                 String value = unhandled[i].getNodeValue();
1131                 if (name.equals("xmlns")) {
1132                     namespaces.put("", value);
1133                 } else if (name.startsWith("xmlns")) {
1134                     namespaces.put(name.substring(name.indexOf(":") + 1), value);
1135                 }
1136             }
1137 
1138             for (int i = 0; i < unhandled.length; i++) {
1139                 String value = unhandled[i].getNodeValue();
1140                 String nodeName = unhandled[i].getNodeName();
1141                 if (value.indexOf(":") > -1 && !nodeName.startsWith("xmlns")) {
1142                     String prefix = value.substring(0, value.indexOf(":"));
1143                     String oldNamespace;
1144                     if ((oldNamespace = (String) namespaces.get(prefix)) != null) {
1145                         value = value.substring(value.indexOf(":") + 1);
1146                         NamespacePrefixList ctx = schema.getNamespaceContext();
1147                         String[] prefixes = ctx.getDeclaredPrefixes();
1148                         for (int j = 0;  j < prefixes.length;  j++) {
1149                             String pref = prefixes[j];
1150                             String uri = ctx.getNamespaceURI(pref);
1151                             if (uri.equals(oldNamespace)) {
1152                                 value = prefix + ":" + value;
1153                             }
1154                         }
1155                     }
1156 
1157                 }
1158                 if (unhandled[i].getNamespaceURI() != null)
1159                     attribute.setAttributeNS(unhandled[i].getNamespaceURI(), nodeName, value);
1160                 else
1161                     attribute.setAttribute(nodeName, value);
1162             }
1163         }
1164 
1165             //process extension
1166         processExtensibilityComponents(attributeObj,attribute);
1167 
1168         return attribute;
1169     }
1170 
1171     /**
1172      * *********************************************************************
1173      * Element serializeChoice(Document doc, XmlSchemaChoice choiceObj,
1174      * XmlSchema schema) throws XmlSchemaSerializerException{
1175      * <p/>
1176      * Each member of complex type will be appended and pass the element
1177      * created.  Complex type processed according to w3c Recommendation
1178      * May 2 2001.
1179      * <p/>
1180      * Parameter:
1181      * doc             - Document the parent use.
1182      * choiceObj       - XmlSchemaChoice that will be serialized.
1183      * schema          - Schema Document object of the parent.
1184      * <p/>
1185      * Return:
1186      * Element of choice schema object.
1187      * **********************************************************************
1188      */
1189     Element serializeChoice(Document doc, XmlSchemaChoice choiceObj,
1190                             XmlSchema schema) throws XmlSchemaSerializerException {
1191         //todo: handle any non schema attri ?
1192 
1193         Element choice = createNewElement(doc, "choice",
1194                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1195         if (choiceObj.id != null)
1196             if (choiceObj.id.length() > 0)
1197                 choice.setAttribute("id", choiceObj.id);
1198 
1199 
1200         serializeMaxMinOccurs(choiceObj, choice);
1201 
1202 
1203         /*
1204             if(choiceObj.maxOccursString != null)
1205             choice.setAttribute("maxOccurs",
1206             choiceObj.maxOccursString);
1207             else if(choiceObj.maxOccurs > 1)
1208             choice.setAttribute("maxOccurs",
1209             choiceObj.maxOccurs +"");
1210           */
1211 
1212 
1213         if (choiceObj.annotation != null) {
1214             Element annotation = serializeAnnotation(doc,
1215                     choiceObj.annotation, schema);
1216             choice.appendChild(annotation);
1217         }
1218 
1219 
1220         XmlSchemaObjectCollection itemColl = choiceObj.items;
1221 
1222         if (itemColl != null) {
1223             int itemLength = itemColl.getCount();
1224 
1225             for (int i = 0; i < itemLength; i++) {
1226                 XmlSchemaObject obj = itemColl.getItem(i);
1227 
1228                 if (obj instanceof XmlSchemaElement) {
1229                     Element el = serializeElement(doc,
1230                             (XmlSchemaElement) obj, schema);
1231                     choice.appendChild(el);
1232                 } else if (obj instanceof XmlSchemaGroupRef) {
1233                     Element group = serializeGroupRef(doc,
1234                             (XmlSchemaGroupRef) obj, schema);
1235                     choice.appendChild(group);
1236                 } else if (obj instanceof XmlSchemaChoice) {
1237                     Element inlineChoice = serializeChoice(doc,
1238                             (XmlSchemaChoice) obj, schema);
1239                     choice.appendChild(inlineChoice);
1240                 } else if (obj instanceof XmlSchemaSequence) {
1241                     Element inlineSequence = serializeSequence(doc,
1242                             (XmlSchemaSequence) obj, schema);
1243                     choice.appendChild(inlineSequence);
1244                 } else if (obj instanceof XmlSchemaAny) {
1245                     Element any = serializeAny(doc, (XmlSchemaAny) obj, schema);
1246                     choice.appendChild(any);
1247                 }
1248             }
1249         }
1250 
1251             //process extension
1252         processExtensibilityComponents(choiceObj,choice);
1253 
1254         return choice;
1255     }
1256 
1257     /**
1258      * *********************************************************************
1259      * Element serializeAll(Document doc, XmlSchemaAll allObj, XmlSchema schema)
1260      * throws XmlSchemaSerializerException{
1261      * <p/>
1262      * Each member of complex type will be appended and pass the element
1263      * created.  Complex type processed according to w3c Recommendation
1264      * May 2 2001.
1265      * <p/>
1266      * Parameter:
1267      * doc             - Document the parent use.
1268      * allObj          - XmlSchemaAll that will be serialized.
1269      * schema          - Schema Document object of the parent.
1270      * <p/>
1271      * Return:
1272      * Element of particle all.
1273      * **********************************************************************
1274      */
1275     Element serializeAll(Document doc, XmlSchemaAll allObj, XmlSchema schema)
1276             throws XmlSchemaSerializerException {
1277         Element allEl = createNewElement(doc, "all", schema.schema_ns_prefix,
1278                 XmlSchema.SCHEMA_NS);
1279 
1280         serializeMaxMinOccurs(allObj, allEl);
1281 
1282         if (allObj.annotation != null) {
1283             Element annotation = serializeAnnotation(doc, allObj.annotation,
1284                     schema);
1285             allEl.appendChild(annotation);
1286         }
1287 
1288         XmlSchemaObjectCollection itemColl = allObj.items;
1289 
1290         if (itemColl != null) {
1291             int itemLength = itemColl.getCount();
1292 
1293             for (int i = 0; i < itemLength; i++) {
1294                 XmlSchemaObject obj = itemColl.getItem(i);
1295                 if (obj instanceof XmlSchemaElement) {
1296                     Element el = serializeElement(doc, (XmlSchemaElement) obj,
1297                             schema);
1298                     allEl.appendChild(el);
1299                 } else
1300                     throw new XmlSchemaSerializerException("Only element "
1301                             + "allowed as child of all model type");
1302             }
1303         }
1304 
1305             //process extension
1306         processExtensibilityComponents(allObj,allEl);
1307 
1308         return allEl;
1309     }
1310 
1311     /**
1312      * *********************************************************************
1313      * Element serializeSimpleTypeList(Document doc,
1314      * XmlSchemaSimpleTypeList listObj, XmlSchema schema)
1315      * throws XmlSchemaSerializerException{
1316      * <p/>
1317      * Each member of complex type will be appended and pass the element
1318      * created.  Complex type processed according to w3c Recommendation
1319      * May 2 2001.
1320      * <p/>
1321      * Parameter:
1322      * doc             - Document the parent use.
1323      * listObj         - XmlSchemaSimpleTypeList that will be serialized.
1324      * schema          - Schema Document object of the parent.
1325      * <p/>
1326      * Return:
1327      * Element of simple type with list method.
1328      * **********************************************************************
1329      */
1330     Element serializeSimpleTypeList(Document doc,
1331                                     XmlSchemaSimpleTypeList listObj, XmlSchema schema)
1332             throws XmlSchemaSerializerException {
1333 
1334         Element list = createNewElement(doc, "list",
1335                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1336 
1337         if (listObj.itemTypeName != null) {
1338             String listItemType = resolveQName(listObj.itemTypeName,
1339                     schema);
1340             list.setAttribute("itemType", listItemType);
1341         }
1342         if (listObj.id != null)
1343             list.setAttribute("id", listObj.id);
1344 
1345         else if (listObj.itemType != null) {
1346             Element inlineSimpleEl = serializeSimpleType(doc, listObj.itemType,
1347                     schema);
1348             list.appendChild(inlineSimpleEl);
1349         }
1350         if (listObj.annotation != null) {
1351             Element annotation = serializeAnnotation(doc, listObj.annotation, schema);
1352             list.appendChild(annotation);
1353         }
1354 
1355             //process extension
1356         processExtensibilityComponents(listObj,list);
1357 
1358         return list;
1359     }
1360 
1361     /**
1362      * *********************************************************************
1363      * Element serializeSimpleTypeUnion(Document doc,
1364      * XmlSchemaSimpleTypeUnion unionObj, XmlSchema schema)
1365      * throws XmlSchemaSerializerException{
1366      * <p/>
1367      * Each member of complex type will be appended and pass the element
1368      * created.  Complex type processed according to w3c Recommendation
1369      * May 2 2001.
1370      * <p/>
1371      * Parameter:
1372      * doc              - Document the parent use.
1373      * unionObj         - XmlSchemaSimpleTypeUnion that will be serialized.
1374      * schema           - Schema Document object of the parent.
1375      * <p/>
1376      * Return:
1377      * Element of simple type with union method.
1378      * **********************************************************************
1379      */
1380     Element serializeSimpleTypeUnion(Document doc,
1381                                      XmlSchemaSimpleTypeUnion unionObj, XmlSchema schema)
1382             throws XmlSchemaSerializerException {
1383 
1384 
1385         Element union = createNewElement(doc, "union",
1386                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1387         if (unionObj.id != null)
1388             union.setAttribute("id", unionObj.id);
1389 
1390         if (unionObj.memberTypesSource != null)
1391             union.setAttribute("memberTypes",
1392                     unionObj.memberTypesSource);
1393         if (unionObj.baseTypes.getCount() > 0) {
1394             int baseTypesLength = unionObj.baseTypes.getCount();
1395             Element baseType;
1396             for (int i = 0; i < baseTypesLength; i++) {
1397                 try {
1398                     baseType = serializeSimpleType(doc,
1399                             (XmlSchemaSimpleType) unionObj.baseTypes.getItem(i),
1400                             schema);
1401                     union.appendChild(baseType);
1402                 } catch (ClassCastException e) {
1403                     throw new XmlSchemaSerializerException("only inline simple type allow as attribute's "
1404                             + "inline type");
1405                 }
1406             }
1407         }
1408         if (unionObj.annotation != null) {
1409             Element annotation = serializeAnnotation(doc, unionObj.annotation,
1410                     schema);
1411             union.appendChild(annotation);
1412         }
1413 
1414             //process extension
1415         processExtensibilityComponents(unionObj,union);
1416 
1417         return union;
1418     }
1419 
1420     /**
1421      * *********************************************************************
1422      * Element serializeAny(Document doc, XmlSchemaAny anyObj, XmlSchema schema)
1423      * <p/>
1424      * Each member of complex type will be appended and pass the element
1425      * created.  Complex type processed according to w3c Recommendation
1426      * May 2 2001.
1427      * <p/>
1428      * Parameter:
1429      * doc              - Document the parent use.
1430      * anyObj           - XmlSchemaAny that will be serialized.
1431      * schema           - Schema Document object of the parent.
1432      * <p/>
1433      * Return:
1434      * Element of any that is part of its parent.
1435      * **********************************************************************
1436      */
1437     Element serializeAny(Document doc, XmlSchemaAny anyObj, XmlSchema schema) {
1438         Element anyEl = createNewElement(doc, "any", schema.schema_ns_prefix,
1439                 XmlSchema.SCHEMA_NS);
1440         if (anyObj.id != null)
1441             if (anyObj.id.length() > 0)
1442                 anyEl.setAttribute("id", anyObj.id);
1443 
1444         serializeMaxMinOccurs(anyObj, anyEl);
1445         
1446 
1447         if (anyObj.namespace != null)
1448             anyEl.setAttribute("namespace",
1449                     anyObj.namespace);
1450 
1451         if (anyObj.processContent != null) {
1452             String value = anyObj.processContent.getValue();
1453             if (!value.equals(Constants.BlockConstants.NONE)) {
1454                 String processContent = convertString(value);
1455                 anyEl.setAttribute("processContents",
1456                         processContent);
1457             }
1458         }
1459         if (anyObj.annotation != null) {
1460             Element annotation = serializeAnnotation(doc,
1461                     anyObj.annotation, schema);
1462             anyEl.appendChild(annotation);
1463         }
1464 
1465             //process extension
1466         processExtensibilityComponents(anyObj,anyEl);
1467 
1468         return anyEl;
1469     }
1470 
1471     /**
1472      * *********************************************************************
1473      * Element serializeGroup(Document doc, XmlSchemaGroup groupObj,
1474      * XmlSchema schema) throws XmlSchemaSerializerException{
1475      * <p/>
1476      * Each member of complex type will be appended and pass the element
1477      * created.  Complex type processed according to w3c Recommendation
1478      * May 2 2001.
1479      * <p/>
1480      * Parameter:
1481      * doc                - Document the parent use.
1482      * groupObj           - XmlSchemaGroup that will be serialized.
1483      * schema             - Schema Document object of the parent.
1484      * <p/>
1485      * Return:
1486      * Element of group elements.
1487      * **********************************************************************
1488      */
1489     Element serializeGroup(Document doc, XmlSchemaGroup groupObj,
1490                            XmlSchema schema) throws XmlSchemaSerializerException {
1491 
1492         Element group = createNewElement(doc, "group",
1493                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1494 
1495         if (groupObj.name != null) {
1496             String grpName = groupObj.name.getLocalPart();
1497             if (grpName.length() > 0) {
1498                 group.setAttribute("name", grpName);
1499             }
1500         } else
1501             throw new XmlSchemaSerializerException("Group must have " +
1502                     "name or ref");
1503 
1504         /* annotations are supposed to be written first!!!!! */
1505         if (groupObj.annotation != null) {
1506             Element annotation = serializeAnnotation(doc,
1507                     groupObj.annotation, schema);
1508             group.appendChild(annotation);
1509         }
1510 
1511         if (groupObj.particle instanceof XmlSchemaSequence) {
1512             Element sequence = serializeSequence(doc,
1513                     (XmlSchemaSequence) groupObj.particle, schema);
1514             group.appendChild(sequence);
1515         } else if (groupObj.particle instanceof XmlSchemaChoice) {
1516             Element choice = serializeChoice(doc,
1517                     (XmlSchemaChoice) groupObj.particle, schema);
1518             group.appendChild(choice);
1519         } else if (groupObj.particle instanceof XmlSchemaAll) {
1520             Element all = serializeAll(doc,
1521                     (XmlSchemaAll) groupObj.particle, schema);
1522             group.appendChild(all);
1523         }
1524 
1525             //process extension
1526         processExtensibilityComponents(groupObj,group);
1527 
1528         return group;
1529     }
1530 
1531     /**
1532      * *********************************************************************
1533      * Element serializeGroupRef(Document doc, XmlSchemaGroupRef groupRefObj,
1534      * XmlSchema schema) throws XmlSchemaSerializerException{
1535      * <p/>
1536      * Each member of complex type will be appended and pass the element
1537      * created.  Complex type processed according to w3c Recommendation
1538      * May 2 2001.
1539      * <p/>
1540      * Parameter:
1541      * doc                   - Document the parent use.
1542      * groupRefObj           - XmlSchemaGroupRef that will be serialized.
1543      * schema                - Schema Document object of the parent.
1544      * <p/>
1545      * Return:
1546      * Element of group elements ref inside its parent.
1547      * **********************************************************************
1548      */
1549     Element serializeGroupRef(Document doc, XmlSchemaGroupRef groupRefObj,
1550                               XmlSchema schema) throws XmlSchemaSerializerException {
1551 
1552         Element groupRef = createNewElement(doc, "group",
1553                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1554 
1555         if (groupRefObj.refName != null) {
1556             String groupRefName = resolveQName(groupRefObj.refName,
1557                     schema);
1558             groupRef.setAttribute("ref", groupRefName);
1559         } else
1560             throw new XmlSchemaSerializerException("Group must have name or ref");
1561 
1562         
1563         serializeMaxMinOccurs(groupRefObj, groupRef);
1564 
1565 
1566 
1567         if (groupRefObj.particle != null) {
1568             if (groupRefObj.particle instanceof XmlSchemaChoice)
1569                 serializeChoice(doc, (XmlSchemaChoice) groupRefObj.particle, schema);
1570             else if (groupRefObj.particle instanceof XmlSchemaSequence)
1571                 serializeSequence(doc,(XmlSchemaSequence) groupRefObj.particle, schema);
1572             else if (groupRefObj.particle instanceof XmlSchemaAll)
1573                 serializeAll(doc,(XmlSchemaAll) groupRefObj.particle, schema);
1574             else
1575                 throw new XmlSchemaSerializerException("The content of group "
1576                         + "ref particle should be"
1577                         + " sequence, choice or all reference:  "
1578                         + "www.w3.org/TR/xmlschema-1#element-group-3.7.2");
1579         }
1580         if (groupRefObj.annotation != null) {
1581             Element annotation = serializeAnnotation(doc,
1582                     groupRefObj.annotation, schema);
1583             groupRef.appendChild(annotation);
1584         }
1585 
1586             //process extension
1587         processExtensibilityComponents(groupRefObj,groupRef);
1588 
1589         return groupRef;
1590     }
1591 
1592     /**
1593      * *********************************************************************
1594      * Element serializeSimpleContent(Document doc,
1595      * XmlSchemaSimpleContent simpleContentObj, XmlSchema schema)
1596      * throws XmlSchemaSerializerException{
1597      * <p/>
1598      * Each member of complex type will be appended and pass the element
1599      * created.  Complex type processed according to w3c Recommendation
1600      * May 2 2001.
1601      * <p/>
1602      * Parameter:
1603      * doc               - Document the parent use.
1604      * simpleContentObj  - XmlSchemaSimpleContent that will be serialized.
1605      * schema            - Schema Document object of the parent.
1606      * <p/>
1607      * Return:
1608      * Element of complex type simple content.
1609      * **********************************************************************
1610      */
1611     Element serializeSimpleContent(Document doc,
1612                                    XmlSchemaSimpleContent simpleContentObj, XmlSchema schema)
1613             throws XmlSchemaSerializerException {
1614         Element simpleContent = createNewElement(doc, "simpleContent",
1615                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1616 
1617         Element content;
1618         if (simpleContentObj.annotation != null) {
1619             Element annotation = serializeAnnotation(doc,
1620                     simpleContentObj.annotation, schema);
1621             simpleContent.appendChild(annotation);
1622         }
1623         if (simpleContentObj.content instanceof
1624                 XmlSchemaSimpleContentRestriction)
1625             content = serializeSimpleContentRestriction(doc,
1626                     (XmlSchemaSimpleContentRestriction) simpleContentObj.content,
1627                     schema);
1628         else if (simpleContentObj.content instanceof
1629                 XmlSchemaSimpleContentExtension)
1630             content = serializeSimpleContentExtension(doc,
1631                     (XmlSchemaSimpleContentExtension) simpleContentObj.content,
1632                     schema);
1633         else
1634             throw new XmlSchemaSerializerException("content of simple content "
1635                     + "must be restriction or extension");
1636 
1637         simpleContent.appendChild(content);
1638 
1639             //process extension
1640         processExtensibilityComponents(simpleContentObj,simpleContent);
1641 
1642         return simpleContent;
1643     }
1644 
1645     /**
1646      * *********************************************************************
1647      * Element serializeComplexContent(Document doc,
1648      * XmlSchemaComplexContent complexContentObj, XmlSchema schema)
1649      * throws XmlSchemaSerializerException{
1650      * <p/>
1651      * Each member of complex type will be appended and pass the element
1652      * created.  Complex type processed according to w3c Recommendation
1653      * May 2 2001.
1654      * <p/>
1655      * Parameter:
1656      * doc                - Document the parent use.
1657      * complexContentObj  - XmlSchemaComplexContent that will be serialized.
1658      * schema             - Schema Document object of the parent.
1659      * <p/>
1660      * Return:
1661      * Element of complex type complex content.
1662      * **********************************************************************
1663      */
1664     Element serializeComplexContent(Document doc,
1665                                     XmlSchemaComplexContent complexContentObj, XmlSchema schema)
1666             throws XmlSchemaSerializerException {
1667 
1668         Element complexContent = createNewElement(doc, "complexContent",
1669                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1670 
1671 
1672         if (complexContentObj.annotation != null) {
1673             Element annotation = serializeAnnotation(doc,
1674                     complexContentObj.annotation, schema);
1675             complexContent.appendChild(annotation);
1676         }
1677 
1678         if (complexContentObj.mixed)
1679             complexContent.setAttribute("mixed", "true");
1680         if (complexContentObj.id != null)
1681             complexContent.setAttribute("id",
1682                     complexContentObj.id);
1683 
1684         Element content;
1685         if (complexContentObj.content instanceof
1686                 XmlSchemaComplexContentRestriction)
1687 
1688             content = serializeComplexContentRestriction(doc,
1689                     (XmlSchemaComplexContentRestriction) complexContentObj.content,
1690                     schema);
1691         else if (complexContentObj.content instanceof
1692                 XmlSchemaComplexContentExtension)
1693             content = serializeComplexContentExtension(doc,
1694                     (XmlSchemaComplexContentExtension) complexContentObj.content,
1695                     schema);
1696         else
1697             throw new XmlSchemaSerializerException("content of complexContent "
1698                     + "must be restriction or extension");
1699 
1700         complexContent.appendChild(content);
1701 
1702             //process extension
1703         processExtensibilityComponents(complexContentObj,complexContent);
1704 
1705         return complexContent;
1706     }
1707 
1708     /**
1709      * *********************************************************************
1710      * Element serializeIdentityConstraint(Document doc,
1711      * XmlSchemaIdentityConstraint constraintObj, XmlSchema schema)
1712      * throws XmlSchemaSerializerException{
1713      * <p/>
1714      * Each member of complex type will be appended and pass the element
1715      * created.  Complex type processed according to w3c Recommendation
1716      * May 2 2001.
1717      * <p/>
1718      * Parameter:
1719      * doc               - Document the parent use.
1720      * constraintObj     - XmlSchemaIdentityConstraint that will be serialized.
1721      * schema            - Schema Document object of the parent.
1722      * <p/>
1723      * Return:
1724      * Element of key, keyref or unique that part of its parent.
1725      * **********************************************************************
1726      */
1727     Element serializeIdentityConstraint(Document doc,
1728                                         XmlSchemaIdentityConstraint constraintObj, XmlSchema schema)
1729             throws XmlSchemaSerializerException {
1730 
1731         Element constraint;
1732 
1733         if (constraintObj instanceof XmlSchemaUnique)
1734             constraint = createNewElement(doc, "unique",
1735                     schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1736         else if (constraintObj instanceof XmlSchemaKey)
1737             constraint = createNewElement(doc, "key",
1738                     schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1739         else if (constraintObj instanceof XmlSchemaKeyref) {
1740             constraint = createNewElement(doc, "keyref",
1741                     schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1742             XmlSchemaKeyref keyref = (XmlSchemaKeyref) constraintObj;
1743             if (keyref.refer != null) {
1744                 String keyrefStr = resolveQName(keyref.refer, schema);
1745                 constraint.setAttribute(
1746                         "refer", keyrefStr);
1747             }
1748         } else
1749             throw new XmlSchemaSerializerException("not valid identity "
1750                     + "constraint");
1751 
1752         if (constraintObj.name != null)
1753             constraint.setAttribute("name",
1754                     constraintObj.name);
1755         if (constraintObj.annotation != null) {
1756             Element annotation = serializeAnnotation(doc,
1757                     constraintObj.annotation, schema);
1758             constraint.appendChild(annotation);
1759         }
1760 
1761         if (constraintObj.selector != null) {
1762             Element selector = serializeSelector(doc,
1763                     constraintObj.selector, schema);
1764             constraint.appendChild(selector);
1765         }
1766         XmlSchemaObjectCollection fieldColl = constraintObj.fields;
1767         if (fieldColl != null) {
1768             int fieldLength = fieldColl.getCount();
1769             for (int i = 0; i < fieldLength; i++) {
1770                 Element field = serializeField(doc,
1771                         (XmlSchemaXPath) fieldColl.getItem(i), schema);
1772                 constraint.appendChild(field);
1773             }
1774         }
1775 
1776             //process extension
1777         processExtensibilityComponents(constraintObj,constraint);
1778 
1779         return constraint;
1780     }
1781 
1782     /**
1783      * *********************************************************************
1784      * Element serializeSelector(Document doc, XmlSchemaXPath selectorObj,
1785      * XmlSchema schema) throws XmlSchemaSerializerException{
1786      * <p/>
1787      * Each member of complex type will be appended and pass the element
1788      * created.  Complex type processed according to w3c Recommendation
1789      * May 2 2001.
1790      * <p/>
1791      * Parameter:
1792      * doc               - Document the parent use.
1793      * selectorObj      - XmlSchemaXPath that will be serialized.
1794      * schema            - Schema Document object of the parent.
1795      * <p/>
1796      * Return:
1797      * Element of selector with collection of xpath as its attrib.  The selector
1798      * itself is the part of identity type.  eg <key><selector xpath="..."
1799      * **********************************************************************
1800      */
1801     Element serializeSelector(Document doc, XmlSchemaXPath selectorObj,
1802                               XmlSchema schema) throws XmlSchemaSerializerException {
1803 
1804         Element selector = createNewElement(doc, "selector",
1805                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1806 
1807         if (selectorObj.xpath != null)
1808             selector.setAttribute("xpath",
1809                     selectorObj.xpath);
1810         else
1811             throw new XmlSchemaSerializerException("xpath can't be null");
1812 
1813         if (selectorObj.annotation != null) {
1814             Element annotation = serializeAnnotation(doc,
1815                     selectorObj.annotation, schema);
1816             selector.appendChild(annotation);
1817         }
1818             //process extension
1819         processExtensibilityComponents(selectorObj,selector);
1820         return selector;
1821     }
1822 
1823     /**
1824      * *********************************************************************
1825      * Element serializeField(Document doc, XmlSchemaXPath fieldObj,
1826      * XmlSchema schema) throws XmlSchemaSerializerException
1827      * <p/>
1828      * Each member of complex type will be appended and pass the element
1829      * created.  Complex type processed according to w3c Recommendation
1830      * May 2 2001.
1831      * <p/>
1832      * Parameter:
1833      * doc           - Document the parent use.
1834      * fieldObj      - XmlSchemaXPath that will be serialized.
1835      * schema        - Schema Document object of the parent.
1836      * <p/>
1837      * Return:
1838      * field element that part of constraint.
1839      * **********************************************************************
1840      */
1841     Element serializeField(Document doc, XmlSchemaXPath fieldObj,
1842                            XmlSchema schema) throws XmlSchemaSerializerException {
1843 
1844         Element field = createNewElement(doc, "field", schema.schema_ns_prefix,
1845                 XmlSchema.SCHEMA_NS);
1846 
1847         if (fieldObj.xpath != null)
1848             field.setAttribute("xpath", fieldObj.xpath);
1849         else
1850             throw new XmlSchemaSerializerException("xpath can't be null");
1851 
1852         if (fieldObj.annotation != null) {
1853             Element annotation = serializeAnnotation(doc,
1854                     fieldObj.annotation, schema);
1855             field.appendChild(annotation);
1856         }
1857 
1858             //process extension
1859         processExtensibilityComponents(fieldObj,field);
1860 
1861         return field;
1862     }
1863 
1864     /**
1865      * *********************************************************************
1866      * Element serializeAnnotation(Document doc, XmlSchemaAnnotation
1867      * annotationObj, XmlSchema schema)
1868      * <p/>
1869      * <p/>
1870      * Each member of complex type will be appended and pass the element
1871      * created.  Complex type processed according to w3c Recommendation
1872      * May 2 2001.
1873      * <p/>
1874      * Parameter:
1875      * doc               - Document the parent use.
1876      * annotationObj      - XmlSchemaAnnotation that will be serialized.
1877      * schema            - Schema Document object of the parent.
1878      * <p/>
1879      * Return:
1880      * annotation element that part of any type. will contain document and
1881      * appinfo for child.
1882      * **********************************************************************
1883      */
1884     Element serializeAnnotation(Document doc, XmlSchemaAnnotation annotationObj,
1885                                 XmlSchema schema) {
1886 
1887         Element annotation = createNewElement(doc, "annotation",
1888                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1889 
1890         XmlSchemaObjectCollection contents = annotationObj.items;
1891         int contentLength = contents.getCount();
1892 
1893         for (int i = 0; i < contentLength; i++) {
1894             XmlSchemaObject obj = contents.getItem(i);
1895 
1896             if (obj instanceof XmlSchemaAppInfo) {
1897                 XmlSchemaAppInfo appinfo = (XmlSchemaAppInfo) obj;
1898                 Element appInfoEl = serializeAppInfo(doc, appinfo, schema);
1899                 annotation.appendChild(appInfoEl);
1900             } else if (obj instanceof XmlSchemaDocumentation) {
1901                 XmlSchemaDocumentation documentation =
1902                         (XmlSchemaDocumentation) obj;
1903 
1904                 Element documentationEl = serializeDocumentation(doc,
1905                         documentation, schema);
1906 
1907 
1908                 annotation.appendChild(documentationEl);
1909             }
1910         }
1911 
1912             //process extension
1913         processExtensibilityComponents(annotationObj,annotation);
1914 
1915         return annotation;
1916     }
1917 
1918     /**
1919      * *********************************************************************
1920      * Element serializeAppInfo(Document doc,XmlSchemaAppInfo appInfoObj,
1921      * XmlSchema schema)
1922      * <p/>
1923      * <p/>
1924      * Each member of complex type will be appended and pass the element
1925      * created.  Complex type processed according to w3c Recommendation
1926      * May 2 2001.
1927      * <p/>
1928      * Parameter:
1929      * doc               - Document the parent use.
1930      * appInfoObj        - XmlSchemaAppInfo that will be serialized.
1931      * schema            - Schema Document object of the parent.
1932      * <p/>
1933      * Return:
1934      * App info element that is part of the annotation.
1935      * **********************************************************************
1936      */
1937     Element serializeAppInfo(Document doc, XmlSchemaAppInfo appInfoObj,
1938                              XmlSchema schema) {
1939 
1940         Element appInfoEl = createNewElement(doc, "appinfo",
1941                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1942         if (appInfoObj.source != null)
1943             appInfoEl.setAttribute("source",
1944                     appInfoObj.source);
1945 
1946         if (appInfoObj.markup != null) {
1947             int markupLength = appInfoObj.markup.getLength();
1948             for (int j = 0; j < markupLength; j++) {
1949                 Node n = appInfoObj.markup.item(j);
1950                appInfoEl.appendChild(doc.importNode(n,true));
1951             }
1952         }
1953 
1954             //process extension
1955         processExtensibilityComponents(appInfoObj,appInfoEl);
1956 
1957         return appInfoEl;
1958     }
1959 
1960     /**
1961      * *********************************************************************
1962      * Element serializeDocumentation(Document doc,XmlSchemaDocumentation
1963      * documentationObj, XmlSchema schema){
1964      * <p/>
1965      * <p/>
1966      * Each member of complex type will be appended and pass the element
1967      * created.  Complex type processed according to w3c Recommendation
1968      * May 2 2001.
1969      * <p/>
1970      * Parameter:
1971      * doc               - Document the parent use.
1972      * documentationObj        - XmlSchemaAppInfo that will be serialized.
1973      * schema            - Schema Document object of the parent.
1974      * <p/>
1975      * Return:
1976      * Element representation of documentation that is part of annotation.
1977      * **********************************************************************
1978      */
1979     Element serializeDocumentation(Document doc, XmlSchemaDocumentation
1980             documentationObj, XmlSchema schema) {
1981 
1982 
1983         Element documentationEl = createNewElement(doc, "documentation",
1984                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
1985         if (documentationObj.source != null)
1986             documentationEl.setAttribute("source",
1987                     documentationObj.source);
1988         if (documentationObj.language != null)
1989             documentationEl.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:lang",
1990                     documentationObj.language);
1991 
1992         if (documentationObj.markup != null) {
1993             int markupLength = documentationObj.markup.getLength();
1994             for (int j = 0; j < markupLength; j++) {
1995                 Node n = documentationObj.markup.item(j);
1996 
1997                 switch (n.getNodeType()) {
1998                     case Node.ELEMENT_NODE:
1999                         appendElement(doc, documentationEl, n, schema);
2000                         break;
2001                     case Node.TEXT_NODE:
2002                         Text t = doc.createTextNode(n.getNodeValue());
2003                         documentationEl.appendChild(t);
2004                         break;
2005                     default:
2006                         break;
2007                 }
2008             }
2009         }
2010             //process extension
2011         processExtensibilityComponents(documentationObj,documentationEl);
2012 
2013         return documentationEl;
2014     }
2015 
2016     /**
2017      * *********************************************************************
2018      * Element serializeSimpleContentRestriction(Document doc,
2019      * XmlSchemaSimpleContentRestriction restrictionObj, XmlSchema schema)
2020      * throws XmlSchemaSerializerException{
2021      * <p/>
2022      * <p/>
2023      * Each member of complex type will be appended and pass the element
2024      * created.  Complex type processed according to w3c Recommendation
2025      * May 2 2001.
2026      * <p/>
2027      * Parameter:
2028      * doc               - Document the parent use.
2029      * restrictionObj    - XmlSchemaSimpleContentRestriction that will be
2030      * serialized.
2031      * schema            - Schema Document object of the parent.
2032      * <p/>
2033      * Return:
2034      * Element of simple content restriction.
2035      * **********************************************************************
2036      */
2037     Element serializeSimpleContentRestriction(Document doc,
2038                                               XmlSchemaSimpleContentRestriction restrictionObj, XmlSchema schema)
2039             throws XmlSchemaSerializerException {
2040 
2041         Element restriction = createNewElement(doc, "restriction",
2042                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
2043 
2044         if (restrictionObj.baseTypeName != null) {
2045             String baseTypeName =
2046                     resolveQName(restrictionObj.baseTypeName, schema);
2047 
2048             restriction.setAttribute("base", baseTypeName);
2049 
2050         }
2051         if (restrictionObj.id != null)
2052             restriction.setAttribute("id", restrictionObj.id);
2053 
2054         if (restrictionObj.annotation != null) {
2055             Element annotation = serializeAnnotation(doc,
2056                     restrictionObj.annotation, schema);
2057             restriction.appendChild(annotation);
2058         }
2059         int attrCollLength = restrictionObj.attributes.getCount();
2060         for (int i = 0; i < attrCollLength; i++) {
2061             XmlSchemaObject obj = restrictionObj.attributes.getItem(i);
2062 
2063             if (obj instanceof XmlSchemaAttribute) {
2064                 Element attribute = serializeAttribute(doc,
2065                         (XmlSchemaAttribute) obj, schema);
2066                 restriction.appendChild(attribute);
2067             } else if (obj instanceof XmlSchemaAttributeGroupRef) {
2068                 Element attributeGroup = serializeAttributeGroupRef(doc,
2069                         (XmlSchemaAttributeGroupRef) obj, schema);
2070                 restriction.appendChild(attributeGroup);
2071             }
2072         }
2073         if (restrictionObj.baseType != null) {
2074             Element inlineSimpleType = serializeSimpleType(doc,
2075                     restrictionObj.baseType, schema);
2076             restriction.appendChild(inlineSimpleType);
2077         }
2078         if (restrictionObj.anyAttribute != null) {
2079             Element anyAttribute = serializeAnyAttribute(doc,
2080                     restrictionObj.anyAttribute, schema);
2081             restriction.appendChild(anyAttribute);
2082         }
2083         XmlSchemaObjectCollection facets = restrictionObj.facets;
2084         int facetLength = facets.getCount();
2085         for (int i = 0; i < facetLength; i++) {
2086             Element facet = serializeFacet(doc,
2087                     (XmlSchemaFacet) facets.getItem(i), schema);
2088             restriction.appendChild(facet);
2089         }
2090 
2091             //process extension
2092         processExtensibilityComponents(restrictionObj,restriction);
2093 
2094         return restriction;
2095     }
2096 
2097     /**
2098      * *********************************************************************
2099      * Element serializeSimpleContentExtension(Document doc,
2100      * XmlSchemaSimpleContentExtension extensionObj, XmlSchema schema)
2101      * throws XmlSchemaSerializerException{
2102      * <p/>
2103      * <p/>
2104      * Each member of complex type will be appended and pass the element
2105      * created.  Complex type processed according to w3c Recommendation
2106      * May 2 2001.
2107      * <p/>
2108      * Parameter:
2109      * doc                 - Document the parent use.
2110      * extensionObj        - XmlSchemaSimpleContentExtension
2111      * that will be serialized.
2112      * schema              - Schema Document object of the parent.
2113      * <p/>
2114      * Return:
2115      * Element of simple content extension.
2116      * **********************************************************************
2117      */
2118     Element serializeSimpleContentExtension(Document doc,
2119                                             XmlSchemaSimpleContentExtension extensionObj, XmlSchema schema)
2120             throws XmlSchemaSerializerException {
2121 
2122         Element extension = createNewElement(doc, "extension",
2123                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
2124 
2125         if (extensionObj.baseTypeName != null) {
2126             String baseTypeName =
2127                     resolveQName(extensionObj.baseTypeName, schema);
2128 
2129             extension.setAttribute("base", baseTypeName);
2130         }
2131 
2132         if (extensionObj.id != null)
2133             extension.setAttribute("id", extensionObj.id);
2134 
2135         if (extensionObj.annotation != null) {
2136             Element annotation = serializeAnnotation(doc,
2137                     extensionObj.annotation, schema);
2138             extension.appendChild(annotation);
2139         }
2140 
2141         XmlSchemaObjectCollection attributes = extensionObj.attributes;
2142         int attributeLength = attributes.getCount();
2143         for (int i = 0; i < attributeLength; i++) {
2144             XmlSchemaObject obj = attributes.getItem(i);
2145 
2146             if (obj instanceof XmlSchemaAttribute) {
2147                 Element attribute = serializeAttribute(doc,
2148                         (XmlSchemaAttribute) obj, schema);
2149                 extension.appendChild(attribute);
2150             } else if (obj instanceof XmlSchemaAttributeGroupRef) {
2151                 Element attributeGroupRef = serializeAttributeGroupRef(doc,
2152                         (XmlSchemaAttributeGroupRef) obj, schema);
2153                 extension.appendChild(attributeGroupRef);
2154             }
2155         }
2156 
2157         /*
2158          * anyAttribute must come *after* any other attributes
2159          */
2160         if (extensionObj.anyAttribute != null) {
2161             Element anyAttribute = serializeAnyAttribute(doc,
2162                     extensionObj.anyAttribute, schema);
2163             extension.appendChild(anyAttribute);
2164         }
2165 
2166             //process extension
2167         processExtensibilityComponents(extensionObj,extension);
2168 
2169         return extension;
2170     }
2171 
2172     /**
2173      * *********************************************************************
2174      * Element serializeComplexContentRestriction(Document doc,
2175      * XmlSchemaComplexContentRestriction restrictionObj, XmlSchema schema)
2176      * throws XmlSchemaSerializerException{
2177      * <p/>
2178      * Each member of complex type will be appended and pass the element
2179      * created.  Complex type processed according to w3c Recommendation
2180      * May 2 2001.
2181      * <p/>
2182      * Parameter:
2183      * doc                 - Document the parent use.
2184      * restrictionObj        - XmlSchemaSimpleContentRestriction
2185      * that will be serialized.
2186      * schema              - Schema Document object of the parent.
2187      * <p/>
2188      * Return:
2189      * Element of simple content restriction.
2190      * **********************************************************************
2191      */
2192     Element serializeComplexContentRestriction(Document doc,
2193                                                XmlSchemaComplexContentRestriction restrictionObj, XmlSchema schema)
2194             throws XmlSchemaSerializerException {
2195 
2196         Element restriction = createNewElement(doc, "restriction",
2197                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
2198 
2199         if (restrictionObj.baseTypeName != null) {
2200             String baseTypeName = resolveQName(restrictionObj.baseTypeName, schema);
2201             restriction.setAttribute(
2202                     "base", baseTypeName);
2203         }
2204 
2205         if (restrictionObj.id != null)
2206             restriction.setAttribute("id",
2207                     restrictionObj.id);
2208 
2209         if (restrictionObj.annotation != null) {
2210             Element annotation = serializeAnnotation(doc,
2211                     restrictionObj.annotation, schema);
2212             restriction.appendChild(annotation);
2213         }
2214 
2215         if (restrictionObj.particle instanceof XmlSchemaSequence) {
2216             Element sequenceParticle = serializeSequence(doc,
2217                     (XmlSchemaSequence) restrictionObj.particle, schema);
2218             restriction.appendChild(sequenceParticle);
2219         } else if (restrictionObj.particle instanceof XmlSchemaChoice) {
2220             Element choiceParticle = serializeChoice(doc,
2221                     (XmlSchemaChoice) restrictionObj.particle, schema);
2222             restriction.appendChild(choiceParticle);
2223         } else if (restrictionObj.particle instanceof XmlSchemaAll) {
2224             Element allParticle = serializeAll(doc,
2225                     (XmlSchemaAll) restrictionObj.particle, schema);
2226             restriction.appendChild(allParticle);
2227         } else if (restrictionObj.particle instanceof XmlSchemaGroupRef) {
2228             Element groupRefParticle = serializeGroupRef(doc,
2229                     (XmlSchemaGroupRef) restrictionObj.particle, schema);
2230             restriction.appendChild(groupRefParticle);
2231         }
2232 
2233         int attributesLength = restrictionObj.attributes.getCount();
2234         for (int i = 0; i < attributesLength; i++) {
2235             XmlSchemaObject obj = restrictionObj.attributes.getItem(i);
2236 
2237             if (obj instanceof XmlSchemaAttribute) {
2238                 Element attr = serializeAttribute(doc,
2239                         (XmlSchemaAttribute) obj, schema);
2240                 restriction.appendChild(attr);
2241             } else if (obj instanceof XmlSchemaAttributeGroupRef) {
2242                 Element attrGroup = serializeAttributeGroupRef(doc,
2243                         (XmlSchemaAttributeGroupRef) obj, schema);
2244                 restriction.appendChild(attrGroup);
2245             }
2246         }
2247 
2248         if (restrictionObj.anyAttribute != null) {
2249             Element anyAttribute = serializeAnyAttribute(doc,
2250                     restrictionObj.anyAttribute, schema);
2251             restriction.appendChild(anyAttribute);
2252         }
2253 
2254             //process extension
2255         processExtensibilityComponents(restrictionObj,restriction);
2256 
2257         return restriction;
2258     }
2259 
2260     /**
2261      * *********************************************************************
2262      * Element serializeComplexContentExtension(Document doc,
2263      * XmlSchemaComplexContentExtension extensionObj, XmlSchema schema)
2264      * throws XmlSchemaSerializerException{
2265      * <p/>
2266      * Each member of complex type will be appended and pass the element
2267      * created.  Complex type processed according to w3c Recommendation
2268      * May 2 2001.
2269      * <p/>
2270      * Parameter:
2271      * doc                 - Document the parent use.
2272      * extensionObj        - XmlSchemaComplexContentRestriction
2273      * that will be serialized.
2274      * schema              - Schema Document object of the parent.
2275      * <p/>
2276      * Return:
2277      * Element of complex content extension.
2278      * **********************************************************************
2279      */
2280     Element serializeComplexContentExtension(Document doc,
2281                                              XmlSchemaComplexContentExtension extensionObj, XmlSchema schema)
2282             throws XmlSchemaSerializerException {
2283 
2284         Element extension = createNewElement(doc, "extension",
2285                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
2286         if (extensionObj.baseTypeName != null) {
2287             String baseType = resolveQName(extensionObj.baseTypeName,
2288                     schema);
2289             extension.setAttribute("base", baseType);
2290         }
2291         if (extensionObj.annotation != null) {
2292             Element annotation = serializeAnnotation(doc,
2293                     extensionObj.annotation, schema);
2294             extension.appendChild(annotation);
2295         }
2296 
2297 
2298         if (extensionObj.particle instanceof XmlSchemaSequence) {
2299             Element sequenceParticle = serializeSequence(doc,
2300                     (XmlSchemaSequence) extensionObj.particle, schema);
2301             extension.appendChild(sequenceParticle);
2302         } else if (extensionObj.particle instanceof XmlSchemaChoice) {
2303             Element choiceParticle = serializeChoice(doc,
2304                     (XmlSchemaChoice) extensionObj.particle, schema);
2305             extension.appendChild(choiceParticle);
2306         } else if (extensionObj.particle instanceof XmlSchemaAll) {
2307             Element allParticle = serializeAll(doc,
2308                     (XmlSchemaAll) extensionObj.particle, schema);
2309             extension.appendChild(allParticle);
2310         } else if (extensionObj.particle instanceof XmlSchemaGroupRef) {
2311             Element groupRefParticle = serializeGroupRef(doc,
2312                     (XmlSchemaGroupRef) extensionObj.particle, schema);
2313             extension.appendChild(groupRefParticle);
2314         }
2315 
2316         int attributesLength = extensionObj.attributes.getCount();
2317         for (int i = 0; i < attributesLength; i++) {
2318             XmlSchemaObject obj = extensionObj.attributes.getItem(i);
2319 
2320             if (obj instanceof XmlSchemaAttribute) {
2321                 Element attr = serializeAttribute(doc,
2322                         (XmlSchemaAttribute) obj, schema);
2323                 extension.appendChild(attr);
2324             } else if (obj instanceof XmlSchemaAttributeGroupRef) {
2325                 Element attrGroup = serializeAttributeGroupRef(doc,
2326                         (XmlSchemaAttributeGroupRef) obj, schema);
2327                 extension.appendChild(attrGroup);
2328             }
2329         }
2330 
2331         if (extensionObj.anyAttribute != null) {
2332             Element anyAttribute = serializeAnyAttribute(doc,
2333                     extensionObj.anyAttribute, schema);
2334             extension.appendChild(anyAttribute);
2335         }
2336 
2337             //process extension
2338         processExtensibilityComponents(extensionObj,extension);
2339 
2340         return extension;
2341     }
2342 
2343     /**
2344      * *********************************************************************
2345      * Element serializeAnyAttribute(Document doc,
2346      * XmlSchemaAnyAttribute anyAttributeObj, XmlSchema schema)
2347      * <p/>
2348      * Each member of complex type will be appended and pass the element
2349      * created.  Complex type processed according to w3c Recommendation
2350      * May 2 2001.
2351      * <p/>
2352      * Parameter:
2353      * doc                 - Document the parent use.
2354      * anyAttributeObj     - XmlSchemaAnyAttribute
2355      * that will be serialized.
2356      * schema              - Schema Document object of the parent.
2357      * <p/>
2358      * Return:
2359      * Element of any attribute element.
2360      * **********************************************************************
2361      */
2362     Element serializeAnyAttribute(Document doc,
2363                                   XmlSchemaAnyAttribute anyAttributeObj, XmlSchema schema) {
2364 
2365         Element anyAttribute = createNewElement(doc, "anyAttribute",
2366                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
2367 
2368 
2369         if (anyAttributeObj.namespace != null)
2370             anyAttribute.setAttribute("namespace",
2371                     anyAttributeObj.namespace);
2372 
2373         if (anyAttributeObj.id != null)
2374             anyAttribute.setAttribute("id",
2375                     anyAttributeObj.id);
2376 
2377         if (anyAttributeObj.processContent != null) {
2378             String processContent = anyAttributeObj.processContent.getValue();
2379             processContent = convertString(processContent);
2380             anyAttribute.setAttribute("processContents",
2381                     processContent);
2382         }
2383         if (anyAttributeObj.annotation != null) {
2384             Element annotation = serializeAnnotation(doc,
2385                     anyAttributeObj.annotation, schema);
2386             anyAttribute.appendChild(annotation);
2387         }
2388 
2389             //process extension
2390         processExtensibilityComponents(anyAttributeObj,anyAttribute);
2391 
2392         return anyAttribute;
2393     }
2394 
2395     /**
2396      * *********************************************************************
2397      * Element serializeAttributeGroupRef(Document doc,
2398      * XmlSchemaAttributeGroupRef attributeGroupObj, XmlSchema schema)
2399      * throws XmlSchemaSerializerException
2400      * <p/>
2401      * Each member of complex type will be appended and pass the element
2402      * created.  Complex type processed according to w3c Recommendation
2403      * May 2 2001.
2404      * <p/>
2405      * Parameter:
2406      * doc                 - Document the parent use.
2407      * attributeGroupObj     - XmlSchemaAttributeGroupRef
2408      * that will be serialized.
2409      * schema              - Schema Document object of the parent.
2410      * <p/>
2411      * Return:
2412      * Element of attribute group ref that part of type.
2413      * **********************************************************************
2414      */
2415     Element serializeAttributeGroupRef(Document doc,
2416                                        XmlSchemaAttributeGroupRef attributeGroupObj, XmlSchema schema)
2417             throws XmlSchemaSerializerException {
2418 
2419         Element attributeGroupRef = createNewElement(doc, "attributeGroup",
2420                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
2421 
2422         if (attributeGroupObj.refName != null) {
2423             String refName = resolveQName(attributeGroupObj.refName,
2424                     schema);
2425             attributeGroupRef.setAttribute("ref", refName);
2426         } else
2427             throw new XmlSchemaSerializerException("Attribute group must have "
2428                     + "ref name set");
2429 
2430         if (attributeGroupObj.id != null)
2431             attributeGroupRef.setAttribute("id",
2432                     attributeGroupObj.id);
2433 
2434         if (attributeGroupObj.annotation != null) {
2435             Element annotation = serializeAnnotation(doc,
2436                     attributeGroupObj.annotation, schema);
2437             attributeGroupRef.appendChild(annotation);
2438         }
2439 
2440             //process extension
2441         processExtensibilityComponents(attributeGroupObj,attributeGroupRef);
2442 
2443         return attributeGroupRef;
2444     }
2445 
2446     /**
2447      * *********************************************************************
2448      * Element serializeAttributeGroup(Document doc,
2449      * XmlSchemaAttributeGroup attributeGroupObj, XmlSchema schema)
2450      * throws XmlSchemaSerializerException{
2451      * <p/>
2452      * Each member of complex type will be appended and pass the element
2453      * created.  Complex type processed according to w3c Recommendation
2454      * May 2 2001.
2455      * <p/>
2456      * Parameter:
2457      * doc                 - Document the parent use.
2458      * attributeGroupObj     - XmlSchemaAttributeGroup
2459      * that will be serialized.
2460      * schema              - Schema Document object of the parent.
2461      * <p/>
2462      * Return:
2463      * Element of attribute group.
2464      * **********************************************************************
2465      */
2466     Element serializeAttributeGroup(Document doc,
2467                                     XmlSchemaAttributeGroup attributeGroupObj, XmlSchema schema)
2468             throws XmlSchemaSerializerException {
2469 
2470         Element attributeGroup = createNewElement(doc, "attributeGroup",
2471                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
2472 
2473         if (attributeGroupObj.name != null) {
2474             String attGroupName = attributeGroupObj.name.getLocalPart();
2475             attributeGroup.setAttribute("name",
2476                     attGroupName);
2477         }else
2478             throw new XmlSchemaSerializerException("Attribute group must"
2479                     + "have name");
2480         if (attributeGroupObj.id != null)
2481             attributeGroup.setAttribute("id",
2482                     attributeGroupObj.id);
2483 
2484         if (attributeGroupObj.annotation != null) {
2485             Element annotation = serializeAnnotation(doc,
2486                     attributeGroupObj.annotation, schema);
2487             attributeGroup.appendChild(annotation);
2488         }
2489         int attributesLength = attributeGroupObj.attributes.getCount();
2490         for (int i = 0; i < attributesLength; i++) {
2491             XmlSchemaObject obj = attributeGroupObj.attributes.getItem(i);
2492 
2493             if (obj instanceof XmlSchemaAttribute) {
2494                 Element attr = serializeAttribute(doc, (XmlSchemaAttribute) obj,
2495                         schema);
2496                 attributeGroup.appendChild(attr);
2497             } else if (obj instanceof XmlSchemaAttributeGroupRef) {
2498                 Element attrGroup = serializeAttributeGroupRef(doc,
2499                         (XmlSchemaAttributeGroupRef) obj, schema);
2500                 attributeGroup.appendChild(attrGroup);
2501             }
2502         }
2503 
2504         if (attributeGroupObj.anyAttribute != null) {
2505             Element anyAttribute = serializeAnyAttribute(doc,
2506                     attributeGroupObj.anyAttribute, schema);
2507             attributeGroup.appendChild(anyAttribute);
2508         }
2509 
2510             //process extension
2511         processExtensibilityComponents(attributeGroupObj,attributeGroup);
2512 
2513         return attributeGroup;
2514     }
2515 
2516     //recursively add any attribute, text and children append all 
2517     //found children base on parent as its root.
2518     private void appendElement(Document doc, Element parent,
2519                                Node children, XmlSchema schema) {
2520         Element elTmp = (Element) children;
2521         Element el = createNewElement(doc, elTmp.getLocalName(),
2522                 schema.schema_ns_prefix, XmlSchema.SCHEMA_NS);
2523         NamedNodeMap attributes = el.getAttributes();
2524         //check if child node has attribute  
2525         //create new element and append it if found
2526         int attributeLength = attributes.getLength();
2527         for (int i = 0; i < attributeLength; i++) {
2528             Node n = attributes.item(i);
2529             //assuming attributes got to throw exception if not later
2530             el.setAttribute(n.getNodeName(),
2531                     n.getNodeValue());
2532         }
2533 
2534         //check any descendant of this node
2535         //if there then append its child
2536         NodeList decendants = el.getChildNodes();
2537         int decendantLength = decendants.getLength();
2538         for (int i = 0; i < decendantLength; i++) {
2539             Node n = decendants.item(i);
2540             short nodeType = n.getNodeType();
2541             if (nodeType == Node.TEXT_NODE) {
2542                 String nValue = n.getNodeValue();
2543                 Text t = doc.createTextNode(nValue);
2544                 el.appendChild(t);
2545             } else if (nodeType == Node.ELEMENT_NODE) {
2546                 appendElement(doc, el, n, schema);
2547             }
2548         }
2549     }
2550 
2551     //break string with prefix into two parts part[0]:prefix , part[1]:namespace
2552     private static String[] getParts(String name) {
2553         String[] parts = new String[2];
2554 
2555         int index = name.indexOf(":");
2556         if (index > -1) {
2557             parts[0] = name.substring(0, index);
2558             parts[1] = name.substring(index + 1);
2559         } else {
2560             parts[0] = "";
2561             parts[1] = name;
2562         }
2563         return parts;
2564     }
2565 
2566     //Convert given string to lower case or w3c standard
2567     private String convertString(String convert) {
2568         String input = convert.trim();
2569         if (input.equals(Constants.BlockConstants.ALL)) {
2570             return "#all";
2571         } else
2572             return input.toLowerCase();
2573     }
2574 
2575     //Create new element with given local name and namespaces check whether
2576     //the prefix is there or not.
2577     private Element createNewElement(Document docs, String localName,
2578                                      String prefix, String namespace) {
2579         String elementName = ((prefix.length() > 0) ? prefix += ":" : "")
2580                 + localName;
2581         return docs.createElementNS(namespace, elementName);
2582     }
2583 
2584     /**
2585      * will search whether the prefix is available in global hash table, if it
2586      * is there than append the prefix to the element name.  If not then it will
2587      * create new prefix corresponding to that namespace and store that in
2588      * hash table.  Finally add the new prefix and namespace to <schema>
2589      * element
2590      * @param names
2591      * @param schemaObj
2592      * @return resolved QName of the string
2593      */
2594 
2595     private String resolveQName(QName names,
2596                                 XmlSchema schemaObj) {
2597 
2598         String namespace = names.getNamespaceURI();
2599         String type[] = getParts(names.getLocalPart());
2600         String typeName = (type.length > 1) ? type[1] : type[0];
2601         String prefixStr;
2602 
2603         // If the namespace is "" then the prefix is also ""
2604         Object prefix = ("".equals(namespace)) ? "" : schema_ns.get(namespace);
2605 
2606         if (prefix == null) {
2607             if (Constants.XMLNS_URI.equals(namespace)) {
2608                 prefix = Constants.XMLNS_PREFIX;
2609             } else {
2610                 int magicNumber = 0;
2611                 Collection prefixes = schema_ns.values();
2612                 while(prefixes.contains("ns" + magicNumber)){
2613                     magicNumber++;
2614                 }
2615                 prefix = "ns" + magicNumber;
2616                 schema_ns.put(namespace, prefix);
2617 
2618                 //setting xmlns in schema
2619                 schemaElement.setAttributeNS(XMLNS_NAMESPACE_URI,
2620                         "xmlns:" + prefix.toString(), namespace);
2621             }
2622         }
2623 
2624         prefixStr = prefix.toString();
2625         prefixStr = (prefixStr.trim().length() > 0) ? prefixStr + ":" : "";
2626 
2627         return prefixStr + typeName;
2628     }
2629 
2630     //for each collection if it is an attribute serialize attribute and 
2631     //append that child to container element.
2632     void setupAttr(Document doc, XmlSchemaObjectCollection collectionObj,
2633                    XmlSchema schema, Element container) throws XmlSchemaSerializerException {
2634         int collectionLength = collectionObj.getCount();
2635         for (int i = 0; i < collectionLength; i++) {
2636             XmlSchemaObject obj = collectionObj.getItem(i);
2637             if (obj instanceof XmlSchemaAttribute) {
2638                 XmlSchemaAttribute attr = (XmlSchemaAttribute) obj;
2639                 Element attrEl = serializeAttribute(doc, attr, schema);
2640                 container.appendChild(attrEl);
2641             } else if (obj instanceof XmlSchemaAttributeGroupRef) {
2642                 XmlSchemaAttributeGroupRef attr = (XmlSchemaAttributeGroupRef) obj;
2643                 Element attrEl = serializeAttributeGroupRef(doc, attr, schema);
2644                 container.appendChild(attrEl);
2645             }
2646         }
2647     }
2648 
2649     public static class XmlSchemaSerializerException extends Exception {
2650 
2651         /**
2652 		 * 
2653 		 */
2654 		private static final long serialVersionUID = 1L;
2655 
2656 		public XmlSchemaSerializerException(String msg) {
2657             super(msg);
2658         }
2659     }
2660 
2661 
2662     /**
2663      * A generic method to process the extra attributes and the the extra
2664      * elements present within the schema.
2665      * What are considered extensions are  child elements with non schema namespace
2666      * and child attributes with any namespace
2667      * @param schemaObject
2668      * @param parentElement
2669      */
2670     private void processExtensibilityComponents(XmlSchemaObject schemaObject,Element parentElement){
2671 
2672         if (extReg!=null){
2673             Map metaInfoMap = schemaObject.getMetaInfoMap();
2674             if (metaInfoMap!=null && !metaInfoMap.isEmpty()) {
2675                 //get the extra objects and call the respective deserializers
2676                 Iterator keysIt = metaInfoMap.keySet().iterator();
2677                 while (keysIt.hasNext()) {
2678                     Object key =  keysIt.next();
2679                     extReg.serializeExtension(schemaObject,metaInfoMap.get(key).getClass(),parentElement);
2680 
2681                 }
2682 
2683             }
2684 
2685         }
2686 
2687     }
2688 
2689 }