KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > schema2beansdev > JavaBeanClass


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.schema2beansdev;
21
22 import java.util.*;
23 import java.io.*;
24
25 import org.netbeans.modules.schema2beans.*;
26 import org.netbeans.modules.schema2beansdev.metadd.*;
27 import org.netbeans.modules.schema2beansdev.gen.*;
28
29 public class JavaBeanClass extends AbstractCodeGeneratorClass implements CodeGeneratorClass {
30     // No element type number can be this one.
31
final protected int elementTypeSetnull = -1;
32     private Map/*QName, String*/ declaredQNames = new HashMap();
33     private boolean loggerDeclared = false;
34
35     JavaBeanClass(BeanBuilder.BeanElement be, GenBeans.Config config) {
36         init(be, config);
37     }
38
39     /**
40      * Generate the java code in the out stream, using the optional
41      * metaDD bean graph.
42      */

43     public void generate(OutputStream out, MetaDD mdd) throws IOException {
44         this.mdd = mdd;
45         metaElement = getMetaElement(beanElement);
46     
47         if (metaElement != null && metaElement.isSkipGeneration()) {
48             config.messageOut.println(Common.getMessage("MSG_SkippingGeneration"));
49             return;
50         }
51
52         findAttributeOwners();
53         
54         genAllParts();
55
56         select(DECL_SECTION);
57         cr();
58
59         printGenBuffers(out);
60     }
61
62     protected void genAllParts() throws IOException {
63         genHeader(HEADER_SECTION);
64         genPackage(HEADER_SECTION);
65         genImports(HEADER_SECTION);
66         genClassName(HEADER_SECTION);
67
68         genConstructor();
69         genAccessors();
70         if (!config.isMinFeatures())
71             genDeepCopy();
72
73         if (config.isGenerateXMLIO() || config.isDumpToString()) {
74             genXMLIO();
75         }
76         if (config.isStaxProduceXMLEventReader())
77             genFetchXMLEventReader();
78         
79         if (config.isGenerateValidate()) {
80             genValidate();
81         }
82         if (config.isGeneratePropertyEvents()) {
83             genPropertyEvents();
84         }
85         if (config.isGenerateStoreEvents()) {
86             genStoreEvents();
87         }
88         if (config.isVetoable()) {
89             genVetoable();
90         }
91         if (config.isGenerateTransactions()) {
92             genTransactions();
93         }
94         if (config.isGenerateHasChanged()) {
95             genHasChanged();
96         }
97         if (config.isGenerateSwitches()) {
98             generateSwitches();
99         }
100         if (!config.isMinFeatures())
101             genPropertiesByName();
102         if (config.isKeepElementPositions()) {
103             genElementPositions();
104         }
105         if (beanElement.isRoot && config.isProcessDocType()) {
106             genProcessDocType();
107         }
108
109         if (!config.isMinFeatures()) {
110             genName();
111
112             genChildBeans();
113         }
114         genEqualsHashCode();
115         if (config.isDumpToString()) {
116             genToString();
117         }
118         if (config.isExtendBaseBean())
119             genExtendBaseBean();
120
121         genTrailer(TRAILER_SECTION);
122         genFinishClass(TRAILER_SECTION);
123
124         try {
125             select(TRAILER_SECTION);
126             printSchema();
127         } catch (IOException ioe) {
128             // Do not generate the schema comment
129
}
130     }
131
132     protected void genMadeChange() throws IOException {
133         if (config.isGenerateHasChanged()) {
134             jw.writeEol("_setChanged(true)");
135         }
136     }
137
138     /**
139      * Whenever we create a constructor, call this method first.
140      */

141     protected void genExtendBaseBeanConstructor() throws IOException {
142         if (config.isExtendBaseBean()) {
143             jw.writeEol("super(null, baseBeanRuntimeVersion)");
144             //jw.writeEol("System.out.println(\"Created class \"+getClass())");
145
}
146     }
147
148     public void genHeader(int out) throws IOException {
149         select(out);
150         gencr("/**");
151         gencr(" * This generated bean class " + className);
152         gencr(" * matches the schema element '" + beanElement.node.getName()+"'.");
153         if (!beanElement.isRoot) {
154             jw.writecr(" * The root bean class is "+rootBeanElement.getClassType());
155         }
156         gencr(" *");
157         printComment(" * ");
158         if (config.isGenerateTimeStamp())
159             gencr(" * Generated on " + new Date());
160         if (beanElement.isRoot) {
161             gencr(" *");
162             gencr(" * This class matches the root element of the "+(config.getSchemaTypeNum() == GenBeans.Config.DTD ? "DTD" : "XML Schema")+",");
163             gencr(" * and is the root of the bean graph.");
164             gencr(" *");
165         
166             dumpBeanTree(jw, " * "+jw.getIndent(), jw.getIndent());
167             gencr(" *");
168         }
169         gencr(" * @"+Common.GENERATED_TAG);
170         gencr(" */"); cr();
171     }
172
173     public void genPackage(int out) {
174         select(out);
175         if (packageName != null) {
176             gen(PACKAGE, packageName);
177             eol();
178             cr();
179         }
180     }
181
182     public void genImports(int out) {
183         select(out);
184     }
185
186     public void genClassName(int out) throws IOException {
187         String JavaDoc name = null;
188         String JavaDoc impName = null;
189     
190         select(out);
191         jw.write("public ");
192         // disable this for now: things are setup to new this class.
193
if (false && beanElement.isAbstract)
194             jw.write("abstract ");
195         jw.write("class ", className);
196         //gen(PUBLIC, CLASS, className);
197

198         if (mdd != null) {
199             if (metaElement != null) {
200                 name = metaElement.getExtends();
201                 impName = metaElement.getImplements();
202             }
203             if (name == null) {
204                 name = mdd.getExtends();
205             }
206             if (impName == null) {
207                 impName = mdd.getImplements();
208             }
209         }
210     
211         if (name != null) {
212             gen(" extends ");
213             gencr(name);
214         }
215         if (impName != null) {
216             gen(" implements ", impName);
217         }
218
219         sp();
220         begin();
221     }
222
223     public void genConstructor() throws IOException {
224         int size = attrList.size();
225         if (!config.isMinFeatures()) {
226             jw.select(DECL_SECTION);
227             for (int i = 0; i < size; i++) {
228                 Property a = (Property)attrList.get(i);
229                 jw.write("public static final String ", a.constName,
230                          " = \"", a.name);
231                 jw.writeEolNoI18N("\"");
232             }
233             jw.cr();
234         }
235         
236         jw.select(CONSTRUCTOR_SECTION);
237         jw.bigComment("Normal starting point constructor.");
238         jw.beginConstructor(className);
239         if (config.isExtendBaseBean()) {
240             jw.select(DECL_SECTION);
241             jw.write("private static final org.netbeans.modules.schema2beans.Version baseBeanRuntimeVersion = new org.netbeans.modules.schema2beans.Version(" +
242                      Version.MAJVER, ", ");
243             jw.write(Version.MINVER + ", ");
244             jw.writeEol(Version.PTCVER + ")");
245             jw.select(CONSTRUCTOR_SECTION);
246             jw.writeEol("this(null, baseBeanRuntimeVersion)");
247             jw.end();
248             jw.cr();
249             jw.bigComment("This constructor is here for BaseBean compatibility.");
250             jw.beginConstructor(className, "java.util.Vector comps, org.netbeans.modules.schema2beans.Version baseBeanRuntimeVersion");
251         }
252         genExtendBaseBeanConstructor();
253
254         if (config.isMakeDefaults() || config.isSetDefaults()) {
255             for (int i = 0; i < size; i++) {
256                 Property a = (Property)attrList.get(i);
257                 boolean indexed = a.isIndexed();
258                 boolean isScalar = a.isScalar();
259                 if (indexed || isScalar || a.ored)
260                     continue;
261                 if (a.getDefaultValue() != null)
262                     continue;
263                 String JavaDoc type = a.getType();
264                 String JavaDoc attr = "_"+a.name;
265                 if (a.elementInstance == Common.TYPE_1) {
266                     // There has to be at least 1 of them.
267
List exceps = JavaUtil.exceptionsFromParsingText(type, false);
268                     if (!exceps.isEmpty()) {
269                         jw.beginTry();
270                     }
271                     gen(attr, " = ");
272                     genNewDefault(a, true);
273                     eol();
274                     if (a.isBean && config.isGenerateParentRefs()) {
275                         jw.writeEol(attr, "._setParent(this)");
276                     }
277                     if (!exceps.isEmpty()) {
278                         end();
279                         genRethrowExceptions(exceps);
280                     }
281                 }
282             }
283         }
284         jw.end();
285         jw.cr();
286
287         // Create a constructor that has all of the required parameters.
288
List requiredParameters = new LinkedList();
289         for (int i = 0; i < size; i++) {
290             Property a = (Property)attrList.get(i);
291             // Is the property optional?
292
if (!a.ored && (a.elementInstance == Common.TYPE_1 || a.elementInstance == Common.TYPE_1_N))
293                 requiredParameters.add(a);
294         }
295         if (!config.isMinFeatures() && requiredParameters.size() > 0) {
296             String JavaDoc parameters = null;
297             for (Iterator it = requiredParameters.iterator(); it.hasNext(); ) {
298                 Property a = (Property) it.next();
299                 if (parameters != null)
300                     parameters += ", ";
301                 else
302                     parameters = "";
303                 String JavaDoc type = a.getType();
304                 String JavaDoc baseType = type;
305                 if (a.isIndexed())
306                     type = baseType + "[]";
307                 String JavaDoc fullClassType = getTypeFullClassName(a, type);
308                 parameters += fullClassType + " " + a.instanceOf();
309             }
310             jw.bigComment("Required parameters constructor");
311             jw.beginConstructor(className, parameters);
312             genExtendBaseBeanConstructor();
313             for (Iterator it = requiredParameters.iterator(); it.hasNext(); ) {
314                 Property a = (Property) it.next();
315                 boolean indexed = a.isIndexed();
316                 String JavaDoc type = a.getType();
317                 String JavaDoc baseType = type;
318                 if (indexed)
319                     type = baseType + "[]";
320                 String JavaDoc attr = "_"+a.name;
321                 SchemaRep.WhiteSpace ws = (SchemaRep.WhiteSpace) a.searchExtraData(SchemaRep.WhiteSpace.class);
322                 if (!indexed) {
323                     if (ws != null)
324                         genWhiteSpaceRestriction(ws, a.instanceOf(), baseType);
325                     jw.write(attr, " = ");
326                     jw.writeEol(a.instanceOf());
327                     if (a.isBean && config.isGenerateParentRefs()) {
328                         jw.beginIf(attr+" != null");
329                         jw.writeEol(attr, "._setParent(this)");
330                         jw.end();
331                     } else if (config.isOptionalScalars() && a.isScalar()) {
332                         jw.writeEol(a.getScalarIsSet(), " = true");
333                     }
334                 } else {
335                     jw.beginIf(a.instanceOf() + "!= null");
336                     if ("java.util.ArrayList".equals(config.getIndexedPropertyType())) {
337                         jw.write("((", config.getIndexedPropertyType(),
338                                  ") ", attr);
339                         jw.writeEol(").ensureCapacity(",
340                                     a.instanceOf(), ".length)");
341                     }
342                     jw.beginFor("int i = 0", "i < "+a.instanceOf()+".length",
343                                 "++i");
344                     if (ws != null)
345                         genWhiteSpaceRestriction(ws, a.instanceOf()+"[i]",
346                                                  baseType);
347                     if (a.isBean && config.isGenerateParentRefs()) {
348                         jw.beginIf(a.instanceOf()+"[i] != null");
349                         jw.writeEol(a.instanceOf(), "[i]._setParent(this)");
350                         jw.end();
351                     }
352                     jw.write(attr, ".add(",
353                              JavaUtil.toObject(a.instanceOf()+"[i]", baseType,
354                                                config.isForME()));
355                     jw.writeEol(")");
356                     jw.end();
357                     jw.end();
358                 }
359             }
360             jw.end();
361             jw.cr();
362         }
363     }
364
365     public void genAccessors() throws IOException {
366         int size = attrList.size();
367         for (int i = 0; i < size; i++) {
368             Property a = (Property)attrList.get(i);
369             boolean indexed = a.isIndexed();
370             boolean isArrayStyle = (config.getIndexedPropertyType() == null);
371             boolean isWrapper = false;
372             boolean isScalar = a.isScalar();
373             String JavaDoc scalarType = a.getScalarType();
374             String JavaDoc attr = "_"+a.name;
375             String JavaDoc propertyName = a.beanIntrospectorName();
376             MetaElement me = getMetaElement(a);
377
378             String JavaDoc type = a.getType();
379             String JavaDoc baseType = type;
380             if (indexed)
381                 type = baseType + "[]";
382             Signatures sigs = getSignatures(a);
383             Signature sig;
384
385             //System.out.println("a.name="+a.name+" a.type="+a.type+" a.dtdName="+a.dtdName+" isWrapper="+isWrapper+" a.classType="+a.classType+" me="+me);
386
select(DECL_SECTION);
387             if (indexed) {
388                 if (isArrayStyle) {
389                     gen(PRIVATE, baseType+"[]", attr);
390                     gen(" = new ", baseType, "[0]");
391                     eol();
392                 } else {
393                     String JavaDoc paramType = (config.jdkTarget >= 150
394                         ? "<"+JavaUtil.toObjectType(baseType)+">"
395                         : "");
396                     gen(PRIVATE, "java.util.List" + paramType, attr);
397                     gen(" = new "+config.getIndexedPropertyType()+paramType+"();");
398                     tabIn();
399                     if (config.jdkTarget < 150)
400                         comment("List<"+baseType+">");
401                     else
402                         cr();
403                 }
404             } else {
405                 gen(PRIVATE, type, attr);
406                 if (a.getDefaultValue() != null && (a.elementInstance == Common.TYPE_1 || a.elementInstance == Common.TYPE_1_N)) {
407                     gen(" = ");
408                     if (!JavaUtil.checkValueToType(type, a.getDefaultValue())) {
409                         config.messageOut.println(Common.getMessage("MSG_NotAGoodValue", a.getDefaultValue(), type));
410                     }
411                     gen(JavaUtil.instanceFrom(type, a.getDefaultValue()));
412                     eol();
413                     if (config.isOptionalScalars() && a.isScalar()) {
414                         gen(PRIVATE, "boolean", a.getScalarIsSet());
415                         gen(" = true");
416                         eol();
417                     }
418                 } else {
419                     eol();
420                     if (config.isOptionalScalars() && a.isScalar()) {
421                         gen(PRIVATE, "boolean", a.getScalarIsSet());
422                         gen(" = false");
423                         eol();
424                     }
425                 }
426             }
427
428             select(ACCESS_SECTION);
429             comment("This attribute is ", Common.instanceToString(a.elementInstance));
430             // Generate setter
431
if (config.jdkTarget >= 150) {
432                 boolean first = true;
433                 for (Iterator extraDataIt = a.extraDataIterator(); extraDataIt.hasNext(); ) {
434                     Object JavaDoc extraData = extraDataIt.next();
435                     if (extraData instanceof HasAnnotation) {
436                         HasAnnotation annotator = (HasAnnotation) extraData;
437                         if (first)
438                             first = false;
439                         else
440                             jw.write(' ');
441                         jw.write('@');
442                         jw.write(annotator.genAnnotation());
443                     }
444                 }
445                 if (!first)
446                     jw.cr();
447             }
448             gen(sigs.findSignature(SETTER));
449             sp();
450             begin();
451             if (a.getPropertyInterface() != null) {
452                 jw.writeEol(type+" value = ("+type+") valueInterface");
453             }
454             if (indexed) {
455                 gen("if (value == null)");
456                 cr();
457                 tabIn();
458                 if (baseType.equals("byte[]"))
459                     jw.writeEol("value = new byte[0][0]");
460                 else
461                     jw.writeEol("value = new ", baseType, "[0]");
462             }
463             if (!indexed) {
464                 SchemaRep.WhiteSpace ws = (SchemaRep.WhiteSpace) a.searchExtraData(SchemaRep.WhiteSpace.class);
465                 if (ws != null)
466                     genWhiteSpaceRestriction(ws, "value", baseType);
467             }
468             if (config.isGeneratePropertyEvents() || config.isVetoable()) {
469                 if (indexed) {
470                     jw.beginIf("value.length == "+a.getSizeMethod()+"()");
471                     jw.writeEol("boolean same = true");
472                     jw.beginFor("int i = 0", "i < value.length", "++i");
473                     jw.beginIf("!("+JavaUtil.genEquals(type, "value[i]",
474                                                   a.getReadMethod(true) + "(i)")+")");
475                     jw.writeEol("same = false");
476                     jw.writeEol("break");
477                     jw.end();
478                     jw.end();
479                     jw.beginIf("same");
480                 } else {
481                     jw.beginIf(JavaUtil.genEquals(type, "value", attr));
482                 }
483                 jw.comment("No change.");
484                 jw.writeEol("return");
485                 jw.end();
486                 if (indexed)
487                     jw.end();
488
489                 if (a.isBean) {
490                     if (config.isGeneratePropertyEvents())
491                         comment("Make the foreign beans take on our property change event listeners.");
492                     if (config.isGenerateParentRefs())
493                         comment("Maintain the parent reference.");
494                     String JavaDoc iterVar = "value";
495                     if (indexed) {
496                         jw.beginFor("int i = 0", "i < value.length", "++i");
497                         iterVar = "value[i]";
498                     }
499                     jw.beginIf(iterVar+" != null");
500                     if (config.isGeneratePropertyEvents())
501                         geneol(iterVar+"._setPropertyChangeSupport(eventListeners)");
502                     if (config.isVetoable())
503                         geneol(iterVar+"._setVetoableChangeSupport(vetos)");
504                     if (config.isGenerateParentRefs())
505                         jw.writeEol(iterVar+"._setParent(this)");
506                     jw.end();
507                     if (indexed)
508                         jw.end();
509                 }
510
511                 jw.writeEol("java.beans.PropertyChangeEvent event = null");
512                 gen("if (");
513                 jw.setFirst(" || ");
514                 if (config.isGeneratePropertyEvents()) {
515                     jw.writeNext("eventListeners != null");
516                 }
517                 if (config.isGenerateStoreEvents()) {
518                     jw.writeNext("storeEvents");
519                 }
520                 if (config.isVetoable()) {
521                     jw.writeNext("vetos != null");
522                 }
523                 gen(") ");
524                 begin();
525                 if (indexed) {
526                     jw.comment("See if only 1 thing changed.");
527                     jw.writeEol("int addIndex = -1");
528                     jw.writeEol("int removeIndex = -1");
529                     jw.writeEol("int oldSize = size", a.name, "()");
530                     jw.writeEol("int newSize = value.length");
531                     jw.beginIf("oldSize + 1 == newSize || oldSize == newSize + 1");
532                     jw.writeEol("boolean checkAddOrRemoveOne = true");
533                     jw.writeEol("int oldIndex = 0, newIndex = 0");
534                     jw.beginFor("",
535                                 "oldIndex < oldSize && newIndex < newSize",
536                                 "++newIndex, ++oldIndex");
537                     //jw.writeEol("System.out.println(\"oldIndex=\"+oldIndex+\" newIndex=\"+newIndex)");
538
//jw.writeEol("System.out.println(\"addIndex=\"+addIndex+\" removeIndex=\"+removeIndex)");
539
jw.beginIf(JavaUtil.genEquals(baseType, "value[newIndex]",
540                                                   a.getReadMethod(true)+"(oldIndex)"));
541                     jw.comment("Same, so just continue.");
542                     jw.endElseBeginIf("addIndex != -1 || removeIndex != -1");
543                     jw.comment("More than 1 difference detected.");
544                     jw.writeEol("addIndex = removeIndex = -1");
545                     jw.writeEol("checkAddOrRemoveOne = false");
546                     jw.writeEol("break");
547                     jw.endElseBeginIf("oldIndex + 1 < oldSize && ("+JavaUtil.genEquals(baseType, "value[newIndex]", a.getReadMethod(true)+"(oldIndex+1)")+")");
548                     jw.writeEol("removeIndex = oldIndex");
549                     jw.writeEol("++oldIndex");
550                     jw.endElseBeginIf("newIndex + 1 < newSize && ("+JavaUtil.genEquals(baseType, "value[newIndex+1]", a.getReadMethod(true)+"(oldIndex)")+")");
551                     jw.writeEol("addIndex = newIndex");
552                     jw.writeEol("++newIndex");
553                     jw.endElseBegin();
554                     jw.comment("More than 1 difference.");
555                     jw.writeEol("addIndex = removeIndex = -1");
556                     jw.writeEol("checkAddOrRemoveOne = false");
557                     jw.writeEol("break");
558                     jw.end();
559                     jw.end(); // for
560
// Only do this check if we fell off the end (oldIndex == newIndex)
561
jw.beginIf("checkAddOrRemoveOne && addIndex == -1 && removeIndex == -1");
562                     jw.beginIf("oldSize + 1 == newSize");
563                     jw.comment("Added last one");
564                     jw.writeEol("addIndex = oldSize");
565                     jw.endElseBeginIf("oldSize == newSize + 1");
566                     jw.comment("Removed last one");
567                     jw.writeEol("removeIndex = newSize");
568                     jw.end();
569                     jw.end();
570                     jw.end();
571
572                     //jw.writeEol("System.out.println(\"addIndex=\"+addIndex+\" removeIndex=\"+removeIndex)");
573
jw.beginIf("addIndex >= 0");
574                     jw.write("event = ");
575                     genNewEvent(a, "addIndex", "null", "value[addIndex]", baseType);
576                     jw.eol();
577                     if (!isArrayStyle && !config.isVetoable() && !config.isKeepElementPositions() && !config.isGenerateStoreEvents()) {
578                         SchemaRep.WhiteSpace ws = (SchemaRep.WhiteSpace) a.searchExtraData(SchemaRep.WhiteSpace.class);
579                         if (ws != null)
580                             genWhiteSpaceRestriction(ws, "value[addIndex]", baseType);
581                         jw.writeEol(attr+".add(addIndex, value[addIndex])");
582                         genMadeChange();
583                         jw.writeEol("eventListeners.firePropertyChange(event)");
584                         jw.writeEol("return");
585                     }
586                     jw.endElseBeginIf("removeIndex >= 0");
587                     jw.write("event = ");
588                     genNewEvent(a, "removeIndex", a.getReadMethod(true)+"(removeIndex)", "null", baseType);
589                     jw.eol();
590                     if (!isArrayStyle && !config.isVetoable() && !config.isKeepElementPositions() && !config.isGenerateStoreEvents()) {
591                         jw.writeEol(attr+".remove(removeIndex)");
592                         genMadeChange();
593                         jw.writeEol("eventListeners.firePropertyChange(event)");
594                         jw.writeEol("return");
595                     }
596                     jw.endElseBegin();
597                 }
598                 jw.write("event = ");
599                 genNewEvent(a, indexed ? "-1" : "",
600                             a.getReadMethod(false)+"()",
601                             "value", type);
602                 jw.eol();
603                 end();
604                 if (indexed) {
605                     jw.end();
606                 }
607             }
608             if (config.isVetoable()) {
609                 gencr("if (vetos != null)");
610                 tabIn();
611                 geneol("vetos.fireVetoableChange(event)");
612             }
613             if (indexed) {
614                 if (config.isKeepElementPositions()) {
615                     jw.comment("Figure out where this type belongs.");
616                     jw.writeEol("int elementCount = fetchChildCount()");
617                     jw.writeEol("int destPos = 0");
618                     jw.writeEol("int srcPos = 0");
619                     // Remove all of the old entries
620
jw.beginFor("", "destPos < elementCount && srcPos < value.length",
621                                 "++destPos");
622                     jw.beginIf("elementTypesByPosition[destPos] == "+i);
623                     jw.comment("replace it");
624                     jw.writeEol("elementsByPosition[destPos] = value[srcPos++]");
625                     jw.end();
626                     jw.end();
627                     jw.comment("Handle when the replacement array is smaller.");
628                     jw.beginWhile("destPos < elementCount");
629                     jw.beginIf("elementTypesByPosition[destPos] == "+i);
630                     jw.writeEol("deleteElement(destPos)");
631                     jw.writeEol("--elementCount");
632                     jw.endElseBegin();
633                     jw.writeEol("++destPos");
634                     jw.end();
635                     jw.end();
636                     jw.comment("Handle when replacement array is larger.");
637                     jw.beginFor("", "srcPos < value.length", "++srcPos");
638                     jw.writeEol("insertElementByPosition(destPos++, ",
639                                 JavaUtil.toObject("value[srcPos]", baseType,
640                                                   config.isForME()),
641                                 ", "+i+")");
642                     jw.end();
643                 }
644                 if (isArrayStyle) {
645                     jw.writeEol(attr, " = value");
646                 } else {
647                     jw.writeEol(attr, ".clear()");
648                     if ("java.util.ArrayList".equals(config.getIndexedPropertyType())) {
649                         jw.writeEol("((", config.getIndexedPropertyType(),
650                                     ") "+attr, ").ensureCapacity(value.length)");
651                     }
652                     jw.beginFor("int i = 0", "i < value.length", "++i");
653                     SchemaRep.WhiteSpace ws = (SchemaRep.WhiteSpace) a.searchExtraData(SchemaRep.WhiteSpace.class);
654                     if (ws != null)
655                         genWhiteSpaceRestriction(ws, "value[i]", baseType);
656                     jw.write(attr, ".add(");
657                     String JavaDoc objectValue = JavaUtil.toObject("value[i]", baseType,
658                                                            config.isForME());
659                     jw.writeEol(objectValue, ")");
660                     jw.end();
661                 }
662             } else {
663                 geneol(attr+" = value");
664                 if (config.isOptionalScalars() && a.isScalar()) {
665                     jw.writeEol(a.getScalarIsSet(), " = true");
666                 }
667                 if (config.isKeepElementPositions()) {
668                     jw.comment("Figure out where this type belongs.");
669                     jw.writeEol("int elementCount = fetchChildCount()");
670                     jw.writeEol("int pos = findFirstOfElementType("+i+")");
671                     if (!isScalar) {
672                         jw.beginIf("value != null");
673                     }
674                     jw.beginIf("pos >= elementCount");
675                     jw.comment("It's the last one to be added");
676                     jw.writeEol("expandElementsByPosition(elementCount+1)");
677                     jw.writeEol("elementTypesByPosition[pos] = "+i);
678                     jw.end();
679                     jw.writeEol("elementsByPosition[pos] = ",
680                                 JavaUtil.toObject("value", type,
681                                                   config.isForME()));
682                     if (!isScalar) {
683                         jw.endElseBegin();
684                         jw.beginIf("pos < elementCount");
685                         jw.writeEol("deleteElement(pos)");
686                         jw.end();
687                         jw.end();
688                     }
689                 }
690             }
691             genMadeChange();
692             if (config.isGeneratePropertyEvents()) {
693                 if (config.isGenerateStoreEvents()) {
694                     gencr("if (storeEvents)");
695                     tabIn();
696                     geneol("storedEvents.add(event)");
697                     gen("else ");
698                 }
699                 gencr("if (event != null)");
700                 tabIn();
701                 geneol("eventListeners.firePropertyChange(event)");
702             }
703
704             genResetMutuallyExclusive(a, true);
705             end();
706             cr();
707
708             if (indexed) {
709                 gen(sigs.findSignature(SETTERINDEXED));
710                 sp();
711                 begin();
712                 if (a.getPropertyInterface() != null) {
713                     jw.writeEol(baseType+" value = ("+baseType+") valueInterface");
714                 }
715                 if (config.isGeneratePropertyEvents()) {
716                     jw.beginIf(JavaUtil.genEquals(type, "value",
717                                                   a.getReadMethod(true)+"(index)",
718                                                   true));
719                     jw.comment("No change.");
720                     jw.writeEol("return");
721                     jw.end();
722                 }
723                 if (a.isBean && config.isGenerateParentRefs()) {
724                     jw.beginIf("value != null");
725                     jw.writeEol("value._setParent(this)");
726                     jw.end();
727                 }
728                 if (config.isGeneratePropertyEvents()) {
729                     if (a.isBean) {
730                         jw.beginIf("value != null");
731                         comment("Make the foreign beans take on our property change event listeners.");
732                         geneol("value._setPropertyChangeSupport(eventListeners)");
733                         if (config.isVetoable())
734                             geneol("value._setVetoableChangeSupport(vetos)");
735                         jw.end();
736                     }
737
738                     gen("if (");
739                     if (config.isGenerateStoreEvents()) {
740                         gen("storeEvents || ");
741                     }
742                     gen("eventListeners != null) ");
743                     begin();
744                     jw.write("java.beans.PropertyChangeEvent event = ");
745                     genNewEvent(a, "index", a.getReadMethod(true)+"(index)",
746                                 "value", baseType);
747                     jw.eol();
748                     if (config.isVetoable()) {
749                         gencr("if (vetos != null)");
750                         tabIn();
751                         geneol("vetos.fireVetoableChange(event)");
752                     }
753                     if (config.isGenerateStoreEvents()) {
754                         gencr("if (storeEvents)");
755                         tabIn();
756                         geneol("storedEvents.add(event)");
757                         gencr("else");
758                         tabIn();
759                     }
760                     geneol("eventListeners.firePropertyChange(event)");
761                     end();
762                 }
763                 if (isArrayStyle) {
764                     jw.writeEol(attr, "[index] = value");
765                 } else {
766                     if (!a.isDirectChild()) {
767                         // Check to see if we need to grow before we set.
768
jw.beginFor("int size = "+attr+".size()",
769                                     "index >= size", "++size");
770                         jw.writeEol(attr, ".add(null)");
771                         jw.end();
772                     }
773                     jw.write(attr, ".set(index, ");
774                     jw.write(JavaUtil.toObject("value", baseType, config.isForME()));
775                     jw.writeEol(")");
776                 }
777                 if (config.isKeepElementPositions()) {
778                     jw.writeEol("int pos = findElementType("+i+", index)");
779                     jw.writeEol("elementsByPosition[pos] = ",
780                                 JavaUtil.toObject("value", baseType,
781                                                   config.isForME()));
782                 }
783                 genMadeChange();
784                 end();
785                 cr();
786             }
787
788             // Generate getter
789
gen(sigs.findSignature(GETTER));
790             sp();
791             begin();
792             if (indexed && !isArrayStyle) {
793                 if (baseType.equals("byte[]"))
794                     jw.writeEol(type, " arr = new byte[", attr, ".size()][]");
795                 else
796                     jw.writeEol(type, " arr = new ", baseType+"["+attr, ".size()]");
797                 if (isScalar) {
798                     jw.beginFor("int i = 0", "i < arr.length", "++i");
799                     jw.write("arr[i] = ");
800                     jw.write(JavaUtil.fromObject(baseType, attr+".get(i)"));
801                     jw.eol();
802                     jw.end();
803                     jw.write("return arr");
804                 } else {
805                     gen("return ("+type+") "+attr+".toArray(arr)");
806                 }
807             } else
808                 gen("return "+attr);
809             eol();
810             end();
811             cr();
812
813             if (indexed) {
814                 if (!config.isMinFeatures() && !isArrayStyle) {
815                     gen(sigs.findSignature(GETTERLIST));
816                     sp();
817                     begin();
818                     gen("return "+attr);
819                     eol();
820                     end();
821                     cr();
822                 }
823
824                 gen(sigs.findSignature(GETTERINDEXED));
825                 sp();
826                 begin();
827                 jw.write("return ");
828                 if (isArrayStyle) {
829                     jw.writeEol(attr, "[index]");
830                 } else {
831                     jw.writeEol(JavaUtil.fromObject(baseType, attr+".get(index)"));
832                 }
833                 end();
834                 cr();
835
836                 comment("Return the number of "+propertyName);
837                 gen(sigs.findSignature(SIZE));
838                 sp();
839                 begin();
840                 if (isArrayStyle) {
841                     jw.writeEol("return ", attr, ".length");
842                 } else {
843                     jw.writeEol("return ", attr, ".size()");
844                 }
845                 end();
846                 cr();
847
848                 if (!isArrayStyle) {
849                     gen(sigs.findSignature(ADD));
850                     sp();
851                     begin();
852                     if (a.getPropertyInterface() != null) {
853                         jw.writeEol(baseType+" value = ("+baseType+") valueInterface");
854                     }
855                     if (a.isBean && config.isGenerateParentRefs()) {
856                         jw.beginIf("value != null");
857                         jw.writeEol("value._setParent(this)");
858                         jw.end();
859                     }
860                     if (a.isBean && config.isGeneratePropertyEvents()) {
861                         jw.beginIf("value != null");
862                         comment("Make the foreign beans take on our property change event listeners.");
863                         geneol("value._setPropertyChangeSupport(eventListeners)");
864                         if (config.isVetoable())
865                             geneol("value._setVetoableChangeSupport(vetos)");
866                         jw.end();
867                     }
868                     jw.writeEol(attr, ".add(",
869                                 JavaUtil.toObject("value", baseType,
870                                                   config.isForME()),
871                                 ")");
872                     if (config.isKeepElementPositions()) {
873                         GraphLink gl = a.getGraphLink();
874                         //jw.comment("gl="+gl);
875
//jw.comment("gl.lastInGroup="+gl.getLastInGroup());
876
//jw.comment("gl.lastInGroup.object="+gl.getLastInGroup().getObject());
877
int lastPropNum;
878                         if (gl == null) {
879                             lastPropNum = i;
880                         } else {
881                             Property lastProp = (Property) gl.getLastSibling().getObject();
882                             if (lastProp == a) {
883                                 lastPropNum = i;
884                             } else {
885                                 for (lastPropNum = 0; lastPropNum < size; ++lastPropNum)
886                                     if (attrList.get(lastPropNum) == lastProp)
887                                         break;
888                                 if (lastPropNum == size) {
889                                     jw.comment("Did not find lastPropNum");
890                                     lastPropNum = i;
891                                 }
892                             }
893                         }
894                         jw.writeEol("int pos = findLastOfElementType("+lastPropNum+")+1");
895                         jw.writeEol("insertElementByPosition(pos, ",
896                                     JavaUtil.toObject("value", baseType,
897                                                       config.isForME()),
898                                     ", "+i+")");
899                     }
900                     if (config.isGeneratePropertyEvents()) {
901                         gen("if (");
902                         if (config.isGenerateStoreEvents()) {
903                             gen("storeEvents || ");
904                         }
905                         gen("eventListeners != null) ");
906                         begin();
907                         jw.write("java.beans.PropertyChangeEvent event = ");
908                         genNewEvent(a, attr+".size()-1", "null",
909                                     "value", baseType);
910                         jw.eol();
911                         if (config.isVetoable()) {
912                             gencr("if (vetos != null)");
913                             tabIn();
914                             geneol("vetos.fireVetoableChange(event)");
915                         }
916                         if (config.isGenerateStoreEvents()) {
917                             gencr("if (storeEvents)");
918                             tabIn();
919                             geneol("storedEvents.add(event)");
920                             gencr("else");
921                             tabIn();
922                         }
923                         geneol("eventListeners.firePropertyChange(event)");
924                         end();
925                     }
926                     jw.writeEol("int positionOfNewItem = "+attr+".size()-1");
927                     if (isMutuallyExclusive(a)) {
928                         jw.beginIf("positionOfNewItem == 0");
929                         genResetMutuallyExclusive(a, false);
930                         jw.end();
931                     }
932                     genMadeChange();
933                     geneol("return positionOfNewItem");
934                     end();
935                     cr();
936
937                     jw.bigComment("Search from the end looking for @param value, and then remove it.");
938                     gen(sigs.findSignature(REMOVE));
939                     sp();
940                     begin();
941                     if (a.getPropertyInterface() != null) {
942                         jw.writeEol(baseType+" value = ("+baseType+") valueInterface");
943                     }
944                     jw.writeEol("int pos = ", attr, ".indexOf(",
945                                 JavaUtil.toObject("value", baseType,
946                                                   config.isForME())+")");
947                     gen("if (pos >= 0) ");
948                     begin();
949                     geneol(attr+".remove(pos)");
950                     if (config.isKeepElementPositions()) {
951                         jw.writeEol("int elementPos = findElementType("+i+", pos)");
952                         jw.writeEol("deleteElement(elementPos)");
953                     }
954                     if (config.isGeneratePropertyEvents()) {
955                         gen("if (");
956                         if (config.isGenerateStoreEvents()) {
957                             gen("storeEvents || ");
958                         }
959                         gen("eventListeners != null) ");
960                         begin();
961                         gen("java.beans.PropertyChangeEvent event = ");
962                         genNewEvent(a, "pos", "value", "null", baseType);
963                         jw.eol();
964                         if (config.isVetoable()) {
965                             gencr("if (vetos != null)");
966                             tabIn();
967                             geneol("vetos.fireVetoableChange(event)");
968                         }
969                         if (config.isGenerateStoreEvents()) {
970                             gencr("if (storeEvents)");
971                             tabIn();
972                             geneol("storedEvents.add(event)");
973                             gencr("else");
974                             tabIn();
975                         }
976                         geneol("eventListeners.firePropertyChange(event)");
977                         end();
978                     }
979                     end();
980                     genMadeChange();
981                     geneol("return pos");
982                     end();
983                     cr();
984                 }
985
986                 MetaProperty mp = getMetaProperty(a.name);
987                 GraphNode graphNode = a.getGraphNode();
988                 SchemaRep.Key key = null;
989                 if (graphNode != null)
990                     key = (SchemaRep.Key)
991                         graphNode.searchExtraData(SchemaRep.Key.class);
992                 if (a.isBean &&
993                     ((key != null) || (mp != null && mp.isKey()))) {
994                     //System.out.println("mp for "+a.name);
995
//System.out.println(mp.dumpBeanNode());
996
config.messageOut.println("Found key: "+key);
997                     SchemaRep.Selector selector = (SchemaRep.Selector)
998                         key.findSubElement(SchemaRep.Selector.class);
999                     SchemaRep.Field field = (SchemaRep.Field)
1000                        key.findSubElement(SchemaRep.Field.class);
1001                    genFinder(a, graphNode, attr, key.getElementName(),
1002                              baseType, a.name,
1003                              selector.getXPath(), field.getXPath(), false);
1004                }
1005            } // end if (indexed)
1006
genDefaultsAccessable(a);
1007
1008            if (a.isBean && !a.getBeanElement().isAbstract) {
1009                genNewMethod(a.getPropertyInterface(), baseType,
1010                             getTypeFullClassName(a));
1011            }
1012        }
1013        if (config.isKeepElementPositions()) {
1014            select(DECL_SECTION);
1015            jw.writeEol("private java.lang.Object[] elementsByPosition = new java.lang.Object[0]"); // we might be storing String, int's, and beans in there.
1016
jw.writeEol("private int[] elementTypesByPosition = new int[0]");
1017        }
1018        if (beanElement.isRoot && !config.isMinFeatures()) {
1019            select(DECL_SECTION);
1020            jw.write("private java.lang.String schemaLocation");
1021            if (mdd.getSchemaLocation() != null) {
1022                jw.write(" = ");
1023                jw.write(JavaUtil.instanceFrom("java.lang.String",
1024                                               mdd.getSchemaLocation()));
1025            }
1026            jw.eol();
1027            select(ACCESS_SECTION);
1028            jw.beginMethod("_setSchemaLocation", "String location", null, "void", jw.PUBLIC);
1029            jw.writeEol("schemaLocation = location");
1030            genMadeChange();
1031            jw.end();
1032            jw.cr();
1033            
1034            jw.beginMethod("_getSchemaLocation", "", null, "String", jw.PUBLIC);
1035            jw.writeEol("return schemaLocation");
1036            jw.endMethod();
1037        }
1038        if (config.isGenerateParentRefs()) {
1039            select(DECL_SECTION);
1040            String JavaDoc parentType = parentBeanType();
1041            jw.writeEol("private ", parentType, " parent");
1042            select(BODY_SECTION);
1043            jw.beginMethod("_setParent", parentType+" parent");
1044            jw.writeEol("this.parent = parent");
1045            jw.endMethod();
1046
1047            jw.beginMethod("_getXPathExpr", "", null, "String", jw.PUBLIC);
1048            jw.beginIf("parent == null");
1049            jw.writeEol("return \"/", beanElement.node.getName(), "\"");
1050            jw.endElseBegin();
1051            jw.writeEol("String parentXPathExpr = parent._getXPathExpr()");
1052            jw.writeEol("String myExpr = parent.nameChild(this, false, false, true)");
1053            jw.writeEol("return parentXPathExpr + \"/\" + myExpr");
1054            jw.end();
1055            jw.endMethod();
1056
1057            jw.beginMethod("_getXPathExpr", "Object childObj", null, "String", jw.PUBLIC);
1058            jw.writeEol("String childName = nameChild(childObj, false, false, true)");
1059            jw.beginIf("childName == null");
1060            jw.writeEol("throw new IllegalArgumentException(\"childObj (\"+childObj.toString()+\") is not a child of this bean ("+className+").\")");
1061            jw.end();
1062            jw.writeEol("return _getXPathExpr() + \"/\" + childName");
1063            jw.endMethod();
1064        }
1065
1066        // Look for finders
1067
for (Iterator it = beanElement.getGraphNode().extraDataIterator(); it.hasNext(); ) {
1068            Object JavaDoc data = it.next();
1069            if (data instanceof BeanBuilder.Finder) {
1070                BeanBuilder.Finder finder = (BeanBuilder.Finder) data;
1071                //System.out.println("Found finder: "+finder);
1072
genFinder(beanElement.getGraphNode(), finder);
1073            }
1074        }
1075    }
1076
1077    protected void genFinder(GraphNode startingGraphNode,
1078                             BeanBuilder.Finder finder) throws IOException {
1079        genFinder(startingGraphNode,
1080                  finder.getFindExpr(), finder.getByExpr(),
1081                  finder.isListFindExpr());
1082    }
1083    
1084    protected void genFinder(GraphNode startingGraphNode,
1085                             String JavaDoc selectorXPath, String JavaDoc fieldXPath,
1086                             boolean isListFindExpr) throws IOException {
1087        genFinder(null, startingGraphNode, null, null, null, null,
1088                  selectorXPath, fieldXPath, isListFindExpr);
1089    }
1090    
1091    protected void genFinder(Property a, GraphNode startingGraphNode,
1092                             String JavaDoc attr, String JavaDoc keyName, String JavaDoc returnType,
1093                             String JavaDoc nameToFind,
1094                             String JavaDoc selectorXPath, String JavaDoc fieldXPath,
1095                             boolean isListFindExpr) throws IOException {
1096        String JavaDoc dtdName = null;
1097        String JavaDoc keyVar = null;
1098        String JavaDoc keyType = null;
1099        String JavaDoc keyTypeInterface = null;
1100        List xpathChain = null;
1101
1102        GraphNode graphNode = startingGraphNode;
1103        Property selectorProp = null;
1104        if (graphNode != null && graphNode.getGraphLink() != null) {
1105            xpathChain = new LinkedList();
1106            GraphLink gl = null;
1107            for (Iterator it = graphNode.getGraphLink().xPathIterator(selectorXPath);
1108                 it.hasNext(); ) {
1109                gl = (GraphLink) it.next();
1110                //System.out.println("selector gl="+gl);
1111
if (gl == null)
1112                    break;
1113                if (gl.getObject() != null)
1114                    xpathChain.add(gl);
1115            }
1116            if (gl != null) {
1117                GraphLink nextStartingLink;
1118                if (gl.element != null) {
1119                    nextStartingLink = gl.element.getGraphLink();
1120                } else {
1121                    nextStartingLink = gl;
1122                }
1123                selectorProp = (Property) gl.getObject();
1124                if (!fieldXPath.equals(".")) {
1125                    //System.out.println("nextStartingLink="+nextStartingLink);
1126
for (Iterator it = nextStartingLink.xPathIterator(fieldXPath);
1127                         it.hasNext(); ) {
1128                        gl = (GraphLink) it.next();
1129                        //System.out.println("field gl="+gl);
1130
if (gl == null) {
1131                            break;
1132                        }
1133                        if (gl.getObject() != null)
1134                            xpathChain.add(gl);
1135                    }
1136                }
1137                if (gl != null) {
1138                    //
1139
// Found the final one.
1140
//
1141
//System.out.println("gl="+gl+" gl.name="+gl.name);
1142
Property finalProp = (Property) gl.getObject();
1143                    if (finalProp != null) {
1144                        dtdName = finalProp.dtdName;
1145                        keyVar = finalProp.instanceOf()+"Key";
1146                        keyType = finalProp.getType();
1147                        keyTypeInterface = finalProp.getPropertyInterface();
1148                    } else {
1149                        config.messageOut.println("Warning: finalProp=null while generating finder.");
1150                    }
1151                }
1152            }
1153            if (gl == null)
1154                xpathChain = null;
1155        }
1156        //System.out.println("dtdName="+dtdName);
1157

1158        if (dtdName == null) {
1159            dtdName = fieldXPath;
1160            keyVar = Common.convertNameInstance(dtdName);
1161            keyType = "String";
1162            jw.comment("Did not figure out proper expression to find the key. This method may not work.");
1163            jw.comment("selectorXPath="+selectorXPath);
1164            if (selectorProp == null) {
1165                jw.comment(" Failed to find selector.");
1166            } else {
1167                jw.comment(" found selector property name="+selectorProp.dtdName);
1168            }
1169            jw.comment("fieldXPath="+fieldXPath);
1170            xpathChain = null;
1171        }
1172
1173        if (selectorProp != null) {
1174            if (nameToFind == null)
1175                nameToFind = Common.convertName(selectorProp.dtdName);
1176            if (returnType == null) {
1177                if (selectorProp.getPropertyInterface() == null)
1178                    returnType = selectorProp.getType();
1179                else
1180                    returnType = selectorProp.getPropertyInterface();
1181            }
1182        }
1183        if (keyName == null)
1184            keyName = fieldXPath;
1185        if (returnType == null)
1186            returnType = "String";
1187        if (isListFindExpr) {
1188            returnType = "java.util.List/*<"+returnType+">*/";
1189            jw.bigComment("Search for the key.\n@return all elements found that match.");
1190        } else {
1191            jw.bigComment("Search for the key.\n@return null if the key is not found.");
1192        }
1193        String JavaDoc methodName;
1194        if (isListFindExpr)
1195            methodName = "findAll"+nameToFind;
1196        else
1197            methodName = "find"+nameToFind;
1198        if (!keyName.equals("."))
1199            methodName = methodName+"By"+Common.convertName(keyName);
1200        String JavaDoc arguments;
1201        if (keyTypeInterface == null)
1202            arguments = keyType+" "+keyVar;
1203        else
1204            arguments = keyTypeInterface+" "+keyVar+"Interface";
1205        jw.beginMethod(methodName,
1206                       arguments, null, returnType,
1207                       jw.PUBLIC | jw.BEANINFO);
1208        if (keyTypeInterface != null)
1209            jw.writeEol(keyVar, " = ("+keyType, ") ", keyVar+"Interface");
1210        if (isListFindExpr)
1211            jw.writeEol("java.util.List _result = new java.util.ArrayList()");
1212        String JavaDoc lastVar, topVar;
1213        if (attr != null) {
1214            beginAttrIterator(attr, a, "_el");
1215            jw.beginIf("_el == null");
1216            jw.writeEol("continue");
1217            jw.end();
1218            lastVar = "_el";
1219            topVar = "_el";
1220        } else {
1221            lastVar = "this";
1222            topVar = "null";
1223        }
1224                    
1225        if (xpathChain != null) {
1226            GraphLink gl = null;
1227            int foundIndices = 0;
1228            for (Iterator it = xpathChain.iterator();
1229                 it.hasNext(); ) {
1230                gl = (GraphLink) it.next();
1231                Property prop = (Property) gl.getObject();
1232                String JavaDoc var = prop.instanceOf()+foundIndices;
1233                if (attr == null && selectorProp == prop)
1234                    topVar = var;
1235                if (prop.isIndexed()) {
1236                    ++foundIndices;
1237                    jw.beginFor("int "+var+"Index = 0",
1238                                var+"Index < "+lastVar+".size"+prop.name+"()",
1239                                var+"Index++");
1240                }
1241                jw.write(prop.getType()+" "+var);
1242                jw.write(" = (", prop.getType(), ") ");
1243                jw.write(lastVar, ".");
1244                jw.write(prop.getReadMethod(prop.isIndexed()));
1245                if (prop.isIndexed())
1246                    jw.write("("+var+"Index)");
1247                else
1248                    jw.write("()");
1249                jw.eol();
1250                jw.beginIf(var+" == null");
1251                if (!it.hasNext()) {
1252                    jw.beginIf(keyVar, " == null");
1253                    if (isListFindExpr)
1254                        jw.writeEol("_result.add(", topVar, ")");
1255                    else
1256                        jw.writeEol("return ", topVar);
1257                    jw.end();
1258                }
1259                jw.writeEol("continue");
1260                jw.end();
1261                lastVar = var;
1262            }
1263            jw.beginIf(lastVar+".equals("+keyVar+")");
1264            if (isListFindExpr)
1265                jw.writeEol("_result.add(", topVar, ")");
1266            else
1267                jw.writeEol("return ", topVar);
1268            jw.end();
1269            for (; foundIndices > 0; --foundIndices)
1270                jw.end();
1271        }
1272
1273        if (attr != null)
1274            jw.end(); // endAttrIterator
1275
if (isListFindExpr)
1276            jw.writeEol("return _result");
1277        else
1278            jw.writeEol("return ", JavaUtil.nullValueForType(returnType));
1279        jw.endMethod();
1280    }
1281
1282    public void genXMLIO() throws IOException {
1283        select(BODY_SECTION);
1284        String JavaDoc beanName = beanElement.node.getName();
1285        if (beanElement.isRoot) {
1286            if (!config.isStandalone()) {
1287                jw.beginMethod("write", "org.openide.filesystems.FileObject fo",
1288                               "java.io.IOException", "void", jw.PUBLIC | jw.IO);
1289                jw.writeEol("org.openide.filesystems.FileLock lock = fo.lock()");
1290                jw.beginTry();
1291                jw.writeEol("java.io.OutputStream out = fo.getOutputStream(lock)");
1292                jw.writeEol("write(out)");
1293                jw.writeEol("out.close()");
1294                jw.endFinallyBegin();
1295                jw.writeEol("lock.releaseLock()");
1296                jw.end();
1297                jw.endMethod();
1298
1299                jw.beginMethod("write", "final org.openide.filesystems.FileObject dir, final String filename",
1300                               "java.io.IOException", "void", jw.PUBLIC | jw.IO);
1301                jw.writeEol("org.openide.filesystems.FileSystem fs = dir.getFileSystem()");
1302                jw.write("fs.runAtomicAction(new org.openide.filesystems.FileSystem.AtomicAction()\n");
1303                jw.begin();
1304                jw.write("public void run() throws java.io.IOException {\n");
1305                jw.writeEol("org.openide.filesystems.FileObject file = dir.getFileObject(filename)");
1306                jw.beginIf("file == null");
1307                jw.writeEol("file = dir.createData(filename)");
1308                jw.end();
1309                jw.writeEol("write(file)");
1310                jw.end();
1311                jw.end();
1312                jw.writeEol(")");
1313                jw.endMethod();
1314            }
1315
1316            jw.beginMethod("write", "java.io.File f",
1317                           "java.io.IOException", "void", jw.PUBLIC | jw.IO);
1318            jw.writeEol("java.io.OutputStream out = new java.io.FileOutputStream(f)");
1319            jw.beginTry();
1320            jw.writeEol("write(out)");
1321            jw.endFinallyBegin();
1322            jw.writeEol("out.close()");
1323            jw.end();
1324            jw.endMethod();
1325
1326            jw.beginMethod("write", "java.io.OutputStream out",
1327                           "java.io.IOException", "void", jw.PUBLIC | jw.IO);
1328            geneol("write(out, null)");
1329            jw.endMethod();
1330
1331            jw.beginMethod("write", "java.io.OutputStream out, String encoding",
1332                           "java.io.IOException", "void", jw.PUBLIC | jw.IO);
1333            geneol("java.io.Writer w");
1334            jw.beginIf("encoding == null");
1335            gen("encoding = \"UTF-8\"");
1336            eolNoI18N();
1337            end();
1338            gen("w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(out, encoding))");
1339            eol();
1340            geneol("write(w, encoding)");
1341            geneol("w.flush()");
1342            jw.endMethod();
1343
1344            jw.bigComment("Print this Java Bean to @param out including an XML header.\n@param encoding is the encoding style that @param out was opened with.");
1345            jw.beginMethod("write", "java.io.Writer out, String encoding",
1346                           "java.io.IOException", "void", jw.PUBLIC | jw.IO);
1347            gen("out.write(\"<?xml version='1.0'\")");
1348            eolNoI18N();
1349            gen("if (encoding != null)");
1350            cr();
1351            tabIn();
1352            gen("out.write(\" encoding='\"+encoding+\"'\")");
1353            eolNoI18N();
1354            gen("out.write(\" ?>\\n\")");
1355            eolNoI18N();
1356            if (config.isProcessDocType()) {
1357                jw.beginIf("docType != null");
1358                jw.writeEol("out.write(docType.toString())");
1359                jw.writeEol("out.write(\"\\n\")");
1360                jw.end();
1361            }
1362            jw.write("writeNode(out, \"", beanName, "\", \"\")");
1363            eolNoI18N();
1364            jw.endMethod();
1365        }
1366
1367        jw.beginMethod("writeNode", "java.io.Writer out",
1368                       "java.io.IOException", "void", jw.PUBLIC | jw.IO);
1369        jw.writeEol("String myName");
1370        if (config.isGenerateParentRefs())
1371            jw.beginIf("parent == null");
1372        jw.writeEol("myName = \"", beanName, "\"");
1373        if (config.isGenerateParentRefs()) {
1374            jw.endElseBegin();
1375            jw.writeEol("myName = parent.nameChild(this, false, true)");
1376            jw.beginIf("myName == null");
1377            jw.writeEol("myName = \"", beanName, "\"");
1378            jw.end();
1379            jw.end();
1380        }
1381        jw.write("writeNode(out, myName, \"\")");
1382        eolNoI18N();
1383        jw.endMethod();
1384
1385        jw.beginMethod("writeNode",
1386                       "java.io.Writer out, String nodeName, String indent",
1387                       "java.io.IOException", "void", jw.PUBLIC | jw.IO);
1388        jw.write("writeNode(out, nodeName, null, indent, new java.util.HashMap");
1389        if (config.jdkTarget >= 150)
1390            jw.write("<String, String>");
1391        jw.writeEol("())");
1392        jw.endMethod();
1393
1394        jw.bigComment("It's not recommended to call this method directly.");
1395        String JavaDoc writeNodeArgs = "java.io.Writer out, String nodeName, String namespace, String indent, java.util.Map";
1396        if (config.jdkTarget >= 150)
1397            writeNodeArgs += "<String, String>";
1398        writeNodeArgs += " namespaceMap";
1399        jw.beginMethod("writeNode", writeNodeArgs,
1400                       "java.io.IOException", "void", jw.PUBLIC | jw.IO | jw.UNSUPPORTED);
1401        int size = attrList.size();
1402        Map namespaceToPrefixTable = new HashMap();
1403        geneol("out.write(indent)");
1404        outWrite("<");
1405        jw.beginIf("namespace != null");
1406        jw.writeEol("out.write((String)namespaceMap.get(namespace))");
1407        outWrite(":");
1408        jw.end();
1409        geneol("out.write(nodeName)");
1410        if (beanElement.isRoot && getDefaultNamespace() != null) {
1411            jw.writeEolNoI18N("out.write(\" xmlns='\")");
1412            jw.writeEolNoI18N("out.write("+JavaUtil.instanceFrom("java.lang.String", getDefaultNamespace())+")");
1413            jw.writeEolNoI18N("out.write(\"'\")");
1414        }
1415        if (beanElement.isRoot) {
1416            jw.beginIf("schemaLocation != null");
1417            jw.writeEol("namespaceMap.put(\"http://www.w3.org/2001/XMLSchema-instance\", \"xsi\")");
1418            namespaceToPrefixTable.put("http://www.w3.org/2001/XMLSchema-instance",
1419                                       "xsi");
1420            jw.writeEol("out.write(\" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='\")");
1421            jw.writeEol("out.write(schemaLocation)");
1422            jw.writeEolNoI18N("out.write(\"'\")");
1423            jw.end();
1424        }
1425
1426        // Deal with namespaces
1427
boolean firstNS = true;
1428        for (int i = 0; i < size; i++) {
1429            Property a = (Property) attrList.get(i);
1430            boolean indexed = a.isIndexed();
1431            String JavaDoc attr = "_" + a.name;
1432            String JavaDoc type = a.getType().intern();
1433            String JavaDoc baseType = type;
1434            if (indexed)
1435                type = (baseType + "[]").intern();
1436            if (isTypeQName(baseType)) {
1437                if (firstNS) {
1438                    firstNS = false;
1439                    jw.comment("Work out any namespaces.");
1440                    jw.writeEol("boolean firstNSAddition = true");
1441                }
1442                if (indexed) {
1443                    beginAttrIterator(attr, a, "element");
1444                    attr = "element";
1445                }
1446                jw.beginIf(attr+" != null && "+
1447                           attr+".getNamespaceURI() != null && !\"\".equals(",
1448                           attr, ".getNamespaceURI())");
1449                jw.writeEol("String prefix = (String) namespaceMap.get(", attr, ".getNamespaceURI())");
1450                jw.beginIf("prefix == null || \"\".equals(prefix)");
1451                jw.writeEol("prefix = ", attr, ".getPrefix()");
1452                jw.beginIf("prefix == null || \"\".equals(prefix)");
1453                jw.writeEol("prefix = \"", a.dtdName, "_ns__\"");
1454                jw.end();
1455                jw.comment("Need to make sure it's a unique prefix too.");
1456                jw.writeEol("boolean changed");
1457                jw.write("do ");
1458                jw.begin();
1459                jw.writeEol("changed = false");
1460                jw.beginFor("java.util.Iterator valueIt = namespaceMap.values().iterator()",
1461                            "valueIt.hasNext()", "");
1462                jw.writeEol("String otherPrefix = (String) valueIt.next()");
1463                jw.beginIf("prefix.equals(otherPrefix)");
1464                jw.writeEol("prefix += \"_\"");
1465                jw.writeEol("changed = true");
1466                jw.end();
1467                jw.end();
1468                jw.end(false);
1469                jw.writeEol(" while (changed)");
1470                jw.beginIf("firstNSAddition");
1471                jw.writeEol("firstNSAddition = false");
1472                jw.comment("Copy on write");
1473                jw.writeEol("namespaceMap = new java.util.HashMap(namespaceMap)");
1474                jw.end();
1475                jw.writeEol("namespaceMap.put(", attr,
1476                            ".getNamespaceURI(), prefix)");
1477                jw.writeEol("out.write(\" xmlns:\")");
1478                jw.writeEol("out.write(prefix)");
1479                jw.writeEol("out.write(\"='\")");
1480                jw.writeEol("out.write(", attr, ".getNamespaceURI())");
1481                jw.writeEol("out.write(\"'\")");
1482                jw.end();
1483                jw.end();
1484                if (indexed)
1485                    jw.end();
1486            } else if (a.getNamespace() != null && !a.getNamespace().equals(getDefaultNamespace()) && !a.getNamespace().equals("http://www.w3.org/XML/1998/namespace")) {
1487                if (namespaceToPrefixTable.containsKey(a.getNamespace()))
1488                    continue;
1489                if (firstNS) {
1490                    firstNS = false;
1491                    jw.comment("Work out any namespaces.");
1492                    jw.writeEol("boolean firstNSAddition = true");
1493                }
1494                String JavaDoc prefix;
1495                prefix = SchemaRep.prefixOf(a.dtdName);
1496                if (prefix == null) {
1497                    prefix = prefixGuesser.guessPrefixFromURI(a.getNamespace());
1498                    //config.messageOut.println("Guessing prefix for "+a.getNamespace()+" is "+prefix);
1499
}
1500                jw.beginIf("namespaceMap.get(",
1501                           JavaUtil.instanceFrom("String",
1502                                                 a.getNamespace()),
1503                           ") == null");
1504                jw.beginIf("firstNSAddition");
1505                jw.writeEol("firstNSAddition = false");
1506                jw.comment("Copy on write");
1507                jw.write("namespaceMap = new java.util.HashMap");
1508                if (config.jdkTarget >= 150)
1509                    jw.write("<String, String>");
1510                jw.writeEol("(namespaceMap)");
1511                jw.end();
1512                jw.writeEol("namespaceMap.put(",
1513                            JavaUtil.instanceFrom("String",
1514                                                  a.getNamespace()),
1515                            ", \"", prefix+"\")");
1516                outWrite(" xmlns:"+prefix+"='");
1517                outWrite(a.getNamespace());
1518                outWrite("'");
1519                jw.end();
1520                namespaceToPrefixTable.put(a.getNamespace(), prefix);
1521            }
1522        }
1523        List directAttributes = new LinkedList(); // List<Property>
1524
List nonDirectAttributes = new LinkedList(); // List<Property>
1525
boolean hasSubElements = false;
1526        if (size > 0) {
1527            // Go over the attributes
1528
for (int i = 0; i < size; i++) {
1529                Property a = (Property) attrList.get(i);
1530                if (!a.isAttribute()) {
1531                    hasSubElements = true;
1532                    continue;
1533                }
1534                if (!a.isDirectChild()) {
1535                    nonDirectAttributes.add(a);
1536                    continue;
1537                }
1538                directAttributes.add(a);
1539            }
1540        }
1541        jw.writeEol("writeNodeAttributes(out, nodeName, namespace, indent, namespaceMap)");
1542
1543        if (hasSubElements) {
1544            geneol("out.write(\">\\n\")");
1545        } else {
1546        }
1547            
1548        jw.writeEol("writeNodeChildren(out, nodeName, namespace, indent, namespaceMap)");
1549        if (hasSubElements) {
1550            geneol("out.write(indent)");
1551            outWrite("</");
1552            jw.beginIf("namespace != null");
1553            jw.writeEol("out.write((String)namespaceMap.get(namespace))");
1554            outWrite(":");
1555            jw.end();
1556            jw.writeEol("out.write(nodeName)");
1557            outWrite(">\n");
1558        } else {
1559            geneol("out.write(\"/>\\n\")");
1560        }
1561        jw.endMethod(); // writeNode
1562

1563        jw.beginMethod("writeNodeAttributes", writeNodeArgs,
1564                       "java.io.IOException", "void", jw.PROTECTED | jw.IO | jw.UNSUPPORTED);
1565        for (Iterator it = directAttributes.iterator(); it.hasNext(); ) {
1566            Property prop = (Property) it.next();
1567            genWriteAttr(prop);
1568        }
1569        if (config.isRespectExtension() && beanElement.getExtension() != null) {
1570            comment("extension is: "+beanElement.getExtension());
1571            jw.writeEol("super.writeNodeAttributes(out, nodeName, namespace, indent, namespaceMap)");
1572        }
1573        jw.endMethod();
1574        
1575        /*
1576        String writeNodeArgs = "java.io.Writer out, String nodeName, String namespace, String indent, java.util.Map";
1577        if (config.jdkTarget >= 150)
1578            writeNodeArgs += "<String, String>";
1579        writeNodeArgs += " namespaceMap";
1580         */

1581        jw.beginMethod("writeNodeChildren", writeNodeArgs,
1582                       "java.io.IOException", "void", jw.PROTECTED | jw.IO | jw.UNSUPPORTED);
1583        if (config.isRespectExtension() && beanElement.getExtension() != null) {
1584            jw.writeEol("super.writeNodeChildren(out, nodeName, namespace, indent, namespaceMap)");
1585        }
1586        if (hasSubElements) {
1587            geneol("String nextIndent = indent + \""+jw.getIndent()+"\"");
1588            if (config.isKeepElementPositions()) {
1589                jw.beginFor("int position = 0, count = fetchChildCount()",
1590                            "position < count", "++position");
1591                jw.writeEol("java.lang.Object child = elementsByPosition[position]");
1592                jw.writeEol("int elementType = elementTypesByPosition[position]");
1593                jw.write("switch (elementType) ");
1594                jw.begin();
1595            }
1596            boolean firstUseOfIndex = true;
1597            for (int i = 0; i < size; i++) {
1598                Property a = (Property)attrList.get(i);
1599                if (a.isAttribute())
1600                    continue;
1601                boolean indexed = a.isIndexed();
1602                String JavaDoc attr = "_" + a.name;
1603                String JavaDoc baseAttr = attr;
1604        
1605                boolean isScalar = a.isScalar();
1606                boolean isNamespaceSignificant = (a.getNamespace() != null && !a.getNamespace().equals(getDefaultNamespace()) && !a.getNamespace().equals("http://www.w3.org/XML/1998/namespace"));
1607
1608                String JavaDoc type = a.getType().intern();
1609                String JavaDoc baseType = type;
1610                if (indexed)
1611                    type = (baseType + "[]").intern();
1612
1613                if (config.isKeepElementPositions()) {
1614                    jw.writecr("case "+i+":");
1615                    jw.indentRight();
1616                    jw.writeEol(baseType+" a"+a.name+" = "+JavaUtil.fromObject(baseType, "child"));
1617                    attr = "a"+a.name;
1618                } else {
1619                    if (indexed) {
1620                        if (!a.isBean && a.attributes != null && a.attributes.length > 0) {
1621                            if (firstUseOfIndex) {
1622                                firstUseOfIndex = false;
1623                                jw.writeEol("int index = 0");
1624                            } else {
1625                                jw.writeEol("index = 0");
1626                            }
1627                        }
1628                        beginAttrIterator(attr, a, "element");
1629                        attr = "element";
1630                    }
1631                    if (!isScalar) {
1632                        jw.beginIf(attr, " != null");
1633                    } else if (!indexed && config.isOptionalScalars() && isScalar) {
1634                        jw.beginIf(a.getScalarIsSet());
1635                    }
1636                }
1637                if (a.isBean) {
1638                    jw.write(attr, ".writeNode(out, \"", a.dtdName);
1639                    jw.write("\", ");
1640                    if (isNamespaceSignificant)
1641                        jw.write(JavaUtil.instanceFrom("String",
1642                                                       a.getNamespace()));
1643                    else
1644                        jw.write("null");
1645                    jw.writeEol(", nextIndent, namespaceMap)");
1646                } else if (a.type == Common.TYPE_COMMENT) {
1647                    jw.writeEol("out.write(nextIndent)");
1648                    jw.writeEol("out.write(\"<!--\")");
1649                    jw.writeEol("out.write(", attr, ")");
1650                    jw.writeEol("out.write(\"-->\\n\")");
1651                } else if ("org.w3c.dom.Element".equals(type)) {
1652                    jw.writeEol("out.write(nextIndent)");
1653                    if (config.isUseRuntime()) {
1654                        jw.writeEol("org.netbeans.modules.schema2beans.XMLUtil.DOMWriter domWriter = new org.netbeans.modules.schema2beans.XMLUtil.DOMWriter()");
1655                        jw.writeEol("domWriter.setWriter(out)");
1656                        jw.writeEol("domWriter.write(", attr, ")");
1657                    } else {
1658                        jw.writeEol("out.write(", attr, ".toString())");
1659                    }
1660                    outWrite("\n");
1661                } else {
1662                    boolean needEndTag = true;
1663                    if (baseType == "boolean" && a.getCanBeEmpty()) {
1664                        jw.beginIf(attr);
1665                        needEndTag = false;
1666                    }
1667                    if (!a.dtdName.equals("#PCDATA")) {
1668                        jw.writeEol("out.write(nextIndent)");
1669                        if (isNamespaceSignificant) {
1670                            outWrite("<");
1671                            jw.writeEol("out.write((String)namespaceMap.get(",
1672                                        JavaUtil.instanceFrom("String",
1673                                                              a.getNamespace()),
1674                                        "))");
1675                            jw.write("out.write(\":", a.dtdName, "\")");
1676                        } else {
1677                            jw.write("out.write(\"<", a.dtdName, "\")");
1678                        }
1679                        eolNoI18N();
1680                        if (isTypeQName(baseType)) {
1681                            jw.writeEol("String nsPrefix", attr, " = null");
1682                            jw.beginIf(attr+".getNamespaceURI() != null && !\"\".equals(",
1683                                        attr, ".getNamespaceURI())");
1684                            jw.write("nsPrefix", attr, " = (String) namespaceMap.get(");
1685                            jw.writeEol(attr, ".getNamespaceURI())");
1686                            jw.end();
1687                        }
1688                        for (int attrNum = 0; attrNum < a.attributes.length; ++attrNum) {
1689                            AttrProp myAttrProp = a.attributes[attrNum];
1690                            //jw.comment("myAttrProp="+myAttrProp);
1691
for (Iterator it = nonDirectAttributes.iterator(); it.hasNext(); ) {
1692                                Property attrProperty = (Property) it.next();
1693                                AttrProp attrProp = attrProperty.getAttrProp();
1694                                if (myAttrProp == attrProp) {
1695                                    String JavaDoc varName;
1696                                    if (attrProperty.isIndexed()) {
1697                                        jw.beginIf("index < size"+attrProperty.name+"()");
1698                                        varName = attrProperty.getReadMethod(true)+"(index)";
1699                                    } else
1700                                        varName = "_"+attrProperty.name;
1701                                    genWriteAttr(attrProperty, varName);
1702                                    if (attrProperty.isIndexed()) {
1703                                        jw.end();
1704                                    }
1705                                }
1706                            }
1707                        }
1708                        if (needEndTag) {
1709                            gen("out.write(\">\")");
1710                            eolNoI18N();
1711                        }
1712                    }
1713                    if (!needEndTag) {
1714                        // no end tag, then no contents
1715
} else {
1716                        genWriteType(a, attr, false);
1717                    }
1718                    if (!needEndTag) {
1719                        gen("out.write(\"/>\\n\")");
1720                        eolNoI18N();
1721                        end();
1722                    } else if (!a.dtdName.equals("#PCDATA")) {
1723                        if (isNamespaceSignificant) {
1724                            outWrite("</");
1725                            jw.writeEol("out.write((String)namespaceMap.get(",
1726                                        JavaUtil.instanceFrom("String",
1727                                                              a.getNamespace()),
1728                                        "))");
1729                            jw.write("out.write(\":", a.dtdName, ">\\n\")");
1730                        } else {
1731                            jw.write("out.write(\"</"+a.dtdName, ">\\n\")");
1732                        }
1733                        eolNoI18N();
1734                    }
1735                }
1736                if (config.isKeepElementPositions()) {
1737                    jw.writeEol("break");
1738                    jw.indentLeft();
1739                } else {
1740                    if (a.isNillable()) {
1741                        if (!isScalar) {
1742                            jw.endElseBegin();
1743                            jw.writeEol("out.write(nextIndent)");
1744                            jw.writeEol("out.write(\"<", a.dtdName, " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:nil='true'/>\\n\")");
1745                        }
1746                    }
1747                    if (!isScalar || (!indexed && config.isOptionalScalars() && isScalar))
1748                        end();
1749                    if (indexed) {
1750                        if (!a.isBean && a.attributes != null && a.attributes.length > 0) {
1751                            jw.writeEol("++index");
1752                        }
1753                        end();
1754                    }
1755                }
1756            }
1757            if (config.isKeepElementPositions()) {
1758                jw.end();
1759                jw.end();
1760            }
1761        }
1762        jw.endMethod(); // writeNodeChildren
1763

1764        // Generate for reading
1765
if (beanElement.isRoot) {
1766            String JavaDoc exceps = "javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException, java.io.IOException";
1767            if (config.isVetoable())
1768                exceps += ", java.beans.PropertyVetoException";
1769
1770            if (!config.isStandalone()) {
1771                jw.beginMethod("read", "org.openide.filesystems.FileObject fo",
1772                               exceps, className, jw.PUBLIC | jw.STATIC | jw.IO);
1773                jw.writeEol("java.io.InputStream in = fo.getInputStream()");
1774                jw.beginTry();
1775                jw.writeEol("return read(in)");
1776                jw.endFinallyBegin();
1777                jw.writeEol("in.close()");
1778                jw.end();
1779                jw.endMethod();
1780            }
1781
1782            jw.beginMethod("read", "java.io.File f",
1783                           exceps, className, jw.PUBLIC | jw.STATIC | jw.IO);
1784            jw.writeEol("java.io.InputStream in = new java.io.FileInputStream(f)");
1785            jw.beginTry();
1786            jw.writeEol("return read(in)");
1787            jw.endFinallyBegin();
1788            jw.writeEol("in.close()");
1789            jw.end();
1790            jw.endMethod();
1791
1792            jw.beginMethod("read", "java.io.InputStream in", exceps, className,
1793                           jw.PUBLIC | jw.STATIC | jw.IO);
1794            geneol("return read(new org.xml.sax.InputSource(in), false, null, null)");
1795            end();
1796            cr();
1797
1798            jw.bigComment("Warning: in readNoEntityResolver character and entity references will\nnot be read from any DTD in the XML source.\nHowever, this way is faster since no DTDs are looked up\n(possibly skipping network access) or parsed.");
1799            jw.beginMethod("readNoEntityResolver", "java.io.InputStream in",
1800                           exceps, className,
1801                           jw.PUBLIC | jw.STATIC | jw.IO);
1802            gencr("return read(new org.xml.sax.InputSource(in), false,");
1803            tabIn();
1804            gen("new org.xml.sax.EntityResolver() ");
1805            begin();
1806            gen("public org.xml.sax.InputSource resolveEntity(String publicId, String systemId) ");
1807            begin();
1808            geneol("java.io.ByteArrayInputStream bin = new java.io.ByteArrayInputStream(new byte[0])");
1809            geneol("return new org.xml.sax.InputSource(bin)");
1810            end();
1811            end();
1812            tabIn();
1813            geneol(", null)");
1814            end();
1815            cr();
1816
1817            jw.beginMethod("read",
1818                           "org.xml.sax.InputSource in, boolean validate, org.xml.sax.EntityResolver er, org.xml.sax.ErrorHandler eh",
1819                           exceps, className,
1820                           jw.PUBLIC | jw.STATIC | jw.IO);
1821            geneol("javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance()");
1822            geneol("dbf.setValidating(validate)");
1823            geneol("dbf.setNamespaceAware(true)");
1824            geneol("javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder()");
1825            gen("if (er != null)");
1826            tabIn();
1827            geneol("db.setEntityResolver(er)");
1828            gen("if (eh != null)");
1829            tabIn();
1830            geneol("db.setErrorHandler(eh)");
1831            geneol("org.w3c.dom.Document doc = db.parse(in)");
1832            geneol("return read(doc)");
1833            end();
1834            cr();
1835
1836            exceps = null;
1837            if (config.isVetoable())
1838                exceps = "java.beans.PropertyVetoException";
1839            jw.beginMethod("read", "org.w3c.dom.Document document",
1840                           exceps, className, jw.PUBLIC | jw.STATIC | jw.IO);
1841            jw.writeEol(className, " a", className, " = new "+className+"()");
1842            jw.writeEol("a", className, ".readFromDocument(document)");
1843            jw.writeEol("return a", className);
1844            jw.endMethod();
1845            
1846            jw.beginMethod("readFromDocument", "org.w3c.dom.Document document",
1847                           exceps, "void", jw.PROTECTED);
1848            if (config.isProcessDocType()) {
1849                String JavaDoc fullDocTypeName;
1850                if (packageName == null)
1851                    fullDocTypeName = className+".DocType";
1852                else
1853                    fullDocTypeName = packageName+"."+className+".DocType";
1854                jw.writeEol("org.w3c.dom.NodeList children = document.getChildNodes()");
1855                jw.writeEol("int length = children.getLength()");
1856                jw.beginFor("int i = 0", "i < length", "++i");
1857                jw.beginIf("children.item(i) instanceof org.w3c.dom.DocumentType");
1858                jw.writeEol("docType = new "+fullDocTypeName+"((org.w3c.dom.DocumentType)children.item(i))");
1859                jw.writeEol("break");
1860                jw.end();
1861                jw.end();
1862            }
1863            geneol("readNode(document.getDocumentElement())");
1864            end();
1865            cr();
1866        }
1867
1868        if (beanElement.isRoot) {
1869            jw.write("protected static class ReadState ");
1870            jw.begin();
1871            jw.writeEol("int lastElementType");
1872            jw.writeEol("int elementPosition");
1873            jw.end();
1874            jw.cr();
1875        }
1876
1877        jw.beginMethod("readNode", "org.w3c.dom.Node node",
1878                       config.isVetoable() ? "java.beans.PropertyVetoException" : null,
1879                       "void", jw.PUBLIC | jw.IO);
1880        jw.write("readNode(node, new java.util.HashMap");
1881        if (config.jdkTarget >= 150)
1882            jw.write("<String, String>");
1883        jw.writeEol("())");
1884        jw.endMethod();
1885
1886        String JavaDoc namespacePrefixesFormalParameter;
1887        if (config.jdkTarget >= 150)
1888            namespacePrefixesFormalParameter = "java.util.Map<String, String> namespacePrefixes";
1889        else
1890            namespacePrefixesFormalParameter = "java.util.Map namespacePrefixes";
1891        
1892        String JavaDoc readNodeArgs = "org.w3c.dom.Node node, "+namespacePrefixesFormalParameter;
1893        jw.beginMethod("readNode", readNodeArgs,
1894                       config.isVetoable() ? "java.beans.PropertyVetoException" : null,
1895                       "void", jw.PUBLIC | jw.IO);
1896        // Go over attributes
1897
beginAttrProcessing("node");
1898        jw.writeEol("boolean firstNamespaceDef = true");
1899        genUpdateNamespaces("namespacePrefixes", "firstNamespaceDef");
1900        
1901        int attrCount = 0;
1902        if (beanElement.isRoot) {
1903            ++attrCount;
1904            jw.writeEol("String xsiPrefix = \"xsi\"");
1905            jw.beginFor("java.util.Iterator it = namespacePrefixes.keySet().iterator()",
1906                        "it.hasNext()", "");
1907            jw.writeEol("String prefix = (String) it.next()");
1908            jw.writeEol("String ns = (String) namespacePrefixes.get(prefix)");
1909            jw.beginIf("\"http://www.w3.org/2001/XMLSchema-instance\".equals(ns)");
1910            jw.writeEol("xsiPrefix = prefix");
1911            jw.writeEol("break");
1912            jw.end();
1913            jw.end();
1914            genReadAttr("schemaLocation", "String",
1915                        "\"+xsiPrefix+\":schemaLocation",
1916                        "node", null, false, null, false, null);
1917        }
1918        jw.writeEol("readNodeAttributes(node, namespacePrefixes, attrs)");
1919        jw.end();
1920        jw.writeEol("readNodeChildren(node, namespacePrefixes)");
1921        jw.endMethod();
1922        
1923        jw.beginMethod("readNodeAttributes", readNodeArgs+", org.w3c.dom.NamedNodeMap attrs",
1924                       config.isVetoable() ? "java.beans.PropertyVetoException" : null,
1925                       "void", jw.PROTECTED | jw.IO);
1926        if (config.isRespectExtension() && beanElement.getExtension() != null)
1927            jw.writeEol("super.readNodeAttributes(node, namespacePrefixes, attrs)");
1928        jw.writeEol("org.w3c.dom.Attr attr");
1929        jw.writeEol("java.lang.String attrValue");
1930        boolean hasNillableElement = false;
1931        for (int i = 0; i < size; i++) {
1932            Property a = (Property)attrList.get(i);
1933            if (a.isNillable())
1934                hasNillableElement = true;
1935            if (!a.isAttribute())
1936                continue;
1937            if (!a.isDirectChild())
1938                continue;
1939            ++attrCount;
1940            genReadAttr(a, "node");
1941        }
1942        jw.endMethod();
1943        
1944        jw.beginMethod("readNodeChildren", readNodeArgs,
1945                       config.isVetoable() ? "java.beans.PropertyVetoException" : null,
1946                       "void", jw.PROTECTED | jw.IO);
1947        if (hasSubElements) {
1948            // FIXME: Should deal with the situation where we get 2 "foo" elements
1949
// and the schema only mentioned 1.
1950
Map dtdNames = new HashMap();
1951            boolean hasDuplicateDtdNames = config.isKeepElementPositions();
1952            boolean hasQNameType = false;
1953            boolean hasNonElementTypes = false;
1954            for (int i = 0; i < size; i++) {
1955                Property a = (Property)attrList.get(i);
1956                if (isTypeQName(a.getType()))
1957                    hasQNameType = true;
1958                if (a.type == Common.TYPE_COMMENT || a.dtdName.equals("#PCDATA")) {
1959                    hasNonElementTypes = true;
1960                    continue;
1961                }
1962                if (a.isAttribute())
1963                    continue;
1964                if (dtdNames.containsKey(a.dtdName)) {
1965                    //jw.comment(a.dtdName+" has duplicates");
1966
hasDuplicateDtdNames = true;
1967                }
1968                dtdNames.put(a.dtdName, a);
1969            }
1970            geneol("org.w3c.dom.NodeList children = node.getChildNodes()");
1971            boolean hasReadState = false;
1972            if (hasDuplicateDtdNames || config.isKeepElementPositions()) {
1973                hasReadState = true;
1974                jw.writeEol(getRootClassName(), ".ReadState readState = new ",
1975                            getRootClassName(),".ReadState()");
1976            }
1977            if (hasDuplicateDtdNames)
1978                jw.writeEol("readState.lastElementType = -1");
1979            if (config.isKeepElementPositions()) {
1980                jw.writeEol("readState.elementPosition = 0");
1981                jw.writeEol("elementsByPosition = new java.lang.Object[children.getLength()]");
1982                jw.writeEol("elementTypesByPosition = new int[children.getLength()]");
1983            }
1984            jw.beginFor("int i = 0, size = children.getLength()",
1985                        "i < size", "++i");
1986            geneol("org.w3c.dom.Node childNode = children.item(i)");
1987            if (!hasNonElementTypes &&
1988                !(config.isRespectExtension() && beanElement.getExtension() != null)) {
1989                jw.beginIf("!(childNode instanceof org.w3c.dom.Element)");
1990                jw.writeEol("continue");
1991                jw.end();
1992            }
1993            geneol("String childNodeName = (childNode.getLocalName() == null ? childNode.getNodeName().intern() : childNode.getLocalName().intern())");
1994            geneol("String childNodeValue = \"\"");
1995            jw.beginIf("childNode.getFirstChild() != null");
1996            geneol("childNodeValue = childNode.getFirstChild().getNodeValue()");
1997            jw.end();
1998            jw.write("boolean recognized = readNodeChild(childNode, childNodeName, childNodeValue, namespacePrefixes");
1999            if (hasReadState)
2000                jw.write(", readState");
2001            jw.writeEol(")");
2002            jw.beginIf("!recognized");
2003            if (!config.isLogSuspicious()) {
2004                comment("Found extra unrecognized childNode");
2005            } else {
2006                jw.beginIf("childNode instanceof org.w3c.dom.Element");
2007                declareLogger();
2008                jw.writeEol("_logger.info(\"Found extra unrecognized childNode '\"+childNodeName+\"'\")");
2009                jw.end();
2010            }
2011            jw.end();
2012            jw.end();
2013            if (config.isKeepElementPositions()) {
2014                jw.beginFor("", "readState.elementPosition < elementTypesByPosition.length",
2015                            "++readState.elementPosition");
2016                jw.writeEol("elementTypesByPosition[readState.elementPosition] = "+elementTypeSetnull);
2017                jw.end();
2018            }
2019            jw.endMethod();
2020
2021            jw.beginMethod("readNodeChild", "org.w3c.dom.Node childNode, String childNodeName, String childNodeValue, "+namespacePrefixesFormalParameter+(hasReadState ? ", "+getRootClassName()+".ReadState readState" : ""),
2022                           config.isVetoable() ? "java.beans.PropertyVetoException" : null,
2023                           "boolean", jw.PROTECTED | jw.IO);
2024           jw.comment("assert childNodeName == childNodeName.intern()");
2025           if (hasNillableElement || hasQNameType ||
2026                nonDirectAttributes.size() > 0)
2027                declareAttrsForRead("childNode");
2028            boolean first = true;
2029            Property anyProp = null; // Is this an any property?
2030
for (int i = 0; i < size; i++) {
2031                Property a = (Property)attrList.get(i);
2032                if (a.isAttribute())
2033                    continue;
2034                boolean indexed = a.isIndexed();
2035                String JavaDoc attr = "_" + a.name;
2036                String JavaDoc baseAttr = attr;
2037                boolean isScalar = a.isScalar();
2038
2039                String JavaDoc type = a.getType().intern();
2040                String JavaDoc baseType = type;
2041                if (indexed)
2042                    type = (baseType + "[]").intern();
2043
2044                if (baseType == "org.w3c.dom.Element") {
2045                    anyProp = a;
2046                    continue;
2047                }
2048                if (first) first = false; else gen("else ");
2049                jw.write("if (");
2050                if (hasDuplicateDtdNames && dtdNames.get(a.dtdName) != a) {
2051                    int alwaysBeforeElementType;
2052                    if (indexed) {
2053                        // Keep reading in elements into this slot, until
2054
// there's another element that says to go on.
2055
alwaysBeforeElementType = i + 1;
2056                    } else {
2057                        // Force it to goto the next slot.
2058
alwaysBeforeElementType = i;
2059                    }
2060                    jw.write("readState.lastElementType < "+alwaysBeforeElementType,
2061                             " && ");
2062                }
2063                if (a.dtdName.equals("#PCDATA"))
2064                    jw.write("childNode instanceof org.w3c.dom.CharacterData");
2065                else if (a.type == Common.TYPE_COMMENT)
2066                    jw.write("childNode instanceof org.w3c.dom.Comment");
2067                else
2068                    jw.write("childNodeName == \""+a.dtdName+"\"");
2069                jw.write(") ");
2070                begin();
2071                String JavaDoc var;
2072                if (a.isNillable()) {
2073                    jw.writeEol("org.w3c.dom.Attr nilAttr = (org.w3c.dom.Attr) attrs.getNamedItem(\"xsi:nil\")");
2074                    jw.beginIf("nilAttr == null || !\"true\".equals(nilAttr.getValue())");
2075                }
2076                if (indexed) {
2077                    var = "a"+a.name;
2078                    if (a.isBean) {
2079                        jw.write(baseType, " ");
2080                    } else {
2081                        geneol(baseType+" "+var);
2082                    }
2083                } else {
2084                    var = attr;
2085                }
2086                if (a.isBean) {
2087                    jw.write(var, " = ");
2088                    genNewDefault(a, true);
2089                    jw.eol();
2090                    if (config.isGeneratePropertyEvents()) {
2091                        geneol(var+"._setPropertyChangeSupport(eventListeners)");
2092                        if (config.isVetoable())
2093                            geneol(var+"._setVetoableChangeSupport(vetos)");
2094                    }
2095                    if (config.isGenerateParentRefs())
2096                        jw.writeEol(var+"._setParent(this)");
2097                }
2098                boolean generatedSet = true;
2099                if (a.isBean)
2100                    geneol(var+".readNode(childNode, namespacePrefixes)");
2101                else if (a.dtdName.equals("#PCDATA")) {
2102                    geneol(var+" = ((org.w3c.dom.CharacterData)childNode).getData()");
2103                } else if (a.type == Common.TYPE_COMMENT) {
2104                    geneol(var+" = ((org.w3c.dom.CharacterData)childNode).getData()");
2105                } else {
2106                    if (config.isTrimNonStrings() &&
2107                        baseType != "String" && baseType != "java.lang.String") {
2108                        jw.writeEol("childNodeValue = childNodeValue.trim()");
2109                    }
2110                    List exceps = JavaUtil.exceptionsFromParsingText(baseType);
2111                    if (!exceps.isEmpty()) {
2112                        jw.beginTry();
2113                    }
2114                    if (baseType == "boolean" || baseType == "java.lang.Boolean") {
2115                        gencr("if (childNode.getFirstChild() == null)");
2116                        tabIn();
2117                        if (baseType == "boolean")
2118                            geneol(var+" = true");
2119                        else
2120                            geneol(var+" = Boolean.TRUE");
2121                        gencr("else");
2122                        tabIn();
2123                    }
2124                    generatedSet = genReadType(baseType, var, "childNodeValue",
2125                                               false, null,
2126                                               isScalar,
2127                                               (SchemaRep.EncodingStyle) a.searchExtraData(SchemaRep.EncodingStyle.class));
2128                        SchemaRep.WhiteSpace ws = (SchemaRep.WhiteSpace) a.searchExtraData(SchemaRep.WhiteSpace.class);
2129                        if (ws != null)
2130                            genWhiteSpaceRestriction(ws, var, baseType);
2131                        //}
2132
if (!indexed && config.isOptionalScalars() && isScalar) {
2133                        jw.writeEol(a.getScalarIsSet(), " = true");
2134                    }
2135                    int directAttrCount = 0;
2136                    for (int attrNum = 0; attrNum < a.attributes.length; ++attrNum) {
2137                        AttrProp myAttrProp = a.attributes[attrNum];
2138                        //jw.comment("myAttrProp="+myAttrProp);
2139
for (Iterator it = nonDirectAttributes.iterator(); it.hasNext(); ) {
2140                            Property attrProperty = (Property) it.next();
2141                            AttrProp attrProp = attrProperty.getAttrProp();
2142                            if (myAttrProp == attrProp) {
2143                                ++directAttrCount;
2144                                genReadAttr(attrProperty, "childNode");
2145                            }
2146                        }
2147                    }
2148                
2149                    if (!exceps.isEmpty()) {
2150                        end();
2151                        genRethrowExceptions(exceps);
2152                    }
2153                }
2154                if (indexed && generatedSet)
2155                    jw.writeEol(attr, ".add(",
2156                                JavaUtil.toObject(var, baseType,
2157                                                  config.isForME()),
2158                                ")");
2159                if (a.isNillable()) {
2160                    jw.endElseBegin();
2161                    if (indexed)
2162                        jw.writeEol(attr, ".add(null)");
2163                    else
2164                        jw.writeEol(var, " = ", JavaUtil.nullValueForType(baseType));
2165                    jw.end();
2166                }
2167                if (hasDuplicateDtdNames)
2168                    jw.writeEol("readState.lastElementType = "+i);
2169                if (config.isKeepElementPositions()) {
2170                    jw.writeEol("elementsByPosition[readState.elementPosition] = "+JavaUtil.toObject(var, type, config.isForME()));
2171                    jw.writeEol("elementTypesByPosition[readState.elementPosition++] = "+i);
2172                }
2173                end();
2174            }
2175            if (anyProp != null) {
2176                String JavaDoc attr = "_" + anyProp.name;
2177                boolean indexed = anyProp.isIndexed();
2178                if (first) first = false; else gen("else ");
2179                jw.beginIf("childNode instanceof org.w3c.dom.Element");
2180                if (indexed)
2181                    jw.writeEol(attr, ".add((org.w3c.dom.Element)childNode)");
2182                else
2183                    jw.writeEol(attr, " = (org.w3c.dom.Element) childNode");
2184                jw.end();
2185            }
2186            if (!first) {
2187                gen("else ");
2188                begin();
2189                if (config.isRespectExtension() && beanElement.getExtension() != null) {
2190                    jw.write("return super.readNodeChild(childNode, childNodeName, childNodeValue, namespacePrefixes");
2191                    if (hasReadState)
2192                        jw.write(", readState");
2193                    jw.writeEol(")");
2194                } else
2195                    jw.writeEol("return false");
2196                /*
2197                jw.writeEol("System.out.println(\"Found extra unrecognized childNode: \"+childNodeName)");
2198                jw.writeEol("System.out.println(\"namespaceURI=\"+childNode.getNamespaceURI())");
2199                jw.writeEol("System.out.println(\"prefix=\"+childNode.getPrefix())");
2200                jw.writeEol("System.out.println(\"localName=\"+childNode.getLocalName())");
2201                jw.writeEol("System.out.println(\"nodeName=\"+childNode.getNodeName())");
2202                */

2203                end();
2204            }
2205            jw.writeEol("return true");
2206        } else {
2207            if (config.isRespectExtension() && beanElement.getExtension() != null) {
2208                jw.writeEol("super.readNodeChildren(node, namespacePrefixes)");
2209            }
2210        }
2211        jw.endMethod();
2212        
2213        if (beanElement.isRoot) {
2214            if (!config.isUseRuntime())
2215                genPrintXML();
2216            genSpecialTypes();
2217        }
2218    }
2219    
2220    protected void genFetchXMLEventReader() throws IOException {
2221        jw.select(BODY_SECTION);
2222        String JavaDoc commonBean = commonBeanType();
2223        String JavaDoc beanName = beanElement.node.getName();
2224        if (beanElement.isRoot) {
2225            String JavaDoc beanQNameName = declareQName(beanElement.getNamespace(), beanName, null);
2226
2227            jw.beginMethod("fetchXMLEventReader", "", null, "javax.xml.stream.XMLEventReader");
2228            jw.writeEol("return new ", getRootClassName()+".XMLEventStateManager(this, ", beanQNameName, ")");
2229            jw.endMethod();
2230            
2231            jw.write("static class XMLEventStateManager implements javax.xml.stream.XMLEventReader");
2232            jw.begin();
2233            jw.writeEol("private java.util.Stack<"+commonBean+"> beans = new java.util.Stack<"+commonBean+">()");
2234            jw.writeEol("private java.util.Stack<javax.xml.namespace.QName> nodeNames = new java.util.Stack<javax.xml.namespace.QName>()");
2235            jw.writeEol("private java.util.Stack<Integer> eventNumbers = new java.util.Stack<Integer>()");
2236            jw.writeEol("private java.util.Stack<Integer> arrayIndices = new java.util.Stack<Integer>()");
2237            jw.writeEol("private java.util.Stack<Integer> elementNumbers = new java.util.Stack<Integer>()");
2238            jw.writeEol("private "+commonBean+" currentBean");
2239            jw.writeEol("private javax.xml.namespace.QName currentNodeName");
2240            jw.writeEol("private int currentEventNumber");
2241            jw.writeEol("private int currentArrayIndex");
2242            jw.writeEol("private int currentElementNumber");
2243            jw.writeEol("private javax.xml.stream.events.XMLEvent next");
2244            jw.cr();
2245            jw.write("public XMLEventStateManager("+commonBean+" bean, javax.xml.namespace.QName nodeName)");
2246            jw.begin();
2247            jw.writeEol("currentBean = bean");
2248            jw.writeEol("this.currentNodeName = nodeName");
2249            jw.writeEol("currentEventNumber = 0");
2250            jw.writeEol("currentArrayIndex = 0");
2251            jw.writeEol("currentElementNumber = 0");
2252            jw.end();
2253            jw.cr();
2254            jw.write("public int getEventNumber()");
2255            jw.begin();
2256            jw.writeEol("return currentEventNumber");
2257            jw.end();
2258            jw.cr();
2259            jw.write("public void nextEventNumber()");
2260            jw.begin();
2261            jw.writeEol("++currentEventNumber");
2262            jw.writeEol("currentArrayIndex = 0");
2263            jw.writeEol("currentElementNumber = 0");
2264            jw.end();
2265            jw.cr();
2266            jw.write("public int getArrayIndex()");
2267            jw.begin();
2268            jw.writeEol("return currentArrayIndex");
2269            jw.end();
2270            jw.cr();
2271            jw.write("public void nextArrayIndex()");
2272            jw.begin();
2273            jw.writeEol("++currentArrayIndex");
2274            jw.writeEol("currentElementNumber = 0");
2275            jw.end();
2276            jw.cr();
2277            jw.write("public int getElementNumber()");
2278            jw.begin();
2279            jw.writeEol("return currentElementNumber");
2280            jw.end();
2281            jw.cr();
2282            jw.write("public void nextElementNumber()");
2283            jw.begin();
2284            jw.writeEol("++currentElementNumber");
2285            jw.end();
2286            jw.cr();
2287            jw.write("public javax.xml.namespace.QName getNodeName()");
2288            jw.begin();
2289            jw.writeEol("return currentNodeName");
2290            jw.end();
2291            jw.cr();
2292            jw.write("public void enterChildBean("+commonBean+" bean, javax.xml.namespace.QName nodeName)");
2293            jw.begin();
2294            jw.writeEol("beans.push(currentBean)");
2295            jw.writeEol("eventNumbers.push(currentEventNumber)");
2296            jw.writeEol("arrayIndices.push(currentArrayIndex)");
2297            jw.writeEol("elementNumbers.push(currentElementNumber)");
2298            jw.writeEol("nodeNames.push(currentNodeName)");
2299            jw.writeEol("currentBean = bean");
2300            jw.writeEol("currentEventNumber = 0");
2301            jw.writeEol("currentArrayIndex = 0");
2302            jw.writeEol("currentElementNumber = 0");
2303            jw.writeEol("currentNodeName = nodeName");
2304            jw.end();
2305            jw.cr();
2306            jw.write("public void doneWithBean()");
2307            jw.begin();
2308            jw.write("if (beans.isEmpty())");
2309            jw.begin();
2310            jw.writeEol("currentBean = null");
2311            jw.writeEol("currentEventNumber = -1");
2312            jw.end();
2313            jw.write("else");
2314            jw.begin();
2315            jw.writeEol("currentBean = beans.pop()");
2316            jw.writeEol("currentEventNumber = eventNumbers.pop()");
2317            jw.writeEol("currentArrayIndex = arrayIndices.pop()");
2318            jw.writeEol("currentElementNumber = elementNumbers.pop()");
2319            jw.writeEol("currentNodeName = nodeNames.pop()");
2320            jw.end();
2321            jw.end();
2322            jw.cr();
2323            jw.write("public Object getProperty(String name) throws IllegalArgumentException");
2324            jw.begin();
2325            jw.writeEol("throw new IllegalArgumentException(\"Got no properties\")");
2326            jw.end();
2327            jw.cr();
2328            jw.write("public void remove()");
2329            jw.begin();
2330            jw.writeEol("throw new UnsupportedOperationException()");
2331            jw.end();
2332            jw.cr();
2333            jw.write("public javax.xml.stream.events.XMLEvent peek() throws javax.xml.stream.XMLStreamException");
2334            jw.begin();
2335            jw.beginIf("next != null");
2336            jw.writeEol("return next");
2337            jw.end();
2338            jw.writeEol("setNextEvent()");
2339            jw.writeEol("return next");
2340            jw.end();
2341            jw.cr();
2342            jw.write("public javax.xml.stream.events.XMLEvent nextTag() throws javax.xml.stream.XMLStreamException");
2343            jw.begin();
2344            jw.writeEol("throw new IllegalArgumentException()");
2345            jw.end();
2346            jw.cr();
2347            jw.write("public javax.xml.stream.events.XMLEvent nextEvent() throws javax.xml.stream.XMLStreamException");
2348            jw.begin();
2349            jw.writeEol("javax.xml.stream.events.XMLEvent result = null");
2350            jw.write("if (next != null)");
2351            jw.begin();
2352            jw.writeEol("result = next");
2353            jw.writeEol("next = null");
2354            jw.writeEol("return result");
2355            jw.end();
2356            jw.writeEol("setNextEvent()");
2357            jw.beginIf("next == null");
2358            jw.writeEol("throw new java.util.NoSuchElementException()");
2359            jw.end();
2360            jw.writeEol("result = next");
2361            jw.writeEol("next = null");
2362            jw.writeEol("return result");
2363            jw.end();
2364            jw.cr();
2365            jw.write("private void setNextEvent() throws javax.xml.stream.XMLStreamException");
2366            jw.begin();
2367            jw.write("while (next == null && currentEventNumber >= 0)");
2368            jw.begin();
2369            jw.writeEol("next = currentBean.getXMLEvent(this)");
2370            jw.end();
2371            jw.end();
2372            jw.cr();
2373            jw.write("public Object next()");
2374            jw.begin();
2375            jw.beginTry();
2376            jw.writeEol("return nextEvent()");
2377            jw.write("} catch (javax.xml.stream.XMLStreamException e)");
2378            jw.begin();
2379            jw.writeEol("throw new RuntimeException(e)");
2380            jw.end();
2381            jw.end();
2382            jw.cr();
2383            jw.write("public boolean hasNext()");
2384            jw.begin();
2385            jw.beginIf("next != null");
2386            jw.writeEol("return true");
2387            jw.end();
2388            jw.beginTry();
2389            jw.writeEol("setNextEvent()");
2390            jw.endCatch("javax.xml.stream.XMLStreamException e");
2391            jw.writeEol("throw new RuntimeException(e)");
2392            jw.end();
2393            jw.writeEol("return (next != null)");
2394            jw.end();
2395            jw.cr();
2396            jw.write("public String getElementText() throws javax.xml.stream.XMLStreamException");
2397            jw.begin();
2398            jw.writeEol("throw new IllegalArgumentException()");
2399            jw.end();
2400            jw.cr();
2401            jw.write("public void close() throws javax.xml.stream.XMLStreamException");
2402            jw.begin();
2403            jw.writeEol("currentEventNumber = -1");
2404            jw.writeEol("beans.clear()");
2405            jw.writeEol("eventNumbers.clear()");
2406            jw.writeEol("arrayIndices.clear()");
2407            jw.writeEol("nodeNames.clear()");
2408            jw.end();
2409            jw.end();
2410
2411            jw.write("static abstract class BaseXMLEvent implements javax.xml.stream.events.XMLEvent ");
2412            jw.begin();
2413            jw.write("public void writeAsEncodedUnicode(java.io.Writer writer) throws javax.xml.stream.XMLStreamException ");
2414            jw.begin();
2415            jw.writeEol("throw new UnsupportedOperationException()");
2416            jw.end();
2417            jw.cr();
2418            jw.write("public boolean isStartElement() ");
2419            jw.begin();
2420            jw.writeEol("return false");
2421            jw.end();
2422            jw.cr();
2423            jw.write("public boolean isStartDocument() ");
2424            jw.begin();
2425            jw.writeEol("return false");
2426            jw.end();
2427            jw.cr();
2428            jw.write("public javax.xml.stream.events.Characters asCharacters() ");
2429            jw.begin();
2430            jw.writeEol("return (javax.xml.stream.events.Characters) this");
2431            jw.end();
2432            jw.cr();
2433            jw.write("public javax.xml.stream.events.EndElement asEndElement() ");
2434            jw.begin();
2435            jw.writeEol("return (javax.xml.stream.events.EndElement) this");
2436            jw.end();
2437            jw.cr();
2438            jw.write("public javax.xml.stream.events.StartElement asStartElement() ");
2439            jw.begin();
2440            jw.writeEol("return (javax.xml.stream.events.StartElement) this");
2441            jw.end();
2442            jw.cr();
2443            jw.write("public javax.xml.stream.Location getLocation() ");
2444            jw.begin();
2445            jw.writeEol("throw new UnsupportedOperationException()");
2446            jw.end();
2447            jw.cr();
2448            jw.write("public javax.xml.namespace.QName getSchemaType() ");
2449            jw.begin();
2450            jw.writeEol("return null");
2451            jw.end();
2452            jw.cr();
2453            jw.write("public boolean isAttribute() ");
2454            jw.begin();
2455            jw.writeEol("return false");
2456            jw.end();
2457            jw.cr();
2458            jw.write("public boolean isCharacters() ");
2459            jw.begin();
2460            jw.writeEol("return false");
2461            jw.end();
2462            jw.cr();
2463            jw.write("public boolean isEndDocument() ");
2464            jw.begin();
2465            jw.writeEol("return false");
2466            jw.end();
2467            jw.cr();
2468            jw.write("public boolean isEndElement() ");
2469            jw.begin();
2470            jw.writeEol("return false");
2471            jw.end();
2472            jw.cr();
2473            jw.write("public boolean isEntityReference() ");
2474            jw.begin();
2475            jw.writeEol("return false");
2476            jw.end();
2477            jw.cr();
2478            jw.write("public boolean isNamespace() ");
2479            jw.begin();
2480            jw.writeEol("return false");
2481            jw.end();
2482            jw.cr();
2483            jw.write("public boolean isProcessingInstruction() ");
2484            jw.begin();
2485            jw.writeEol("return false");
2486            jw.end();
2487            jw.cr();
2488            jw.end();
2489            jw.cr();
2490            jw.write("static class ThisStartDocument extends BaseXMLEvent implements javax.xml.stream.events.StartDocument ");
2491            jw.begin();
2492            jw.write("public int getEventType() ");
2493            jw.begin();
2494            jw.writeEol("return javax.xml.stream.XMLStreamConstants.START_DOCUMENT");
2495            jw.end();
2496            jw.cr();
2497            jw.write("public boolean isStartDocument() ");
2498            jw.begin();
2499            jw.writeEol("return true");
2500            jw.end();
2501            jw.cr();
2502            jw.write("public boolean standaloneSet() ");
2503            jw.begin();
2504            jw.writeEol("return false");
2505            jw.end();
2506            jw.cr();
2507            jw.write("public boolean isStandalone() ");
2508            jw.begin();
2509            jw.writeEol("return false");
2510            jw.end();
2511            jw.cr();
2512            jw.write("public String getVersion() ");
2513            jw.begin();
2514            jw.writeEol("return \"1.0\"");
2515            jw.end();
2516            jw.cr();
2517            jw.write("public String getSystemId() ");
2518            jw.begin();
2519            jw.writeEol("return null");
2520            jw.end();
2521            jw.cr();
2522            jw.write("public String getCharacterEncodingScheme() ");
2523            jw.begin();
2524            jw.writeEol("return \"UTF-8\"");
2525            jw.end();
2526            jw.cr();
2527            jw.write("public boolean encodingSet() ");
2528            jw.begin();
2529            jw.writeEol("return true");
2530            jw.end();
2531            jw.end();
2532            jw.cr();
2533            jw.write("static class ThisAttribute extends BaseXMLEvent implements javax.xml.stream.events.Attribute ");
2534            jw.begin();
2535            jw.writeEol("private javax.xml.namespace.QName name");
2536            jw.writeEol("private String value");
2537            jw.writeEol("private String dtdType");
2538            jw.writeEol("private javax.xml.namespace.QName schemaType");
2539            jw.cr();
2540            jw.write("public ThisAttribute(javax.xml.namespace.QName name, String value, String dtdType, javax.xml.namespace.QName schemaType) ");
2541            jw.begin();
2542            jw.writeEol("this.name = name");
2543            jw.writeEol("this.value = value");
2544            jw.writeEol("this.dtdType = dtdType");
2545            jw.writeEol("this.schemaType = schemaType");
2546            jw.end();
2547            jw.cr();
2548            jw.write("public int getEventType() ");
2549            jw.begin();
2550            jw.writeEol("return javax.xml.stream.XMLStreamConstants.ATTRIBUTE");
2551            jw.end();
2552            jw.cr();
2553            jw.write("public boolean isSpecified() ");
2554            jw.begin();
2555            jw.writeEol("return true");
2556            jw.end();
2557            jw.cr();
2558            jw.write("public String getValue() ");
2559            jw.begin();
2560            jw.writeEol("return value");
2561            jw.end();
2562            jw.cr();
2563            jw.write("public javax.xml.namespace.QName getName() ");
2564            jw.begin();
2565            jw.writeEol("return name");
2566            jw.end();
2567            jw.cr();
2568            jw.write("public String getDTDType() ");
2569            jw.begin();
2570            jw.writeEol("return dtdType");
2571            jw.end();
2572            jw.cr();
2573            jw.write("public javax.xml.namespace.QName getSchemaType() ");
2574            jw.begin();
2575            jw.writeEol("return schemaType");
2576            jw.end();
2577            jw.end();
2578            jw.cr();
2579            jw.write("static class ThisNamespace extends ThisAttribute implements javax.xml.stream.events.Namespace ");
2580            jw.begin();
2581            jw.writeEol("private String prefix");
2582            jw.cr();
2583            jw.write("public ThisNamespace(String prefix, String uri) ");
2584            jw.begin();
2585            jw.writeEol("super(new javax.xml.namespace.QName(\"http://FIXME/xmlns\", prefix, \"xmlns\"), uri, null, null)");
2586            jw.writeEol("this.prefix = prefix");
2587            jw.end();
2588            jw.cr();
2589            jw.write("public boolean isDefaultNamespaceDeclaration() ");
2590            jw.begin();
2591            jw.writeEol("return \"\".equals(prefix)");
2592            jw.end();
2593            jw.cr();
2594            jw.write("public String getPrefix() ");
2595            jw.begin();
2596            jw.writeEol("return prefix");
2597            jw.end();
2598            jw.cr();
2599            jw.write("public String getNamespaceURI() ");
2600            jw.begin();
2601            jw.writeEol("return getValue()");
2602            jw.end();
2603            jw.end();
2604            jw.cr();
2605            jw.write("static class ThisStartElement extends BaseXMLEvent implements javax.xml.stream.events.StartElement ");
2606            jw.begin();
2607            jw.writeEol("private javax.xml.namespace.QName name");
2608            jw.writeEol("private java.util.Map<javax.xml.namespace.QName, ThisAttribute> attributes = new java.util.HashMap<javax.xml.namespace.QName, ThisAttribute>()");
2609            jw.writeEol("private java.util.Map<String, ThisNamespace> namespaces = new java.util.HashMap<String, ThisNamespace>()");
2610            jw.cr();
2611            jw.write("public ThisStartElement(javax.xml.namespace.QName name) ");
2612            jw.begin();
2613            jw.writeEol("this.name = name");
2614            jw.end();
2615            jw.cr();
2616            jw.write("public void addAttribute(javax.xml.namespace.QName attrName, String attrValue, String dtdType, javax.xml.namespace.QName schemaType) ");
2617            jw.begin();
2618            jw.writeEol("attributes.put(attrName, new ThisAttribute(attrName, attrValue, dtdType, schemaType))");
2619            jw.end();
2620            jw.cr();
2621            jw.write("public void addNamespace(String prefix, String uri) ");
2622            jw.begin();
2623            jw.writeEol("namespaces.put(prefix, new ThisNamespace(prefix, uri))");
2624            jw.end();
2625            jw.cr();
2626            jw.write("public int getEventType() ");
2627            jw.begin();
2628            jw.writeEol("return javax.xml.stream.XMLStreamConstants.START_ELEMENT");
2629            jw.end();
2630            jw.cr();
2631            jw.write("public boolean isStartElement() ");
2632            jw.begin();
2633            jw.writeEol("return true");
2634            jw.end();
2635            jw.cr();
2636            jw.write("public String getNamespaceURI(String prefix) ");
2637            jw.begin();
2638            jw.writeEol("return namespaces.get(prefix).getNamespaceURI()");
2639            jw.end();
2640            jw.cr();
2641            jw.write("public javax.xml.stream.events.Attribute getAttributeByName(javax.xml.namespace.QName name) ");
2642            jw.begin();
2643            jw.writeEol("return attributes.get(name)");
2644            jw.end();
2645            jw.cr();
2646            jw.write("public java.util.Iterator getNamespaces() ");
2647            jw.begin();
2648            jw.writeEol("return namespaces.values().iterator()");
2649            jw.end();
2650            jw.cr();
2651            jw.write("public javax.xml.namespace.NamespaceContext getNamespaceContext() ");
2652            jw.begin();
2653            jw.writeEol("throw new UnsupportedOperationException()");
2654            jw.end();
2655            jw.cr();
2656            jw.write("public javax.xml.namespace.QName getName() ");
2657            jw.begin();
2658            jw.writeEol("return name");
2659            jw.end();
2660            jw.cr();
2661            jw.write("public java.util.Iterator getAttributes() ");
2662            jw.begin();
2663            jw.writeEol("return attributes.values().iterator()");
2664            jw.end();
2665            jw.write("public String toString() ");
2666            jw.begin();
2667            jw.writeEol("return \"StartElement: \"+name.toString()");
2668            jw.end();
2669            jw.end();
2670            jw.cr();
2671            jw.write("static class ThisEndElement extends BaseXMLEvent implements javax.xml.stream.events.EndElement ");
2672            jw.begin();
2673            jw.writeEol("private javax.xml.namespace.QName name");
2674            jw.cr();
2675            jw.write("public ThisEndElement(javax.xml.namespace.QName name) ");
2676            jw.begin();
2677            jw.writeEol("this.name = name");
2678            jw.end();
2679            jw.cr();
2680            jw.write("public int getEventType() ");
2681            jw.begin();
2682            jw.writeEol("return javax.xml.stream.XMLStreamConstants.END_ELEMENT");
2683            jw.end();
2684            jw.cr();
2685            jw.write("public boolean isEndElement() ");
2686            jw.begin();
2687            jw.writeEol("return true");
2688            jw.end();
2689            jw.cr();
2690            jw.write("public java.util.Iterator getNamespaces() ");
2691            jw.begin();
2692            jw.writeEol("throw new UnsupportedOperationException()");
2693            jw.end();
2694            jw.cr();
2695            jw.write("public javax.xml.namespace.QName getName() ");
2696            jw.begin();
2697            jw.writeEol("return name");
2698            jw.end();
2699            jw.write("public String toString() ");
2700            jw.begin();
2701            jw.writeEol("return \"EndElement: \"+name.toString()");
2702            jw.end();
2703            jw.end();
2704            jw.cr();
2705            jw.write("static class ThisCharacters extends BaseXMLEvent implements javax.xml.stream.events.Characters ");
2706            jw.begin();
2707            jw.writeEol("private String data");
2708            jw.cr();
2709            jw.write("public ThisCharacters(String data) ");
2710            jw.begin();
2711            jw.writeEol("this.data = data");
2712            jw.end();
2713            jw.cr();
2714            jw.write("public int getEventType() ");
2715            jw.begin();
2716            jw.writeEol("return javax.xml.stream.XMLStreamConstants.CHARACTERS");
2717            jw.end();
2718            jw.cr();
2719            jw.write("public boolean isCharacters() ");
2720            jw.begin();
2721            jw.writeEol("return true");
2722            jw.end();
2723            jw.cr();
2724            jw.write("public boolean isWhiteSpace() ");
2725            jw.begin();
2726            jw.write("for (int i = 0; i < data.length(); ++i) ");
2727            jw.begin();
2728            jw.writeEol("char c = data.charAt(i)");
2729            jw.writeEol("if (!Character.isWhitespace(c))");
2730            jw.writeEol("return false");
2731            jw.end();
2732            jw.writeEol("return true");
2733            jw.end();
2734            jw.cr();
2735            jw.write("public boolean isIgnorableWhiteSpace() ");
2736            jw.begin();
2737            jw.writeEol("return false");
2738            jw.end();
2739            jw.cr();
2740            jw.write("public boolean isCData() ");
2741            jw.begin();
2742            jw.writeEol("return false");
2743            jw.end();
2744            jw.cr();
2745            jw.write("public String getData() ");
2746            jw.begin();
2747            jw.writeEol("return data");
2748            jw.end();
2749            jw.write("public String toString() ");
2750            jw.begin();
2751            jw.writeEol("return \"Characters: \"+data");
2752            jw.end();
2753            jw.end();
2754            jw.cr();
2755            jw.write("static class ThisEndDocument extends BaseXMLEvent implements javax.xml.stream.events.EndDocument ");
2756            jw.begin();
2757            jw.write("public int getEventType() ");
2758            jw.begin();
2759            jw.writeEol("return javax.xml.stream.XMLStreamConstants.END_DOCUMENT");
2760            jw.end();
2761            jw.cr();
2762            jw.write("public boolean isEndDocument() ");
2763            jw.begin();
2764            jw.writeEol("return true");
2765            jw.end();
2766            jw.end();
2767            jw.cr();
2768        }
2769        jw.beginMethod("getXMLEvent", getRootClassName()+".XMLEventStateManager state", null, "javax.xml.stream.events.XMLEvent");
2770        jw.write("switch (state.getEventNumber()) ");
2771        jw.begin();
2772        int caseNum = 0;
2773        if (beanElement.isRoot) {
2774            jw.writecr("case "+caseNum++, ":");
2775            jw.indentRight();
2776            jw.writeEol("state.nextEventNumber()");
2777            jw.writeEol("return new ThisStartDocument()");
2778            jw.indentLeft();
2779        }
2780        
2781        jw.writecr("case "+caseNum++, ":");
2782        jw.begin();
2783        jw.writeEol("state.nextEventNumber()");
2784        jw.writeEol(getRootClassName()+".ThisStartElement startElement = new ",
2785                getRootClassName(),".ThisStartElement(state.getNodeName())");
2786        int size = attrList.size();
2787        for (int i = 0; i < size; i++) {
2788            Property a = (Property)attrList.get(i);
2789            if (!a.isAttribute())
2790                continue;
2791            if (!a.isDirectChild())
2792                continue;
2793            String JavaDoc qNameName = declareQName(a.getNamespace(), a.dtdName, null);
2794            String JavaDoc typeQNameName;
2795            //System.out.println("graphNode null for "+a.getType());
2796
SchemaRep schemaRep = new SchemaRep();
2797            String JavaDoc xmlSchemaType = schemaRep.javaType2XMLSchemaTypeComplex(a.getType());
2798            //System.out.println("xmlSchemaType="+xmlSchemaType);
2799
typeQNameName = declareQName(schemaRep.getNamespaceURI(schemaRep.prefixOf(xmlSchemaType)),
2800                    schemaRep.removePrefix(xmlSchemaType), null);
2801
2802            String JavaDoc varName = "_"+a.name;
2803            if (!a.isScalar()) {
2804                jw.beginIf(varName+" != null");
2805            } else if (config.isOptionalScalars() && a.isScalar()) {
2806                jw.beginIf(a.getScalarIsSet());
2807            }
2808            jw.write("startElement.addAttribute(", qNameName, ", ");
2809            jw.write(JavaUtil.typeToString(a.getType(), varName));
2810            jw.writeEol(", \"CDATA\", ", typeQNameName, ")");
2811            if (!a.isScalar() || (config.isOptionalScalars() && a.isScalar()))
2812                jw.end();
2813        }
2814
2815        if (beanElement.isRoot) {
2816            jw.beginIf("schemaLocation != null");
2817            String JavaDoc slQNameName = declareQName("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation", "xsi");
2818            String JavaDoc typeQNameName = declareQName("http://www.w3.org/2001/XMLSchema", "string", "xsd");
2819            jw.write("startElement.addAttribute(", slQNameName, ", ");
2820            jw.writeEol("schemaLocation, \"CDATA\", ", typeQNameName, ")");
2821            jw.end();
2822        }
2823        jw.writeEol("return startElement");
2824        jw.end();
2825
2826        int numberOfNonAttributeProperties = countNumberOfNonAttributeProperties();
2827        comment("Number of non attribute properties: "+numberOfNonAttributeProperties);
2828        int childStartCaseNum = caseNum;
2829        if (caseNum < childStartCaseNum + numberOfNonAttributeProperties) {
2830            while (caseNum < childStartCaseNum + numberOfNonAttributeProperties) {
2831                jw.writecr("case "+caseNum++, ":");
2832            }
2833            jw.indentRight();
2834            // numberOfNonAttributeProperties
2835
jw.writeEol("javax.xml.stream.events.XMLEvent event = getXMLEventChildren(state, state.getEventNumber() - "+(childStartCaseNum)+")");
2836            jw.writeEol("return event");
2837            jw.indentLeft();
2838       }
2839        
2840        jw.writecr("case "+caseNum++, ":");
2841        jw.indentRight();
2842        jw.writeEol("state.nextEventNumber()");
2843        jw.writeEol("return new ", getRootClassName(), ".ThisEndElement(state.getNodeName())");
2844        jw.indentLeft();
2845
2846        if (beanElement.isRoot) {
2847            jw.writecr("case "+caseNum++, ":");
2848            jw.indentRight();
2849            jw.writeEol("state.nextEventNumber()");
2850            jw.writeEol("return new ThisEndDocument()");
2851            jw.indentLeft();
2852        }
2853        jw.writecr("default:");
2854        jw.indentRight();
2855        jw.writeEol("state.doneWithBean()");
2856        jw.writeEol("break");
2857        jw.indentLeft();
2858        jw.end();
2859        jw.writeEol("return null");
2860        jw.endMethod();
2861        
2862        jw.beginMethod("getXMLEventChildren", getRootClassName()+".XMLEventStateManager state, int eventNumber", null, "javax.xml.stream.events.XMLEvent", jw.PROTECTED);
2863        caseNum = 0;
2864        jw.write("switch (eventNumber) ");
2865        jw.begin();
2866        
2867        if (config.isRespectExtension() && beanElement.getExtension() != null) {
2868            jw.writecr("default:");
2869            jw.indentRight();
2870            jw.writeEol("javax.xml.stream.events.XMLEvent event = super.getXMLEventChildren(state, eventNumber)");
2871            jw.beginIf("true"); // workaround "unreachable statement" error from javac which can happen if default is the only thing in the switch
2872
jw.writeEol("return event");
2873            jw.end();
2874            jw.indentLeft();
2875            caseNum = countNumberOfNonAttributePropertiesRecurse(beanElement.getExtension());
2876        }
2877        for (int i = 0; i < size; i++) {
2878            Property a = (Property)attrList.get(i);
2879            if (a.isAttribute())
2880                continue;
2881            boolean indexed = a.isIndexed();
2882            String JavaDoc varName = "_"+a.name;
2883            
2884            String JavaDoc qNameName = declareQName(a.getNamespace(), a.dtdName, null);
2885            jw.writecr("case "+caseNum++, ":");
2886            jw.begin();
2887            if (indexed) {
2888                varName = "element";
2889                jw.writeEol(a.getTypeFullClassName(packageName), " element = null");
2890                if (!a.isBean) {
2891                    jw.beginIf("state.getElementNumber() == 0");
2892                }
2893                jw.beginWhile("state.getArrayIndex() < size"+a.name+"()");
2894                jw.writeEol("element = ", a.getReadMethod(true), "(state.getArrayIndex())");
2895                jw.beginIf("element != null");
2896                jw.writeEol("break");
2897                jw.end();
2898                jw.writeEol("state.nextArrayIndex()");
2899                jw.end();
2900                if (!a.isBean) {
2901                    jw.endElseBegin();
2902                    jw.writeEol("element = ", a.getReadMethod(true), "(state.getArrayIndex())");
2903                    jw.writeEol("assert element != null");
2904                    jw.end();
2905                }
2906            } else {
2907            }
2908            if (a.isBean) {
2909                jw.beginIf(varName+" != null");
2910                if (indexed)
2911                    jw.writeEol("state.nextArrayIndex()");
2912                else
2913                    jw.writeEol("state.nextEventNumber()");
2914                jw.write("state.enterChildBean(", varName, ", ");
2915                jw.writeEol(qNameName, ")");
2916                jw.writeEol("return ", varName, ".getXMLEvent(state)");
2917                jw.endElseBegin();
2918                jw.writeEol("state.nextEventNumber()");
2919                jw.end();
2920                jw.writeEol("break");
2921                jw.end();
2922            } else {
2923                if (!a.isScalar()) {
2924                    jw.beginIf(varName+" != null");
2925                } else if (config.isOptionalScalars() && a.isScalar()) {
2926                    jw.beginIf(a.getScalarIsSet());
2927                }
2928                jw.writeEol("state.nextElementNumber()");
2929                jw.write("switch (state.getElementNumber()) ");
2930                jw.begin();
2931                jw.writecr("case 1:");
2932                jw.indentRight();
2933                jw.write(getRootClassName(), ".ThisStartElement startElement = new ", getRootClassName());
2934                jw.writeEol(".ThisStartElement(", qNameName, ")");
2935                for (int attrNum = 0; attrNum < a.attributes.length; ++attrNum) {
2936                    AttrProp attr = a.attributes[attrNum];
2937                    //jw.comment("attr "+attr);
2938
Property prop = findProperty(attr);
2939
2940                    String JavaDoc qNameNameAttr = declareQName(prop.getNamespace(), prop.dtdName, null);
2941                    String JavaDoc typeQNameNameAttr;
2942                    //System.out.println("graphNode null for "+a.getType());
2943
SchemaRep schemaRep = new SchemaRep();
2944                    String JavaDoc xmlSchemaType = schemaRep.javaType2XMLSchemaTypeComplex(a.getType());
2945                    //System.out.println("xmlSchemaType="+xmlSchemaType);
2946
typeQNameNameAttr = declareQName(schemaRep.getNamespaceURI(schemaRep.prefixOf(xmlSchemaType)),
2947                            schemaRep.removePrefix(xmlSchemaType), null);
2948
2949                    String JavaDoc varNameAttr = "_"+prop.name;
2950                    if (!a.isScalar()) {
2951                        jw.beginIf(varNameAttr+" != null");
2952                    } else if (config.isOptionalScalars() && a.isScalar()) {
2953                        jw.beginIf(a.getScalarIsSet());
2954                    }
2955                    jw.write("startElement.addAttribute("+qNameNameAttr+", ");
2956                    jw.write(JavaUtil.typeToString(a.getType(), varNameAttr));
2957                    jw.writeEol(", \"CDATA\", ", typeQNameNameAttr, ")");
2958                    if (!a.isScalar() || (config.isOptionalScalars() && a.isScalar()))
2959                        jw.end();
2960                }
2961                jw.writeEol("return startElement");
2962                jw.indentLeft();
2963                jw.writecr("case 2:");
2964                jw.indentRight();
2965                jw.write("return new ", getRootClassName(), ".ThisCharacters(");
2966                if (isTypeQName(a.getType())) {
2967                    // see line 3118 or so
2968
jw.write(a.getType());
2969                } else if ("byte[]".equals(a.getType())) {
2970                    // Is this hexBinary or base64Binary?
2971
SchemaRep.EncodingStyle style = (SchemaRep.EncodingStyle) a.searchExtraData(SchemaRep.EncodingStyle.class);
2972                    if (style instanceof SchemaRep.HexBinary) {
2973                    } else if (style instanceof SchemaRep.Base64Binary) {
2974                        jw.write(getRootClassName(), ".encodeBase64BinaryString(");
2975                        jw.writeEol(varName, "))");
2976                    } else {
2977                        config.messageOut.println("Unknown encoding style for "+a.getType()+" for property "+a.name);
2978                    }
2979                } else {
2980                    jw.write(JavaUtil.typeToString(a.getType(), varName));
2981                    jw.writeEol(")");
2982                }
2983                jw.indentLeft();
2984                jw.writecr("case 3:");
2985                jw.indentRight();
2986                jw.write("return new ", getRootClassName(), ".ThisEndElement(", qNameName);
2987                jw.writeEol(")");
2988                jw.indentLeft();
2989                jw.writecr("default:");
2990                jw.indentRight();
2991                if (indexed) {
2992                    jw.writeEol("state.nextArrayIndex()");
2993                    jw.writeEol("return getXMLEvent(state)");
2994                } else {
2995                    jw.writeEol("break");
2996                }
2997                jw.indentLeft();
2998                jw.end();
2999                if (!a.isScalar() || (config.isOptionalScalars() && a.isScalar())) {
3000                    if (indexed) {
3001                        jw.endElse();
3002                        jw.cr();
3003                        jw.indentOneLevel();
3004                    } else {
3005                        jw.end();
3006                    }
3007                }
3008                jw.writeEol("state.nextEventNumber()");
3009                jw.writeEol("break");
3010                jw.end();
3011            }
3012            /*
3013            if (indexed) {
3014                jw.writeEol("state.nextEventNumber()");
3015                jw.writeEol("return getXMLEvent(state)");
3016                jw.end();
3017            }
3018             */

3019        }
3020
3021        jw.end();
3022        jw.writeEol("return null");
3023        jw.endMethod();
3024
3025    }
3026    
3027    /**
3028     * Declare the QNAME as a constant.
3029     * @return the name of the identifier choosen.
3030     */

3031    protected String JavaDoc declareQName(String JavaDoc namespaceUri, String JavaDoc localPart, String JavaDoc prefix) throws IOException {
3032        if ("http://www.w3.org/XML/1998/namespace".equals(namespaceUri)) {
3033            if (prefix == null)
3034                prefix = "xml";
3035            if (localPart.startsWith("xml:"))
3036                localPart = localPart.substring(4);
3037        }
3038        QName qname = new QName(namespaceUri, localPart, prefix);
3039        if (declaredQNames.containsKey(qname))
3040            return (String JavaDoc) declaredQNames.get(qname);
3041        jw.pushSelect(DECL_SECTION);
3042        if (declaredQNames.size() == 0)
3043            jw.cr();
3044        String JavaDoc qNameName = "QNAME_"+Common.constName(localPart);
3045        while (declaredQNames.containsKey(qNameName))
3046            qNameName = qNameName + "2";
3047        declaredQNames.put(qname, qNameName);
3048        //System.out.println("Declaring "+qNameName+" "+qname);
3049
jw.write("public static final javax.xml.namespace.QName ");
3050        jw.write(qNameName);
3051        jw.write(" = new javax.xml.namespace.QName(");
3052        if (namespaceUri == null)
3053            jw.write("null");
3054        else
3055            jw.write(JavaUtil.instanceFrom("String", namespaceUri));
3056        jw.write(", \"");
3057        jw.write(localPart);
3058        jw.write("\"");
3059        if (prefix != null)
3060            jw.write(", ", JavaUtil.instanceFrom("String", prefix));
3061        jw.writeEolNoI18N(")");
3062        jw.popSelect();
3063        return qNameName;
3064    }
3065
3066    protected void declareLogger() throws IOException {
3067        if (loggerDeclared)
3068            return;
3069        jw.pushSelect(DECL_SECTION);
3070        jw.writeEol("private static final java.util.logging.Logger _logger = java.util.logging.Logger.getLogger(\""+fullClassName+"\")");
3071        jw.popSelect();
3072        loggerDeclared = true;
3073    }
3074
3075    protected void genUpdateNamespaces(String JavaDoc namespaceMapName,
3076                                       String JavaDoc firstNamespaceVarName) throws IOException {
3077        jw.beginFor("int attrNum = 0", "attrNum < attrs.getLength()",
3078                    "++attrNum");
3079        jw.writeEol("attr = (org.w3c.dom.Attr) attrs.item(attrNum)");
3080        jw.writeEol("String attrName = attr.getName()");
3081        //jw.writeEol("System.out.println(\"attrName=\"+attrName)
3082
jw.beginIf("attrName.startsWith(\"xmlns:\")");
3083        if (firstNamespaceVarName != null) {
3084            jw.beginIf(firstNamespaceVarName);
3085            jw.writeEol(firstNamespaceVarName, " = false");
3086            jw.comment("Dup prefix map, so as to not write over previous values, and to make it easy to clear out our entries.");
3087            jw.write(namespaceMapName, " = new java.util.HashMap");
3088            if (config.jdkTarget >= 150)
3089                jw.write("<String, String>");
3090            jw.writeEol("(", namespaceMapName, ")");
3091            jw.end();
3092        }
3093        jw.writeEol("String attrNSPrefix = attrName.substring(6, attrName.length())");
3094        jw.writeEol(namespaceMapName, ".put(attrNSPrefix, attr.getValue())");
3095        jw.end();
3096        jw.end();
3097    }
3098
3099    protected void genWriteAttr(Property a) throws IOException {
3100        genWriteAttr(a, "_"+a.name);
3101    }
3102    
3103    protected void genWriteAttr(Property a, String JavaDoc varName) throws IOException {
3104        boolean isScalar = a.isScalar();
3105        String JavaDoc dtdName = a.dtdName;
3106        String JavaDoc namespace = a.getNamespace();
3107
3108        comment(dtdName+" is an attribute with namespace "+namespace);
3109        if (!isScalar) {
3110            gen("if ("+varName+" != null) ");
3111            begin();
3112        }
3113        if (namespace != null && !namespace.equals(getDefaultNamespace()) && !namespace.equals("http://www.w3.org/XML/1998/namespace")) {
3114            dtdName = SchemaRep.removePrefix(dtdName);
3115            outWrite(" ");
3116            jw.writeEol("out.write((String)namespaceMap.get(",
3117                     JavaUtil.instanceFrom("String", namespace),
3118                     "))");
3119            jw.writeEol("out.write(\":", dtdName, "='\")");
3120        } else {
3121            jw.writeEol("out.write(\" ", dtdName, "='\")");
3122        }
3123        genWriteType(a, varName, true);
3124        gen("out.write(\"'\")");
3125        eolNoI18N();
3126        if (!isScalar) {
3127            end();
3128        }
3129    }
3130
3131    protected void genWriteType(Property a, String JavaDoc varName,
3132                                boolean isAttribute) throws IOException {
3133        String JavaDoc type = a.getType();
3134        boolean isScalar = a.isScalar();
3135
3136        if (isScalar || JavaUtil.canProduceNoXMLMetaChars(type)) {
3137            jw.write("out.write("+JavaUtil.typeToString(type, varName));
3138            jw.writeEol(")");
3139        } else if (isTypeQName(type)) {
3140            jw.beginIf(varName+".getNamespaceURI() != null && !\"\".equals(",
3141                       varName, ".getNamespaceURI())");
3142            jw.writeEol("out.write((String) namespaceMap.get(", varName,
3143                        ".getNamespaceURI()))");
3144            jw.writeEol("out.write(\":\")");
3145            jw.end();
3146            if (config.isUseRuntime())
3147                jw.write("org.netbeans.modules.schema2beans.XMLUtil");
3148            else
3149                jw.write(getRootClassName());
3150            jw.write(".writeXML(out, ");
3151            jw.write(varName, ".getLocalPart(), "+isAttribute);
3152            jw.writeEol(")");
3153        } else if ("byte[]".equals(type)) {
3154            // Is this hexBinary or base64Binary?
3155
SchemaRep.EncodingStyle style = (SchemaRep.EncodingStyle) a.searchExtraData(SchemaRep.EncodingStyle.class);
3156            if (style instanceof SchemaRep.HexBinary) {
3157                jw.beginFor("int byteIndex = 0", "byteIndex < "+varName+".length",
3158                            "++byteIndex");
3159                jw.writeEol("int belement = (int) ", varName, "[byteIndex]");
3160                jw.beginIf("belement < 0");
3161                jw.writeEol("belement += 256");
3162                jw.end();
3163                jw.beginIf("belement < 16");
3164                jw.writeEol("out.write(\"0\")");
3165                jw.end();
3166                jw.writeEol("out.write(Integer.toHexString(belement).toUpperCase())");
3167                jw.end();
3168            } else if (style instanceof SchemaRep.Base64Binary) {
3169                jw.write("out.write(");
3170                jw.write(getRootClassName());
3171                jw.write(".encodeBase64BinaryString(");
3172                jw.write(varName);
3173                jw.write(")");
3174                jw.writeEol(")");
3175            } else {
3176                config.messageOut.println("Unknown encoding style for "+type+" for property "+a.name);
3177            }
3178        } else {
3179            if (config.isUseRuntime())
3180                jw.write("org.netbeans.modules.schema2beans.XMLUtil");
3181            else
3182                jw.write(getRootClassName());
3183            jw.write(".writeXML(out, ");
3184            if ("java.util.Calendar".equals(type)) {
3185                jw.write(getRootClassName());
3186                jw.write(".calendarToString(");
3187                jw.write(varName);
3188                jw.write(")");
3189            } else {
3190                jw.write(JavaUtil.typeToString(type, varName));
3191            }
3192            jw.write(", "+isAttribute);
3193            jw.writeEol(")");
3194        }
3195    }
3196
3197    protected void beginAttrProcessing(String JavaDoc nodeName) throws IOException {
3198        jw.beginIf(nodeName, ".hasAttributes()");
3199        declareAttrsForRead(nodeName);
3200    }
3201
3202    protected void genReadAttr(Property a, String JavaDoc nodeName) throws IOException {
3203        genReadAttr("_" + a.name, a.getType().intern(), a.dtdName, nodeName,
3204                    (SchemaRep.WhiteSpace) a.searchExtraData(SchemaRep.WhiteSpace.class),
3205                    a.isIndexed(), a.getAddMethod(), a.isScalar(),
3206                    (SchemaRep.EncodingStyle) a.searchExtraData(SchemaRep.EncodingStyle.class));
3207    }
3208
3209    protected void genReadAttr(String JavaDoc attr, String JavaDoc type, String JavaDoc dtdName,
3210                               String JavaDoc nodeName,
3211                               SchemaRep.WhiteSpace ws,
3212                               boolean isIndexed,
3213                               String JavaDoc addMethod, boolean isScalar,
3214                               SchemaRep.EncodingStyle style) throws IOException {
3215        String JavaDoc baseType = type;
3216        jw.writeEol("attr = (org.w3c.dom.Attr) attrs.getNamedItem(\"",
3217                    dtdName, "\")");
3218        List exceps = JavaUtil.exceptionsFromParsingText(baseType);
3219        String JavaDoc var = "attrValue";
3220        jw.beginIf("attr != null");
3221        jw.writeEol("attrValue = attr.getValue()");
3222        if (ws != null) {
3223            genWhiteSpaceRestriction(ws, var, "java.lang.String");
3224        }
3225        if (isIndexed) {
3226            jw.endElseBegin();
3227            jw.writeEol("attrValue = null");
3228            jw.end();
3229        }
3230        if (!exceps.isEmpty()) {
3231            jw.beginTry();
3232        }
3233        genReadType(baseType, attr, var, isIndexed, addMethod, isScalar, style);
3234        if (!exceps.isEmpty()) {
3235            jw.end();
3236            genRethrowExceptions(exceps);
3237        }
3238        if (!isIndexed)
3239            jw.end();
3240    }
3241
3242    /**
3243     * @return whether or not a setter was generated.
3244     */

3245    protected boolean genReadType(String JavaDoc type, String JavaDoc var, String JavaDoc expr,
3246                               boolean isIndexed, String JavaDoc addMethod,
3247                               boolean isScalar, SchemaRep.EncodingStyle style) throws IOException {
3248        type = type.intern();
3249        if (isIndexed) {
3250            jw.writeEol(type, " processedValueFor", var);
3251            if (genReadType(type, "processedValueFor"+var, expr, false, null,
3252                            isScalar, style)) {
3253                jw.writeEol(addMethod, "(processedValueFor", var, ")");
3254            }
3255        } else if (isTypeQName(type)) {
3256            jw.writeEol("int colonPos = ", expr, ".indexOf(':')");
3257            //jw.writeEol("System.out.println(\"colonPos=\"+colonPos+\" childNodeValue=\"+childNodeValue)");
3258
jw.beginIf("colonPos < 0");
3259            jw.write(var, " = new ", type);
3260            jw.writeEol("(", expr, ")");
3261            jw.endElseBegin();
3262            jw.writeEol("java.util.Map nsPrefixes = new java.util.HashMap(namespacePrefixes)");
3263            genUpdateNamespaces("nsPrefixes", null);
3264            jw.writeEol("String prefix = ", expr, ".substring(0, colonPos)");
3265            jw.writeEol("String ns = (String) nsPrefixes.get(prefix)");
3266            //jw.writeEol("System.out.println(\"prefix=\"+prefix+\" ns=\"+ns)");
3267
jw.write("String localPart = ", expr);
3268            jw.writeEol(".substring(colonPos+1, ", expr, ".length())");
3269            jw.writeEol(var, " = new ", type, "(ns, localPart, prefix)");
3270            jw.end();
3271        } else if (type == "byte[]") {
3272            // Is this hexBinary or base64Binary?
3273
if (style instanceof SchemaRep.HexBinary) {
3274                // example: 07FB
3275
jw.writeEol(var, " = new byte[(childNodeValue.length()+1) / 2]");
3276                jw.beginFor("int byteIndex = 0", "byteIndex < "+var+".length",
3277                            "++byteIndex");
3278                jw.writeEol("String octet = childNodeValue.substring(byteIndex * 2, byteIndex * 2 + 2)");
3279                jw.writeEol(var, "[byteIndex] = Integer.valueOf(octet, 16).byteValue()");
3280                jw.end();
3281            } else if (style instanceof SchemaRep.Base64Binary) {
3282                jw.write(var, " = ");
3283                jw.write(getRootClassName());
3284                jw.writeEol(".decodeBase64BinaryString(childNodeValue)");
3285            } else {
3286                config.messageOut.println("Unknown encoding style for "+type+" for "+var);
3287            }
3288        } else if ((!isScalar && !JavaUtil.isInstantiable(type)
3289                    && type != "java.util.Calendar") ||
3290                   type == "org.netbeans.modules.schema2beansdev.beangraph.BeanGraph" ||
3291                   type == "org.netbeans.modules.schema2beansdev.metadd.MetaDD" ||
3292                   type == "java.io.PrintStream") {
3293            config.messageOut.println("Warning: Don't know how to create a "+type);
3294            jw.comment("Don't know how to create a "+type);
3295            return false;
3296        } else {
3297            if (type == "java.util.Calendar") {
3298                jw.write(var, " = ");
3299                jw.write(getRootClassName());
3300                jw.writeEol(".stringToCalendar(", expr, ")");
3301            } else {
3302                jw.writecr(JavaUtil.genParseText(type, expr, var,
3303                                                 config.isForME()));
3304            }
3305        }
3306        return true;
3307    }
3308
3309    protected void declareAttrsForRead(String JavaDoc nodeName) throws IOException {
3310        jw.writeEol("org.w3c.dom.NamedNodeMap attrs = ", nodeName, ".getAttributes()");
3311        jw.writeEol("org.w3c.dom.Attr attr");
3312        jw.writeEol("java.lang.String attrValue");
3313    }
3314
3315    public void genPrintXML() throws IOException {
3316        jw.bigComment("Takes some text to be printed into an XML stream and escapes any\ncharacters that might make it invalid XML (like '<').");
3317        jw.beginMethod("writeXML", "java.io.Writer out, String msg", "java.io.IOException", "void", jw.PUBLIC | jw.STATIC | jw.IO);
3318        geneol("writeXML(out, msg, true)");
3319        end();
3320        cr();
3321        jw.beginMethod("writeXML", "java.io.Writer out, String msg, boolean attribute", "java.io.IOException", "void", jw.PUBLIC | jw.STATIC | jw.IO);
3322        gencr("if (msg == null)");
3323        tabIn();
3324        geneol("return");
3325        geneol("int msgLength = msg.length()");
3326        jw.beginFor("int i = 0", "i < msgLength", "++i");
3327        geneol("char c = msg.charAt(i)");
3328        geneol("writeXML(out, c, attribute)");
3329        end();
3330        end();
3331        cr();
3332        jw.beginMethod("writeXML", "java.io.Writer out, char msg, boolean attribute", "java.io.IOException", "void", jw.PUBLIC | jw.STATIC | jw.IO);
3333        gencr("if (msg == '&')");
3334        tabIn();
3335        geneol("out.write(\"&amp;\")");
3336        gencr("else if (msg == '<')");
3337        tabIn();
3338        geneol("out.write(\"&lt;\")");
3339        gencr("else if (msg == '>')");
3340        tabIn();
3341        geneol("out.write(\"&gt;\")");
3342        gen("else ");
3343        jw.beginIf("attribute");
3344        gencr("if (msg == '\"')");
3345        tabIn();
3346        geneol("out.write(\"&quot;\")");
3347        gencr("else if (msg == '\\'')");
3348        tabIn();
3349        geneol("out.write(\"&apos;\")");
3350        gencr("else if (msg == '\\n')");
3351        tabIn();
3352        geneol("out.write(\"&#xA;\")");
3353        gencr("else if (msg == '\\t')");
3354        tabIn();
3355        geneol("out.write(\"&#x9;\")");
3356        gencr("else");
3357        tabIn();
3358        geneol("out.write(msg)");
3359        jw.end();
3360        gencr("else");
3361        tabIn();
3362        geneol("out.write(msg)");
3363        jw.endMethod();
3364    }
3365
3366    protected void outWrite(String JavaDoc text) throws IOException {
3367        jw.writeEol("out.write(",
3368                    JavaUtil.instanceFrom("String", text),
3369                    ")");
3370    }
3371
3372    /**
3373     * Generate stuff for special types as needed.
3374     */

3375    public void genSpecialTypes() throws IOException {
3376        if (rootBeanElement.isUsedType("java.util.Calendar")) {
3377            JavaBeansUtil.genReadType(jw, "java.util.Calendar");
3378            JavaBeansUtil.genWriteType(jw, "java.util.Calendar");
3379            jw.cr();
3380        }
3381        if (rootBeanElement.isUsedType("byte[]")) {
3382            JavaBeansUtil.genReadType(jw, "base64Binary");
3383            JavaBeansUtil.genWriteType(jw, "base64Binary");
3384            jw.cr();
3385        }
3386    }
3387
3388    public void genValidate() throws IOException {
3389        select(BODY_SECTION);
3390        if (beanElement.isRoot && !config.isUseRuntime()) {
3391            String JavaDoc commonBeanType = commonBeanType();
3392            jw.write("public static class ValidateException extends Exception ");
3393            jw.begin();
3394            jw.write("private ", commonBeanType);
3395            jw.writeEol(" failedBean");
3396            jw.writeEol("private String failedPropertyName");
3397            jw.writeEol("private FailureType failureType");
3398            jw.write("public ValidateException(String msg, String failedPropertyName, ", commonBeanType, " failedBean) ");
3399            jw.begin();
3400            jw.writeEol("super(msg)");
3401            jw.writeEol("this.failedBean = failedBean");
3402            jw.writeEol("this.failedPropertyName = failedPropertyName");
3403            jw.end();
3404            jw.write("public ValidateException(String msg, FailureType ft, String failedPropertyName, ", commonBeanType, " failedBean) ");
3405            jw.begin();
3406            jw.writeEol("super(msg)");
3407            jw.writeEol("this.failureType = ft");
3408            jw.writeEol("this.failedBean = failedBean");
3409            jw.writeEol("this.failedPropertyName = failedPropertyName");
3410            jw.end();
3411            jw.writecr("public String getFailedPropertyName() {return failedPropertyName;}");
3412            jw.writecr("public FailureType getFailureType() {return failureType;}");
3413            jw.write("public ", commonBeanType);
3414            jw.writecr(" getFailedBean() {return failedBean;}");
3415            jw.write("public static class FailureType ");
3416            jw.begin();
3417            jw.writeEol("private final String name");
3418            jw.writecr("private FailureType(String name) {this.name = name;}");
3419            jw.writecr("public String toString() { return name;}");
3420            jw.writeEol("public static final FailureType NULL_VALUE = new FailureType(\"NULL_VALUE\")");
3421            jw.writeEol("public static final FailureType DATA_RESTRICTION = new FailureType(\"DATA_RESTRICTION\")");
3422            jw.writeEol("public static final FailureType ENUM_RESTRICTION = new FailureType(\"ENUM_RESTRICTION\")");
3423            jw.writeEol("public static final FailureType ALL_RESTRICTIONS = new FailureType(\"ALL_RESTRICTIONS\")");
3424            jw.writeEol("public static final FailureType MUTUALLY_EXCLUSIVE = new FailureType(\"MUTUALLY_EXCLUSIVE\")");
3425            jw.end();
3426            jw.end();
3427            jw.cr();
3428        }
3429        jw.beginMethod("validate", "", (config.isUseRuntime() ? "org.netbeans.modules.schema2beans" : getRootClassName())+".ValidateException", "void", jw.PUBLIC);
3430        genValidateProperties();
3431        if (config.isRespectExtension() && beanElement.getExtension() != null) {
3432            jw.writeEol("super.validate()");
3433        }
3434        jw.endMethod();
3435    }
3436
3437    protected void genValidateFail(String JavaDoc detail, String JavaDoc name,
3438                                   boolean quoteDetail,
3439                                   ValidateException.FailureType ft,
3440                                   JavaWriter out) throws IOException {
3441        out.write("throw new ");
3442        String JavaDoc validateException;
3443        if (config.isUseRuntime())
3444            validateException = "org.netbeans.modules.schema2beans.ValidateException";
3445        else
3446            validateException = getRootClassName()+".ValidateException";
3447        out.write(validateException);
3448        out.write("(");
3449        if (quoteDetail)
3450            out.write('"');
3451        out.write(detail);
3452        if (quoteDetail)
3453            out.write('"');
3454        out.write(", ", validateException+".FailureType.",
3455                 ft.toString());
3456        out.writeEolNoI18N(", \""+name+"\", this)");
3457    }
3458
3459    public void genPropertyEvents() throws IOException {
3460        select(DECL_SECTION);
3461        gen(PRIVATE, "java.beans.PropertyChangeSupport", "eventListeners");
3462        eol();
3463        select(BODY_SECTION);
3464        jw.beginMethod("addPropertyChangeListener",
3465                       "java.beans.PropertyChangeListener listener", null,
3466                       "void", jw.PUBLIC | jw.BEANINFO);
3467        jw.beginIf("eventListeners == null");
3468        geneol("eventListeners = new java.beans.PropertyChangeSupport(this)");
3469        end();
3470        geneol("eventListeners.addPropertyChangeListener(listener)");
3471        genCallMethodOnBeans(".addPropertyChangeListener(listener)");
3472        jw.endMethod();
3473
3474        jw.beginMethod("removePropertyChangeListener",
3475                       "java.beans.PropertyChangeListener listener", null,
3476                       "void", jw.PUBLIC | jw.BEANINFO);
3477        genCallMethodOnBeans(".removePropertyChangeListener(listener)");
3478        jw.beginIf("eventListeners == null");
3479        geneol("return");
3480        end();
3481        geneol("eventListeners.removePropertyChangeListener(listener)");
3482        jw.beginIf("!eventListeners.hasListeners(null)");
3483        geneol("eventListeners = null");
3484        jw.end();
3485        jw.endMethod();
3486
3487        jw.beginMethod("_setPropertyChangeSupport",
3488                       "java.beans.PropertyChangeSupport listeners", null,
3489                       "void", jw.PUBLIC);
3490        jw.writeEol("eventListeners = listeners");
3491        genCallMethodOnBeans("._setPropertyChangeSupport(listeners)");
3492        jw.endMethod();
3493    }
3494
3495    protected void genCallMethodOnBeans(String JavaDoc methodParams) throws IOException {
3496        int size = attrList.size();
3497        for (int i = 0; i < size; i++) {
3498            Property a = (Property) attrList.get(i);
3499            if (!a.isBean)
3500                continue;
3501            boolean indexed = a.isIndexed();
3502            String JavaDoc attr = "_" + a.name;
3503            String JavaDoc type = a.getType().intern();
3504            String JavaDoc baseType = type;
3505            if (indexed) {
3506                beginAttrIterator(attr, a, "element");
3507                attr = "element";
3508            }
3509            jw.beginIf(attr, " != null");
3510            jw.writeEol(attr, methodParams);
3511            jw.end();
3512            if (indexed)
3513                jw.end();
3514        }
3515    }
3516
3517    public void genStoreEvents() throws IOException {
3518        select(DECL_SECTION);
3519        gen(PROTECTED, "boolean", "storeEvents = false");
3520        eol();
3521        gen(PRIVATE, "java.util.List", "storedEvents = new java.util.LinkedList()");
3522        eol();
3523        select(BODY_SECTION);
3524        jw.beginMethod("fireStoredEvents");
3525        jw.beginIf("eventListeners == null");
3526        geneol("storedEvents.clear()");
3527        geneol("return");
3528        end();
3529        /*
3530        comment("Compress the events");
3531        geneol("java.util.Map uniqueEvents = new java.util.HashMap(storedEvents.size()*4)");
3532        gen("for (java.util.Iterator it = storedEvents.iterator(); it.hasNext(); ) ");
3533        begin();
3534        geneol("java.beans.PropertyChangeEvent event = (java.beans.PropertyChangeEvent) it.next()");
3535        comment("The last event by the property name is stored in uniqueEvents");
3536        gencr("if (uniqueEvents.containsKey(event.getPropertyName())");
3537        tabIn();
3538        geneol("uniqueEvents.put(event.getPropertyName(), event)");
3539        end();
3540        */

3541        jw.beginFor("java.util.Iterator it = storedEvents.iterator()",
3542                    "it.hasNext()", "");
3543        geneol("java.beans.PropertyChangeEvent event = (java.beans.PropertyChangeEvent) it.next()");
3544        /*gencr("if (uniqueEvents.get(event.getPropertyName()) == event)");
3545          tabIn();*/

3546        geneol("eventListeners.firePropertyChange(event)");
3547        end();
3548        geneol("storedEvents.clear()");
3549        end();
3550        cr();
3551    }
3552
3553    public void genVetoable() throws IOException {
3554        select(DECL_SECTION);
3555        gen(PRIVATE, "java.beans.VetoableChangeSupport", "vetos");
3556        eol();
3557        select(BODY_SECTION);
3558        jw.beginMethod("addVetoableChangeListener",
3559                       "java.beans.VetoableChangeListener listener", null,
3560                       "void", jw.PUBLIC | jw.BEANINFO);
3561        jw.beginIf("vetos == null");
3562        geneol("vetos = new java.beans.VetoableChangeSupport(this)");
3563        end();
3564        geneol("vetos.addVetoableChangeListener(listener)");
3565        end();
3566        cr();
3567        jw.beginMethod("removePropertyChangeListener",
3568                       "java.beans.VetoableChangeListener listener", null,
3569                       "void", jw.PUBLIC | jw.BEANINFO);
3570        jw.beginIf("vetos == null");
3571        geneol("return");
3572        end();
3573        geneol("vetos.removeVetoableChangeListener(listener)");
3574        jw.beginIf("!vetos.hasListeners(null)");
3575        geneol("vetos = null");
3576        end();
3577        end();
3578        cr();
3579        jw.beginMethod("_setVetoableChangeSupport",
3580                       "java.beans.VetoableChangeSupport vs", "void", null,
3581                       jw.PACKAGE_LEVEL);
3582        geneol("vetos = vs");
3583        end();
3584        cr();
3585    }
3586
3587    public void genElementPositions() throws IOException {
3588        select(BODY_SECTION);
3589        jw.beginMethod("fetchChildByPosition", "int position", null,
3590                       "java.lang.Object", jw.PUBLIC);
3591        jw.beginIf("elementTypesByPosition[position] == "+elementTypeSetnull);
3592        jw.writeEol("throw new IndexOutOfBoundsException(\"position \"+position+\" out of bounds\")");
3593        jw.end();
3594        jw.writeEol("return elementsByPosition[position]");
3595        jw.endMethod();
3596        jw.beginMethod("fetchChildCount", "", null, "int", jw.PUBLIC);
3597        jw.writeEol("int position = elementTypesByPosition.length");
3598        jw.beginFor("", "position > 0 && elementTypesByPosition[position-1] == "+elementTypeSetnull, "--position");
3599        jw.writeEol("");
3600        jw.end();
3601        jw.writeEol("return position");
3602        jw.endMethod();
3603        jw.beginMethod("expandElementsByPosition", "int size", null, "void",
3604                       jw.PROTECTED);
3605        jw.beginIf("elementTypesByPosition.length >= size");
3606        jw.writeEol("return");
3607        jw.end();
3608        jw.writeEol("int newSize = elementTypesByPosition.length+8");
3609        jw.writeEol("java.lang.Object[] newElementsByPosition = new java.lang.Object[newSize]");
3610        jw.writeEol("int[] newElementTypesByPosition = new int[newSize]");
3611        jw.writeEol("System.arraycopy(elementsByPosition, 0, newElementsByPosition, 0, elementTypesByPosition.length)");
3612        jw.writeEol("System.arraycopy(elementTypesByPosition, 0, newElementTypesByPosition, 0, elementTypesByPosition.length)");
3613        jw.beginFor("int i = elementTypesByPosition.length",
3614                    "i < newSize", "++i");
3615        jw.writeEol("newElementTypesByPosition[i] = "+elementTypeSetnull);
3616        jw.end();
3617        jw.writeEol("elementTypesByPosition = newElementTypesByPosition");
3618        jw.writeEol("elementsByPosition = newElementsByPosition");
3619        jw.endMethod();
3620
3621        jw.beginMethod("insertElementByPosition",
3622                       "int position, Object element, int elementType",
3623                       null, "void",
3624                       jw.PROTECTED);
3625        jw.writeEol("int childCount = fetchChildCount()");
3626        jw.writeEol("expandElementsByPosition(childCount+1)");
3627        jw.writeEol("int i = childCount - 1");
3628        jw.beginFor("", "i >= position", "--i");
3629        jw.writeEol("elementsByPosition[i + 1] = elementsByPosition[i]");
3630        jw.writeEol("elementTypesByPosition[i + 1] = elementTypesByPosition[i]");
3631        jw.end();
3632        jw.writeEol("elementTypesByPosition[position] = elementType");
3633        jw.writeEol("elementsByPosition[position] = element");
3634        jw.comment("assert childCount == fetchChildCount() + 1;");
3635        jw.endMethod();
3636
3637        jw.beginMethod("deleteElement", "int position", null, "void",
3638                       jw.PROTECTED);
3639        jw.writeEol("int i = position+1");
3640        jw.writeEol("int size = elementTypesByPosition.length");
3641        jw.beginFor("", "i < size && elementTypesByPosition[i] != "+elementTypeSetnull, "++i");
3642        jw.writeEol("elementsByPosition[i - 1] = elementsByPosition[i]");
3643        jw.writeEol("elementTypesByPosition[i - 1] = elementTypesByPosition[i]");
3644        //jw.writeEol("System.out.println(\"elementTypesByPosition[\"+(i-1)+\"]=\"+elementTypesByPosition[i-1])");
3645
jw.end();
3646        jw.writeEol("elementTypesByPosition[i-1] = "+elementTypeSetnull);
3647        jw.writeEol("elementsByPosition[i - 1] = null");
3648        jw.comment("assert size == fetchChildCount() - 1;");
3649        jw.endMethod();
3650
3651        jw.beginMethod("findFirstOfElementType", "int elementType", null,
3652                       "int", jw.PROTECTED);
3653        jw.writeEol("int maxPos = elementTypesByPosition.length");
3654        jw.writeEol("int pos = 0");
3655        jw.beginFor("", "pos < maxPos && elementTypesByPosition[pos] < elementType",
3656                    "++pos");
3657        jw.end();
3658        jw.writeEol("return pos");
3659        jw.endMethod();
3660
3661        jw.beginMethod("findElementType", "int elementType, int index", null,
3662                       "int", jw.PROTECTED);
3663        jw.writeEol("int maxPos = elementTypesByPosition.length");
3664        jw.writeEol("int pos = 0");
3665        jw.beginFor("", "pos < maxPos", "++pos");
3666        jw.beginIf("elementTypesByPosition[pos] == elementType");
3667        jw.beginIf("index <= 0");
3668        jw.writeEol("return pos");
3669        jw.end();
3670        jw.writeEol("--index");
3671        jw.end();
3672        jw.end();
3673        jw.writeEol("return pos");
3674        jw.endMethod();
3675
3676        jw.beginMethod("findLastOfElementType", "int elementType", null, "int",
3677                       jw.PROTECTED);
3678        jw.writeEol("int childCount = elementTypesByPosition.length");
3679        jw.writeEol("int pos = childCount - 1");
3680        // We can't do a binary search here, since the element types are
3681
// not always sorted.
3682
jw.beginFor("", "pos >=0", "--pos");
3683        jw.beginIf("elementTypesByPosition[pos] == "+elementTypeSetnull);
3684        jw.writeEol("--childCount");
3685        jw.writeEol("continue");
3686        jw.end();
3687        jw.beginIf("elementTypesByPosition[pos] <= elementType");
3688        jw.writeEol("return pos");
3689        jw.end();
3690        jw.end();
3691        //jw.beginIf("childCount < 0");
3692
//jw.writeEol("return 0");
3693
//jw.end();
3694
jw.writeEol("return childCount");
3695        jw.endMethod();
3696    }
3697
3698    protected void genProcessDocType() throws IOException {
3699        String JavaDoc fullDocTypeName;
3700        fullDocTypeName = fullClassName+".DocType";
3701        select(DECL_SECTION);
3702        jw.writeEol("private "+fullDocTypeName+" docType = null");
3703        select(ACCESS_SECTION);
3704        jw.beginMethod("fetchDocType", "", null, fullDocTypeName, jw.PUBLIC);
3705        jw.writeEol("return docType");
3706        jw.endMethod();
3707        jw.beginMethod("changeDocType", fullDocTypeName+" dt", null, "void", jw.PUBLIC);
3708        jw.writeEol("docType = dt");
3709        jw.endMethod();
3710        jw.beginMethod("changeDocType", "String publicId, String systemId", null, "void", jw.PUBLIC);
3711        jw.writeEol("docType = new ", fullDocTypeName, "(publicId, systemId)");
3712        jw.endMethod();
3713        select(BODY_SECTION);
3714        jw.write("public static class DocType ");
3715        jw.begin();
3716        jw.writeEol("private org.w3c.dom.NamedNodeMap entities");
3717        jw.writeEol("private String internalSubset");
3718        jw.writeEol("private String name");
3719        jw.writeEol("private org.w3c.dom.NamedNodeMap notations");
3720        jw.writeEol("private String publicId");
3721        jw.writeEol("private String systemId");
3722        jw.cr();
3723        jw.write("public DocType("+fullDocTypeName+" docType) ");
3724        jw.begin();
3725        jw.writeEol("entities = docType.getEntities()");
3726        jw.writeEol("internalSubset = docType.getInternalSubset()");
3727        jw.writeEol("name = docType.getName()");
3728        jw.writeEol("notations = docType.getNotations()");
3729        jw.writeEol("publicId = docType.getPublicId()");
3730        jw.writeEol("systemId = docType.getSystemId()");
3731        jw.endMethod();
3732        jw.write("public DocType(org.w3c.dom.DocumentType docType) ");
3733        jw.begin();
3734        jw.writeEol("entities = docType.getEntities()");
3735        jw.writeEol("internalSubset = docType.getInternalSubset()");
3736        jw.writeEol("name = docType.getName()");
3737        jw.writeEol("notations = docType.getNotations()");
3738        jw.writeEol("publicId = docType.getPublicId()");
3739        jw.writeEol("systemId = docType.getSystemId()");
3740        jw.endMethod();
3741        jw.write("public DocType(String publicId, String systemId) ");
3742        jw.begin();
3743        jw.writeEol("this(\"",
3744                    beanElement.node.getName(), "\", publicId, systemId)");
3745        jw.end();
3746        jw.cr();
3747        jw.write("public DocType(String name, String publicId, String systemId) ");
3748        jw.begin();
3749        jw.writeEol("this.name = name");
3750        jw.writeEol("this.publicId = publicId");
3751        jw.writeEol("this.systemId = systemId");
3752        jw.endMethod();
3753        jw.write("public org.w3c.dom.NamedNodeMap getEntities() ");
3754        jw.begin();
3755        jw.writeEol("return entities");
3756        jw.endMethod();
3757        jw.write("public String getInternalSubset() ");
3758        jw.begin();
3759        jw.writeEol("return internalSubset");
3760        jw.endMethod();
3761        jw.write("public String getName() ");
3762        jw.begin();
3763        jw.writeEol("return name");
3764        jw.endMethod();
3765        jw.write("public org.w3c.dom.NamedNodeMap getNotations() ");
3766        jw.begin();
3767        jw.writeEol("return notations");
3768        jw.endMethod();
3769        jw.write("public String getPublicId() ");
3770        jw.begin();
3771        jw.writeEol("return publicId");
3772        jw.endMethod();
3773        jw.write("public String getSystemId() ");
3774        jw.begin();
3775        jw.writeEol("return systemId");
3776        jw.endMethod();
3777        jw.write("public String toString() ");
3778        jw.begin();
3779        jw.writeEol("String result = \"<!DOCTYPE \"");
3780        jw.writeEol("result += name");
3781        jw.beginIf("publicId != null");
3782        jw.writeEol("result += \" PUBLIC \\\"\"");
3783        jw.writeEol("result += publicId"); // should be printXML
3784
jw.writeEol("result += \"\\\"\"");
3785        jw.beginIf("systemId == null");
3786        jw.writeEol("systemId = \"SYSTEM\"");
3787        jw.end();
3788        jw.end();
3789        jw.beginIf("systemId != null");
3790        jw.writeEol("result += \" \\\"\"");
3791        jw.writeEol("result += systemId");
3792        jw.writeEol("result += \"\\\"\"");
3793        jw.end();
3794        jw.beginIf("entities != null");
3795        jw.writeEol("int length = entities.getLength()");
3796        jw.beginIf("length > 0");
3797        jw.writeEol("result += \" [\"");
3798        jw.beginFor("int i = 0", "i < length", "++i");
3799        jw.writeEol("org.w3c.dom.Node node = entities.item(i)");
3800        jw.writeEol("result += \"<\"+node.getNodeName()+\">\"");
3801        jw.writeEol("result += node.getNodeValue()");
3802        jw.writeEol("result += \"</\"+node.getNodeName()+\">\"");
3803        jw.end();
3804        jw.writeEol("result += \"]\"");
3805        jw.end();
3806        jw.end();
3807        jw.writeEol("result += \">\"");
3808        jw.writeEol("return result");
3809        jw.end();
3810
3811        jw.endMethod();
3812    }
3813
3814    public void genTransactions() throws IOException {
3815        select(BODY_SECTION);
3816        jw.beginMethod("beginTransaction");
3817        //geneol("inTransaction = true");
3818
geneol("storeEvents = true");
3819        comment("Tell each child bean to also beginTransaction");
3820        genCallMethodOnSubBeans("beginTransaction()");
3821        end();
3822        cr();
3823
3824        jw.beginMethod("commit");
3825        geneol("storeEvents = false");
3826        comment("Tell each child bean to also commit");
3827        genCallMethodOnSubBeans("commit()");
3828        geneol("fireStoredEvents()");
3829        end();
3830        cr();
3831
3832        jw.beginMethod("rollback");
3833        comment("Go over all of the events and put them back");
3834        geneol("java.beans.PropertyChangeEvent[] events = new java.beans.PropertyChangeEvent[storedEvents.size()]");
3835        jw.beginFor("int i = events.length-1", "i >= 0", "--i");
3836        geneol("java.beans.PropertyChangeEvent event = events[i]");
3837        //jw.beginIf("event.getOldValue() == null");
3838
geneol("changePropertyByName(event.getPropertyName(), event.getOldValue())");
3839        end();
3840        // we might be able to speed things up by setting eventListeners = null
3841
geneol("storeEvents = false");
3842        geneol("storedEvents.clear()");
3843        comment("Tell each child bean to also rollback");
3844        genCallMethodOnSubBeans("rollback()");
3845        end();
3846        cr();
3847    }
3848
3849    protected void genCallMethodOnSubBeans(String JavaDoc methodName) throws IOException {
3850        int size = attrList.size();
3851        for (int i = 0; i < size; i++) {
3852            Property a = (Property)attrList.get(i);
3853            boolean indexed = a.isIndexed();
3854            String JavaDoc attr = "_" + a.name;
3855            String JavaDoc type = a.getType();
3856            if (a.isBean) {
3857                String JavaDoc value = attr;
3858                if (indexed) {
3859                    beginAttrIterator(attr, a, "element");
3860                    value = "element";
3861                }
3862                gencr("if ("+value+" != null)");
3863                tabIn();
3864                gen(value);
3865                gen(".");
3866                geneol(methodName);
3867                if (indexed)
3868                    end();
3869            }
3870        }
3871    }
3872
3873    public void genPropertiesByName() throws IOException {
3874        jw.beginMethod("changePropertyByName", "String name, Object value",
3875                       null, "void", jw.PUBLIC);
3876        geneol("if (name == null) return");
3877        geneol("name = name.intern()");
3878        int size = attrList.size();
3879        for (int i = 0; i < size; i++) {
3880            Property a = (Property)attrList.get(i);
3881            boolean indexed = a.isIndexed();
3882            boolean isScalar = a.isScalar();
3883            String JavaDoc attr = "_" + a.name;
3884            String JavaDoc type = a.getType();
3885            if (i > 0)
3886                gen("else ");
3887            gencr("if (name == \""+a.beanIntrospectorName()+"\")");
3888            tabIn();
3889            if (indexed) {
3890                gen("add"+a.name);
3891                geneol("("+JavaUtil.fromObject(type, "value")+")");
3892                gen("else ");
3893                gencr("if (name == \""+a.beanIntrospectorName()+"[]\")");
3894                tabIn();
3895                gen(a.getWriteMethod()+"(");
3896                geneol("("+type+"[]) value)");
3897            } else {
3898                gen(a.getWriteMethod()+"(");
3899                gen(JavaUtil.fromObject(type, "value"));
3900                geneol(")");
3901            }
3902        }
3903        if (size > 0) {
3904            gencr("else");
3905            tabIn();
3906            if (config.isRespectExtension() && beanElement.getExtension() != null) {
3907                jw.writeEol("super.changePropertyByName(name, value)");
3908            } else {
3909                genInvalidName("name");
3910            }
3911        }
3912        genMadeChange();
3913        end();
3914        cr();
3915
3916        jw.beginMethod("fetchPropertyByName", "String name", null, "Object", jw.PUBLIC);
3917        for (int i = 0; i < size; i++) {
3918            Property a = (Property)attrList.get(i);
3919            boolean indexed = a.isIndexed();
3920            String JavaDoc type = a.getType();
3921            gen("if (name == \""+a.beanIntrospectorName());
3922            if (indexed)
3923                gen("[]");
3924            gencr("\")");
3925            tabIn();
3926            jw.write("return ");
3927            if (indexed)
3928                jw.writeEol(a.getReadMethod(false)+"()");
3929            else
3930                jw.writeEol(JavaUtil.toObject(a.getReadMethod(false)+"()", type,
3931                                              config.isForME()));
3932        }
3933        if (config.isRespectExtension() && beanElement.getExtension() != null) {
3934            jw.writeEol("return super.fetchPropertyByName(name)");
3935        } else {
3936            genInvalidName("name");
3937        }
3938        jw.endMethod();
3939    }
3940
3941    public void genEqualsHashCode() throws IOException {
3942        select(EQUALS_SECTION);
3943        jw.beginMethod("equals", "Object o", null, "boolean", jw.PUBLIC);
3944        jw.write("return o instanceof ", fullClassName);
3945        jw.writeEol(" && equals((", fullClassName, ") o)");
3946        jw.endMethod();
3947        
3948        jw.beginMethod("equals", fullClassName+" inst", null, "boolean", jw.PUBLIC);
3949        jw.beginIf("inst == this");
3950        jw.writeEol("return true");
3951        jw.end();
3952        jw.beginIf("inst == null");
3953        jw.writeEol("return false");
3954        jw.end();
3955        
3956        select(HASHCODE_SECTION);
3957        jw.beginMethod("hashCode", "", null, "int", jw.PUBLIC);
3958        geneol("int result = 17");
3959
3960        boolean isArrayStyle = (config.getIndexedPropertyType() == null);
3961        int size = attrList.size();
3962        for (int i = 0; i < size; i++) {
3963            Property a = (Property)attrList.get(i);
3964            boolean indexed = a.isIndexed();
3965            boolean isWrapper = false;
3966            MetaElement me = getMetaElement(a);
3967            boolean isScalar = a.isScalar();
3968
3969            String JavaDoc type = a.getType().intern();
3970            String JavaDoc baseType = type;
3971            if (indexed)
3972                type = (baseType + "[]").intern();
3973
3974            String JavaDoc attr = "_" + a.name;
3975            String JavaDoc baseAttr = attr;
3976            String JavaDoc otherAttr = "inst."+attr;
3977            select(EQUALS_SECTION);
3978            if (indexed) {
3979                gen("if (size"+a.name+"() != inst.size"+a.name+"())");
3980                cr();
3981                tabIn();
3982                gen("return false");
3983                eol();
3984                comment("Compare every element.");
3985                String JavaDoc fullType = getTypeFullClassName(a);
3986                if (isArrayStyle) {
3987                    jw.beginFor("int pos = 0, size = size"+a.name+"()",
3988                                "pos < size", "++pos");
3989                    attr = attr+"[pos]";
3990                    otherAttr = otherAttr+"[pos]";
3991                } else {
3992                    jw.beginFor("java.util.Iterator it = "+attr+".iterator(), it2 = inst."+attr+".iterator()",
3993                                "it.hasNext() && it2.hasNext()", "");
3994                    gen(fullType);
3995                    gen(" element = ");
3996                    geneol(JavaUtil.fromObject(fullType, "it.next()"));
3997                    gen(fullType);
3998                    gen(" element2 = ");
3999                    geneol(JavaUtil.fromObject(fullType, "it2.next()"));
4000                    attr = "element";
4001                    otherAttr = "element2";
4002                }
4003            }
4004            if (!indexed && config.isOptionalScalars() && a.isScalar()) {
4005                jw.beginIf(a.getScalarIsSet()+" != inst."+a.getScalarIsSet());
4006                jw.writeEol("return false");
4007                jw.end();
4008                jw.beginIf(a.getScalarIsSet());
4009            }
4010            jw.beginIf("!("+JavaUtil.genEquals(baseType, attr, otherAttr)+")");
4011            jw.writeEol("return false");
4012            jw.end();
4013            if (!indexed && config.isOptionalScalars() && a.isScalar()) {
4014                jw.end();
4015            }
4016            if (indexed) {
4017                end();
4018            }
4019
4020            select(HASHCODE_SECTION);
4021            gen("result = 37*result + (");
4022            if (isScalar) {
4023                if (!indexed && config.isOptionalScalars() && a.isScalar())
4024                    gen(a.getScalarIsSet(), " ? 0 : (");
4025                gen(JavaUtil.exprToInt(type, baseAttr));
4026                if (!indexed && config.isOptionalScalars() && a.isScalar())
4027                    gen(")");
4028            } else
4029                gen(baseAttr+" == null ? 0 : "+baseAttr+".hashCode()");
4030            gen(")");
4031            eol();
4032        }
4033        select(EQUALS_SECTION);
4034        if (config.isRespectExtension() && beanElement.getExtension() != null) {
4035            jw.writeEol("return super.equals(inst)");
4036        } else {
4037            jw.writeEol("return true");
4038        }
4039        jw.endMethod();
4040
4041        select(HASHCODE_SECTION);
4042        if (config.isRespectExtension() && beanElement.getExtension() != null) {
4043            jw.writeEol("result = 37*result + super.hashCode()");
4044        }
4045        jw.writeEol("return result");
4046        jw.endMethod();
4047    }
4048
4049    void genDeepCopy() throws IOException {
4050        select(CONSTRUCTOR_SECTION);
4051        jw.bigComment("Deep copy");
4052        jw.beginConstructor(className, fullClassName+" source");
4053        jw.writeEol("this(source, false)");
4054        jw.end();
4055        jw.cr();
4056        jw.bigComment("Deep copy\n@param justData just copy the XML relevant data");
4057        jw.beginConstructor(className, fullClassName+" source, boolean justData");
4058        if (config.isGenerateParentRefs()) {
4059            jw.writeEol("this(source, null, justData)");
4060            jw.end();
4061            jw.cr();
4062            jw.bigComment("Deep copy");
4063            jw.beginConstructor(className, fullClassName+" source, "+parentBeanType()+" parent, boolean justData");
4064        }
4065        if (config.isRespectExtension() && beanElement.getExtension() != null) {
4066            if (config.isGenerateParentRefs()) {
4067                jw.writeEol("super(source, parent, justData)");
4068            } else {
4069                jw.writeEol("super(source, justData)");
4070            }
4071        }
4072        genExtendBaseBeanConstructor();
4073        //jw.writeEol("System.out.println(\"Deep copy for "+className+"\")");
4074
if (config.isGenerateParentRefs()) {
4075            jw.writeEol("this.parent = parent");
4076        }
4077        for (int i = 0, size = attrList.size(); i < size; i++) {
4078            Property a = (Property) attrList.get(i);
4079            boolean indexed = a.isIndexed();
4080            boolean isScalar = a.isScalar();
4081            String JavaDoc attr = "_" + a.name;
4082            String JavaDoc type = a.getType().intern();
4083            String JavaDoc fullClassType = getTypeFullClassName(a);
4084            boolean isArrayStyle = (config.getIndexedPropertyType() == null);
4085
4086            String JavaDoc nextElement = "it.next()";
4087            if (indexed) {
4088                if (isArrayStyle) {
4089                    jw.writeEol(attr, " = new ", fullClassType, "[source."+attr+".length]");
4090                    jw.beginFor("int index = 0",
4091                                "index < source."+attr+".length", "++index");
4092                    nextElement = "source."+attr+"[index]";
4093                } else {
4094                    jw.beginFor("java.util.Iterator it = source."+attr+".iterator()",
4095                                "it.hasNext()", "");
4096                }
4097            }
4098            //System.out.println("type="+type+" needToCallClone="+needToCallClone+" mutable="+mutable);
4099
String JavaDoc getter;
4100            if (indexed) {
4101                getter = "srcElement";
4102                if (isScalar) {
4103                    if (config.jdkTarget < 150) {
4104                        // It's already in object format, it would be silly to
4105
// convert back and forth.
4106
jw.write("Object");
4107                    } else {
4108                        jw.write(JavaUtil.toObjectType(fullClassType));
4109                    }
4110                    jw.write(" ", getter, " = ");
4111                    if (config.jdkTarget >= 150)
4112                        jw.write("("+JavaUtil.toObjectType(fullClassType)+") ");
4113                    jw.writeEol(nextElement);
4114                } else {
4115                    jw.writeEol(fullClassType+" ", getter," = ",
4116                                isArrayStyle ? nextElement : JavaUtil.fromObject(fullClassType, nextElement));
4117                }
4118            } else
4119                getter = "source." + attr;
4120
4121            if (type == "byte[]") {
4122                jw.writeEol("byte[] destElement"+attr, " = new byte[", getter, ".length]");
4123                jw.writeEol("System.arraycopy(", getter+", 0, destElement"+attr+", 0, ", getter, ".length)");
4124            }
4125            gen(attr);
4126            if (indexed) {
4127                if (isArrayStyle) {
4128                    jw.write("[index] = ");
4129                } else {
4130                    gen(".add(");
4131                }
4132            } else {
4133                gen(" = ");
4134            }
4135            if (type == "byte[]") {
4136                jw.write("destElement", attr);
4137            } else {
4138                genCopy(getter, a, "justData");
4139            }
4140            if (indexed && !isArrayStyle) {
4141                jw.write(")");
4142            }
4143            jw.eol();
4144            if (!indexed && config.isOptionalScalars() && a.isScalar()) {
4145                jw.writeEol(a.getScalarIsSet(), " = source.", a.getScalarIsSet());
4146            }
4147            if (indexed) {
4148                jw.end();
4149            }
4150        }
4151        if (beanElement.isRoot && config.isProcessDocType()) {
4152            String JavaDoc fullDocTypeName;
4153            if (packageName == null)
4154                fullDocTypeName = className+".DocType";
4155            else
4156                fullDocTypeName = packageName+"."+className+".DocType";
4157            jw.beginIf("source.docType != null");
4158            jw.writeEol("docType = new "+fullDocTypeName+"(source.docType)");
4159            jw.end();
4160        }
4161        if (beanElement.isRoot) {
4162            jw.writeEol("schemaLocation = source.schemaLocation");
4163        }
4164        boolean firstJustData = true;
4165        if (config.isGenerateStoreEvents()) {
4166            if (firstJustData) {
4167                firstJustData = false;
4168                jw.beginIf("!justData");
4169            }
4170            geneol("storeEvents = source.storeEvents");
4171        }
4172        if (config.isVetoable()) {
4173            if (firstJustData) {
4174                firstJustData = false;
4175                jw.beginIf("!justData");
4176            }
4177            geneol("vetos = source.vetos");
4178        }
4179        if (config.isGeneratePropertyEvents()) {
4180            if (firstJustData) {
4181                firstJustData = false;
4182                jw.beginIf("!justData");
4183            }
4184            jw.beginIf("source.eventListeners != null");
4185            jw.writeEol("eventListeners = new java.beans.PropertyChangeSupport(this)");
4186            jw.writeEol("java.beans.PropertyChangeListener[] theListeners = source.eventListeners.getPropertyChangeListeners()");
4187            jw.beginFor("int i = 0", "i < theListeners.length", "++i");
4188            jw.writeEol("eventListeners.addPropertyChangeListener(theListeners[i])");
4189            jw.end();
4190            jw.end();
4191        }
4192        if (!firstJustData)
4193            jw.end();
4194        end();
4195        cr();
4196    }
4197
4198    public void genHasChanged() throws IOException {
4199        if (beanElement.isRoot) {
4200            select(DECL_SECTION);
4201            jw.writeEol("private boolean changed");
4202        }
4203        select(BODY_SECTION);
4204        jw.bigComment("Change the result of _hasChanged().\nThis is done automatically when a value in this bean graph gets changed.");
4205        jw.beginMethod("_setChanged", "boolean changed", null, "void", jw.PUBLIC);
4206        if (beanElement.isRoot) {
4207            jw.writeEol("this.changed = changed");
4208        } else {
4209            jw.beginIf("parent != null");
4210            jw.writeEol("parent._setChanged(changed)");
4211            jw.end();
4212        }
4213        jw.endMethod();
4214        if (beanElement.isRoot) {
4215            jw.bigComment("@return true if something has changed in this bean graph.");
4216            jw.beginMethod("_hasChanged", "", null, "boolean", jw.PUBLIC);
4217            jw.writeEol("return changed");
4218            jw.endMethod();
4219        }
4220    }
4221    
4222    public void genChildBeans() throws IOException {
4223        select(BODY_SECTION);
4224        jw.bigComment("Return an array of all of the properties that are beans and are set.");
4225        String JavaDoc cb = config.isExtendBaseBean() ? "org.netbeans.modules.schema2beans.BaseBean" : commonBeanType();
4226        jw.beginMethod("childBeans", "boolean recursive", null, cb+"[]", jw.PUBLIC);
4227        jw.write("java.util.List");
4228        if (config.jdkTarget >= 150)
4229            jw.write("<", cb, ">");
4230        jw.write(" children = new java.util.LinkedList");
4231        if (config.jdkTarget >= 150)
4232            jw.write("<", cb, ">");
4233        jw.writeEol("()");
4234        jw.writeEol("childBeans(recursive, children)");
4235        jw.writeEol(cb+"[] result = new "+cb+"[children.size()]");
4236        jw.writeEol("return ("+cb+"[]) children.toArray(result)");
4237        jw.endMethod();
4238        jw.bigComment("Put all child beans into the beans list.");
4239        String JavaDoc childBeansArgs = "boolean recursive, java.util.List";
4240        if (config.jdkTarget >= 150)
4241            childBeansArgs += "<"+cb+">";
4242        childBeansArgs += " beans";
4243        jw.beginMethod("childBeans", childBeansArgs, null, "void", jw.PUBLIC);
4244        for (int i = 0, size = attrList.size(); i < size; i++) {
4245            Property a = (Property) attrList.get(i);
4246            if (!a.isBean)
4247                continue;
4248            boolean indexed = a.isIndexed();
4249            String JavaDoc type = a.getType().intern();
4250            String JavaDoc attr = "_" + a.name;
4251            if (indexed) {
4252                beginAttrIterator(attr, a, "element");
4253                attr = "element";
4254            }
4255            jw.beginIf(attr+" != null");
4256            jw.beginIf("recursive");
4257            jw.writeEol(attr+".childBeans(true, beans)");
4258            jw.end();
4259            jw.writeEol("beans.add("+attr+")");
4260            jw.end();
4261            if (indexed) {
4262                jw.end();
4263            }
4264        }
4265        if (config.isRespectExtension() && beanElement.getExtension() != null) {
4266            jw.writeEol("super.childBeans(recursive, beans)");
4267        }
4268        jw.endMethod();
4269    }
4270
4271    public void genName() throws IOException {
4272        select(BODY_SECTION);
4273        jw.beginMethod("nameSelf", "", null, "String", jw.PUBLIC);
4274        if (config.isGenerateParentRefs()) {
4275            jw.beginIf("parent != null");
4276            jw.writeEol("String parentName = parent.nameSelf()");
4277            jw.writeEol("String myName = parent.nameChild(this, false, false)");
4278            jw.writeEol("return parentName + \"/\" + myName");
4279            jw.end();
4280        }
4281        String JavaDoc beanName = Common.convertName(beanElement.node.getName());
4282        if (beanElement.isRoot)
4283            jw.writeEol("return \"/"+beanName+"\"");
4284        else
4285            jw.writeEol("return \""+beanName+"\"");
4286        jw.endMethod();
4287
4288        jw.beginMethod("nameChild", "Object childObj", null, "String", jw.PUBLIC);
4289        jw.writeEol("return nameChild(childObj, false, false)");
4290        jw.endMethod();
4291        
4292        jw.bigComment("@param childObj The child object to search for\n@param returnSchemaName Whether or not the schema name should be returned or the property name\n@return null if not found");
4293        jw.beginMethod("nameChild", "Object childObj, boolean returnConstName, boolean returnSchemaName", null, "String", jw.PUBLIC);
4294        jw.writeEol("return nameChild(childObj, returnConstName, returnSchemaName, false)");
4295        jw.endMethod();
4296
4297        jw.bigComment("@param childObj The child object to search for\n@param returnSchemaName Whether or not the schema name should be returned or the property name\n@return null if not found");
4298        jw.beginMethod("nameChild", "Object childObj, boolean returnConstName, boolean returnSchemaName, boolean returnXPathName", null, "String", jw.PUBLIC);
4299        // Sort by type
4300
Map typeMap = new HashMap(); // Map<String, List<Property>>
4301
for (int i = 0, size = attrList.size(); i < size; i++) {
4302            Property prop = (Property) attrList.get(i);
4303            String JavaDoc type = JavaUtil.toObjectType(prop.getType());
4304            if (type.equals("String"))
4305                type = "java.lang.String"; // normalize
4306
List lst = (List) typeMap.get(type);
4307            if (lst == null) {
4308                lst = new LinkedList();
4309                typeMap.put(type, lst);
4310            }
4311            lst.add(prop);
4312        }
4313        for (Iterator types = typeMap.keySet().iterator(); types.hasNext(); ) {
4314            String JavaDoc type = (String JavaDoc) types.next();
4315            jw.beginIf("childObj instanceof "+type);
4316            jw.writeEol(type, " child = (", type, ") childObj");
4317            boolean firstUseOfIndex = true;
4318            for (Iterator props = ((List)typeMap.get(type)).iterator(); props.hasNext(); ) {
4319                Property prop = (Property) props.next();
4320                String JavaDoc attr = "_" + prop.name;
4321                String JavaDoc childExpr = "child";
4322                if (JavaUtil.isPrimitiveType(prop.getType()))
4323                    childExpr = JavaUtil.fromObject(prop.getType(), "child");
4324                if (prop.isIndexed()) {
4325                    if (firstUseOfIndex) {
4326                        firstUseOfIndex = false;
4327                        jw.writeEol("int index = 0");
4328                    } else {
4329                        jw.writeEol("index = 0");
4330                    }
4331                    beginAttrIterator(attr, prop, "element");
4332                    jw.beginIf(childExpr+" == element");
4333                    jw.beginIf("returnConstName");
4334                    jw.writeEol("return ", prop.constName);
4335                    if (prop.type != Common.TYPE_COMMENT) {
4336                        jw.endElseBeginIf("returnSchemaName");
4337                        jw.writeEol("return \"", prop.dtdName, "\"");
4338                        jw.endElseBeginIf("returnXPathName");
4339                        jw.write("return \"");
4340                        if (prop.isAttribute())
4341                            jw.write("@");
4342                        jw.writeEol(prop.dtdName,
4343                                    "[position()=\"+index+\"]\"");
4344                    }
4345                    jw.endElseBegin();
4346                    jw.writeEol("return \""+prop.getEventName()+".\"+Integer.toHexString(index)");
4347                    jw.end();
4348                    jw.end();
4349                    jw.writeEol("++index");
4350                    jw.end();
4351                } else {
4352                    jw.beginIf(childExpr+" == "+attr);
4353                    jw.beginIf("returnConstName");
4354                    jw.writeEol("return ", prop.constName);
4355                    if (prop.type != Common.TYPE_COMMENT) {
4356                        jw.endElseBeginIf("returnSchemaName");
4357                        jw.writeEol("return \"", prop.dtdName, "\"");
4358                        jw.endElseBeginIf("returnXPathName");
4359                        jw.write("return \"");
4360                        if (prop.isAttribute())
4361                            jw.write("@");
4362                        jw.writeEol(prop.dtdName, "\"");
4363                    }
4364                    jw.endElseBegin();
4365                    jw.writeEol("return \""+prop.getEventName()+"\"");
4366                    jw.end();
4367                    jw.end();
4368                }
4369            }
4370            jw.end();
4371        }
4372        if (config.isRespectExtension() && beanElement.getExtension() != null) {
4373            jw.writeEol("return super.nameChild(childObj, returnConstName, returnSchemaName, returnXPathName)");
4374        } else {
4375            jw.writeEol("return null");
4376        }
4377        jw.endMethod();
4378    }
4379
4380    public void genToString() throws IOException {
4381        jw.beginMethod("toString", "", null, "String", jw.PUBLIC);
4382        jw.writeEol("java.io.StringWriter sw = new java.io.StringWriter()");
4383        jw.beginTry();
4384        jw.writeEol("writeNode(sw)");
4385        jw.endCatch("java.io.IOException e");
4386        jw.comment("How can we actually get an IOException on a StringWriter?");
4387        jw.writeEol("throw new RuntimeException(e)");
4388        jw.end();
4389        jw.writeEol("return sw.toString()");
4390        jw.endMethod();
4391    }
4392
4393    public void genExtendBaseBean() throws IOException {
4394        int size = attrList.size();
4395        jw.beginMethod("dump", "StringBuffer str, String indent", null,
4396                       "void", jw.PUBLIC);
4397        jw.writeEol("str.append(toString())");
4398        jw.endMethod();
4399
4400        jw.pushSelect(jw.DECL_SECTION);
4401        String JavaDoc[] propByNameKeys = new String JavaDoc[size+1];
4402        for (int i = 0; i < size; i++) {
4403            Property a = (Property)attrList.get(i);
4404            propByNameKeys[i] = a.name;
4405        }
4406        propByNameKeys[size] = "";
4407        jw.writeEol("private java.util.Map propByName = new java.util.HashMap("+(JavaUtil.getOptimialHashMapSize(propByNameKeys)), ", 1.0f)");
4408        jw.popSelect();
4409        jw.beginMethod("beanProp", "String name", null, "org.netbeans.modules.schema2beans.BeanProp", jw.PUBLIC);
4410        jw.writeEol("if (name == null) return null");
4411        jw.writeEol("org.netbeans.modules.schema2beans.BeanProp prop = (org.netbeans.modules.schema2beans.BeanProp) propByName.get(name)");
4412        jw.beginIf("prop == null");
4413        jw.writeEol("name = name.intern()");
4414        jw.writeEol("boolean indexed");
4415        jw.writeEol("int options");
4416        jw.writeEol("String constName");
4417        jw.writeEol("String schemaName");
4418        jw.writeEol("java.lang.reflect.Method writer = null");
4419        jw.writeEol("java.lang.reflect.Method arrayWriter = null");
4420        jw.writeEol("java.lang.reflect.Method reader = null");
4421        jw.writeEol("java.lang.reflect.Method arrayReader = null");
4422        jw.writeEol("java.lang.reflect.Method adder = null");
4423        jw.writeEol("java.lang.reflect.Method remover = null");
4424        boolean defaultKey = true;
4425        if (metaElement != null) {
4426            MetaProperty[] mp = metaElement.getMetaProperty();
4427            for (int i=0; i<mp.length; i++) {
4428                if (mp[i].isKey()) {
4429                    // At least one key is defined - default to false
4430
defaultKey = false;
4431                    break;
4432                }
4433            }
4434        }
4435
4436        jw.beginTry();
4437        for (int i = 0; i < size; i++) {
4438            Property a = (Property)attrList.get(i);
4439            boolean indexed = a.isIndexed();
4440            String JavaDoc type = a.getType();
4441            MetaProperty mp = getMetaProperty(a.name);
4442            boolean keyedElement = defaultKey;
4443            boolean genVetoable = config.isVetoable();
4444            if (mp != null) {
4445                keyedElement = (mp.isKey())?true:defaultKey;
4446                genVetoable = (mp.isVetoable())?true:genVetoable;
4447            }
4448            MetaElement me = getMetaElement(a);
4449            if (me != null) {
4450                genVetoable = (me.isVetoable())?true:genVetoable;
4451            }
4452            if (a.isBean)
4453                genVetoable = false;
4454            String JavaDoc signatureType = a.getSignatureType(packageName);
4455
4456            /*
4457            if (a.getEventName().equals(a.beanIntrospectorName()))
4458                jw.beginIf("name == \""+a.getEventName()+"\" || name == \""+a.constName+"\"");
4459            else
4460                jw.beginIf("name == \""+a.getEventName()+"\" || name == \""+a.beanIntrospectorName()+"\" || name == \""+a.constName+"\"");
4461            */

4462            jw.beginIf("name == "+a.constName+"");
4463            jw.writeEol("indexed = "+indexed);
4464            jw.writeEol("constName = ", a.constName, "");
4465            jw.writeEol("schemaName = \"", a.dtdName, "\"");
4466            jw.write("options = ");
4467            if (a.ored)
4468                jw.write("org.netbeans.modules.schema2beans.Common.SEQUENCE_OR | ");
4469            if (genVetoable)
4470                jw.write("org.netbeans.modules.schema2beans.Common.TYPE_VETOABLE |");
4471            if (a.type == Common.TYPE_BOOLEAN && !a.getCanBeEmpty())
4472                gen("org.netbeans.modules.schema2beans.Common.TYPE_SHOULD_NOT_BE_EMPTY | ");
4473            if (keyedElement)
4474                gen("org.netbeans.modules.schema2beans.Common.TYPE_KEY | ");
4475            jw.writeEol("org.netbeans.modules.schema2beans.Common.",
4476                        Common.instanceToCommonString(a.elementInstance),
4477                        "|org.netbeans.modules.schema2beans.Common.",
4478                        Common.typeToString(a.type));
4479            if (indexed) {
4480                jw.writeEol("reader = getClass().getMethod(\"",
4481                            a.getReadMethod(true), "\", new Class[] {Integer.TYPE})");
4482                jw.writeEol("arrayReader = getClass().getMethod(\"",
4483                            a.getReadMethod(false), "\", new Class[] {})");
4484                jw.writeEol("writer = getClass().getMethod(\"",
4485                            a.getWriteMethod(), "\", new Class[] {Integer.TYPE, ",
4486                            signatureType+".class})");
4487                jw.writeEol("arrayWriter = getClass().getMethod(\"",
4488                            a.getWriteMethod(), "\", new Class[] {",
4489                            signatureType+"[].class})");
4490                jw.writeEol("adder = getClass().getMethod(\"",
4491                            a.getAddMethod(), "\", new Class[] {",
4492                            signatureType+".class})");
4493                jw.writeEol("remover = getClass().getMethod(\"",
4494                            a.getRemoveMethod(), "\", new Class[] {",
4495                            signatureType+".class})");
4496            } else {
4497                jw.writeEol("writer = getClass().getMethod(\"",
4498                            a.getWriteMethod(), "\", new Class[] {",
4499                            signatureType+".class})");
4500                jw.writeEol("reader = getClass().getMethod(\"",
4501                            a.getReadMethod(false), "\", new Class[] {})");
4502            }
4503            jw.end(false);
4504            jw.write(" else ");
4505        }
4506        jw.begin();
4507        jw.comment("Check if name is a schema name.");
4508        for (int i = 0; i < size; i++) {
4509            Property a = (Property)attrList.get(i);
4510            // Only check those names we haven't looked at before.
4511
if (a.dtdName.equals(a.name))
4512                continue;
4513            jw.beginIf("name == \""+a.dtdName+"\"");
4514            jw.writeEol("prop = beanProp(", a.constName, ")");
4515            jw.writeEol("propByName.put(name, prop)");
4516            jw.writeEol("return prop");
4517            jw.end();
4518        }
4519        genInvalidName("name");
4520        jw.end();
4521        jw.endCatch("java.lang.NoSuchMethodException e");
4522        jw.writeEol("throw new RuntimeException(e)");
4523        jw.end();
4524        
4525        jw.write("prop = new org.netbeans.modules.schema2beans.ReflectiveBeanProp(this, schemaName, ");
4526        jw.write("constName, options, getClass(), ");
4527        jw.writeEol(""+beanElement.isRoot, ", writer, arrayWriter, reader, arrayReader, adder, remover)");
4528        jw.writeEol("propByName.put(name, prop)");
4529        jw.end(); // if
4530

4531        jw.writeEol("return prop");
4532        jw.endMethod();
4533
4534        jw.beginMethod("beanProp", "", null, "org.netbeans.modules.schema2beans.BeanProp", jw.PUBLIC);
4535        jw.beginIf("parent == null");
4536        jw.writeEol("org.netbeans.modules.schema2beans.BeanProp prop = (org.netbeans.modules.schema2beans.BeanProp) propByName.get(\"\")");
4537        jw.beginIf("prop == null");
4538        jw.write("prop = new org.netbeans.modules.schema2beans.ReflectiveBeanProp(this, \"",
4539                 beanElement.node.getName(), "\", \"", className);
4540        jw.writeEol("\", org.netbeans.modules.schema2beans.Common.TYPE_1 | org.netbeans.modules.schema2beans.Common.TYPE_BEAN, ",
4541                    className,
4542                    ".class, isRoot(), null, null, null, null, null, null)");
4543        jw.writeEol("propByName.put(\"\", prop)");
4544        jw.end(); // if
4545
jw.writeEol("return prop");
4546        jw.end();
4547        jw.writeEol("String myConstName = parent.nameChild(this, true, false)");
4548        jw.writeEol("return parent.beanProp(myConstName)");
4549        jw.endMethod();
4550
4551        jw.beginMethod("beanProp", "int order", null, "org.netbeans.modules.schema2beans.BeanProp", jw.PUBLIC|jw.UNSUPPORTED);
4552        jw.writeEol("prepareBeanPropList()");
4553        jw.writeEol("return (org.netbeans.modules.schema2beans.BeanProp) beanPropList.get(order)");
4554        jw.endMethod();
4555        
4556        jw.beginMethod("parent", "", null, "org.netbeans.modules.schema2beans.BaseBean", jw.PUBLIC);
4557        jw.writeEol("return (org.netbeans.modules.schema2beans.BaseBean) parent");
4558        jw.endMethod();
4559
4560        jw.beginMethod("_getParent", "", null, "org.netbeans.modules.schema2beans.Bean", jw.PUBLIC);
4561        jw.writeEol("return parent");
4562        jw.endMethod();
4563
4564        jw.beginMethod("newInstance", "String name", null, "org.netbeans.modules.schema2beans.BaseBean", jw.PUBLIC|jw.UNSUPPORTED);
4565        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4566        jw.endMethod();
4567
4568        jw.beginMethod("dtdName", "", null, "String", jw.PUBLIC);
4569        jw.beginIf("parent == null");
4570        if (!beanElement.isRoot())
4571            jw.comment("Not necessarily the right schema name, but make a good guess.");
4572        jw.writeEol("return \"", beanElement.node.getName(), "\"");
4573        jw.end();
4574        jw.writeEol("return parent.nameChild(this, false, true)");
4575        jw.endMethod();
4576
4577        jw.beginMethod("comments", "", null, "org.w3c.dom.Comment[]", jw.PUBLIC|jw.UNSUPPORTED);
4578        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4579        jw.endMethod();
4580
4581        jw.beginMethod("addComment", "String comment", null, "org.w3c.dom.Comment", jw.PUBLIC|jw.UNSUPPORTED);
4582        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4583        jw.endMethod();
4584
4585        jw.beginMethod("removeComment", "org.w3c.dom.Comment comment", null, "void", jw.PUBLIC|jw.UNSUPPORTED);
4586        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4587        jw.endMethod();
4588
4589        jw.beginMethod("createProperty",
4590                       "String dtdName, String beanName, Class type", null, "void", jw.PUBLIC|jw.UNSUPPORTED);
4591        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4592        jw.endMethod();
4593
4594        jw.beginMethod("createProperty",
4595                       "String dtdName, String beanName, int option, Class type", null, "void", jw.PUBLIC|jw.UNSUPPORTED);
4596        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4597        jw.endMethod();
4598
4599        jw.beginMethod("createRoot",
4600                       "String dtdName, String beanName, int option, Class type", null, "void", jw.PUBLIC|jw.UNSUPPORTED);
4601        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4602        jw.endMethod();
4603
4604        jw.beginMethod("knownValues",
4605                       "String name", null, "Object[]", jw.PUBLIC|jw.UNSUPPORTED);
4606        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4607        jw.endMethod();
4608
4609        jw.beginMethod("addKnownValue",
4610                       "String name, Object value", null, "void", jw.PUBLIC|jw.UNSUPPORTED);
4611        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4612        jw.endMethod();
4613
4614        jw.beginMethod("createAttribute",
4615                       "String dtdName, String name, int type, String[] values, String defValue", null, "void", jw.PUBLIC|jw.UNSUPPORTED);
4616        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4617        jw.endMethod();
4618
4619        jw.beginMethod("createAttribute",
4620                       "String propName, String dtdName, String name, int type, String[] values, String defValue", null, "void", jw.PUBLIC|jw.UNSUPPORTED);
4621        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4622        jw.endMethod();
4623
4624        jw.beginMethod("setAttributeValue",
4625                       "String propName, String name, String value", null, "void", jw.PUBLIC|jw.UNSUPPORTED);
4626        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4627        jw.endMethod();
4628
4629        jw.beginMethod("setAttributeValue",
4630                       "String name, String value", null, "void", jw.PUBLIC|jw.UNSUPPORTED);
4631        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4632        jw.endMethod();
4633
4634        jw.beginMethod("getAttributeValue",
4635                       "String name", null, "String", jw.PUBLIC|jw.UNSUPPORTED);
4636        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4637        jw.endMethod();
4638
4639        jw.beginMethod("getAttributeValue",
4640                       "String propName, String name", null, "String", jw.PUBLIC|jw.UNSUPPORTED);
4641        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4642        jw.endMethod();
4643
4644        jw.beginMethod("setAttributeValue",
4645                       "String propName, int index, String name, String value", null, "void", jw.PUBLIC|jw.UNSUPPORTED);
4646        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4647        jw.endMethod();
4648
4649        jw.beginMethod("getAttributeValue",
4650                       "String propName, int index, String name", null, "String", jw.PUBLIC|jw.UNSUPPORTED);
4651        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4652        jw.endMethod();
4653
4654        jw.beginMethod("getAttributeNames",
4655                       "String propName", null, "String[]", jw.PUBLIC);
4656        jw.writeEol("return new String[] {}");
4657        jw.endMethod();
4658
4659        jw.beginMethod("getAttributeNames",
4660                       "", null, "String[]", jw.PUBLIC);
4661        jw.writeEol("return new String[] {}");
4662        jw.endMethod();
4663
4664        jw.beginMethod("listAttributes",
4665                       "String propName", null, "org.netbeans.modules.schema2beans.BaseAttribute[]", jw.PUBLIC);
4666        jw.writeEol("return new org.netbeans.modules.schema2beans.BaseAttribute[] {}");
4667        jw.endMethod();
4668
4669        jw.beginMethod("listAttributes",
4670                       "", null, "org.netbeans.modules.schema2beans.BaseAttribute[]", jw.PUBLIC);
4671        jw.writeEol("return new org.netbeans.modules.schema2beans.BaseAttribute[] {}");
4672        jw.endMethod();
4673
4674        jw.beginMethod("findAttributeValue",
4675                       "String attrName, String value", null, "String[]", jw.PUBLIC);
4676        jw.writeEol("return new String[] {}");
4677        jw.endMethod();
4678
4679        jw.beginMethod("findPropertyValue",
4680                       "String propName, Object value", null, "String[]", jw.PUBLIC|jw.UNSUPPORTED);
4681        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4682        jw.endMethod();
4683
4684        jw.beginMethod("findValue",
4685                       "Object value", null, "String[]", jw.PUBLIC|jw.UNSUPPORTED);
4686        jw.writeEol("throw new UnsupportedOperationException(\"Not implemented\")");
4687        jw.endMethod();
4688
4689        jw.beginMethod("buildPathName", "StringBuffer str", null, "void", jw.PROTECTED);
4690        jw.writeEol("str.append(nameSelf())");
4691        jw.endMethod();
4692
4693        jw.beginMethod("graphManager", "", null, "org.netbeans.modules.schema2beans.GraphManager", jw.PUBLIC);
4694        jw.beginIf("graphManager == null");
4695        jw.beginIf("parent == null");
4696        //jw.writeEol("System.out.println(\"Creating GraphManager for \"+getClass()+\" this=\"+this)");
4697
//jw.comment("new Exception().printStackTrace()");
4698
jw.writeEol("graphManager = new org.netbeans.modules.schema2beans.GraphManager(this)");
4699        jw.endElseBegin();
4700        jw.writeEol("graphManager = parent.graphManager()");
4701        jw.end();
4702        jw.end();
4703        jw.writeEol("return graphManager");
4704        jw.endMethod();
4705
4706        jw.beginMethod("clone", "", null, "Object", jw.PUBLIC | jw.BEANINFO);
4707        jw.writeEol("return new ", className, "(this, null, false)");
4708        jw.endMethod();
4709
4710        jw.beginMethod("cloneData", "", null, "Object", jw.PUBLIC | jw.BEANINFO);
4711        jw.writeEol("return new ", className, "(this, null, true)");
4712        jw.endMethod();
4713
4714        jw.pushSelect(DECL_SECTION);
4715        jw.write("private java.util.List beanPropList = null");
4716        jw.eol(false);
4717        jw.write("\t");
4718        jw.comment("List<org.netbeans.modules.schema2beans.BeanProp>");
4719        jw.popSelect();
4720        jw.beginMethod("prepareBeanPropList", "", null, "void", jw.PRIVATE);
4721        jw.beginIf("beanPropList == null");
4722        jw.writeEol("beanPropList = new java.util.ArrayList("+size+")");
4723        for (int i = 0; i < size; i++) {
4724            Property a = (Property)attrList.get(i);
4725            jw.writeEol("beanPropList.add(beanProp(", a.constName, "))");
4726        }
4727        jw.end();
4728        jw.endMethod();
4729
4730        jw.beginMethod("beanPropsIterator", "", null, "java.util.Iterator",
4731                       jw.PROTECTED);
4732        jw.writeEol("prepareBeanPropList()");
4733        jw.writeEol("return beanPropList.iterator()");
4734        jw.endMethod();
4735
4736        jw.beginMethod("beanProps", "", null, "org.netbeans.modules.schema2beans.BeanProp[]", jw.PUBLIC);
4737        jw.writeEol("prepareBeanPropList()");
4738        jw.writeEol("org.netbeans.modules.schema2beans.BeanProp[] ret = new org.netbeans.modules.schema2beans.BeanProp["+size+"]");
4739        jw.writeEol("ret = (org.netbeans.modules.schema2beans.BeanProp[]) beanPropList.toArray(ret)");
4740        jw.writeEol("return ret");
4741        jw.endMethod();
4742
4743        jw.beginMethod("setValue", "String name, Object value", null, "void", jw.PUBLIC);
4744        new NamePropertyVisitor("name") {
4745                public void generateProp() throws IOException {
4746                    if (curProp.isIndexed()) {
4747                        jw.write(curProp.getWriteMethod(), "(");
4748                        jw.writeEol("(", curProp.getType(), "[]) value)");
4749                    } else {
4750                        jw.write(curProp.getWriteMethod(), "(");
4751                        jw.write(JavaUtil.fromObject(curProp.getType(), "value"));
4752                        jw.writeEol(")");
4753                    }
4754                }
4755            }.generate();
4756        jw.endMethod();
4757
4758        jw.beginMethod("setValue", "String name, int index, Object value", null, "void", jw.PUBLIC);
4759        new NamePropertyVisitor("name") {
4760                public void generateProp() throws IOException {
4761                    if (curProp.isIndexed()) {
4762                        jw.write(curProp.getWriteMethod(), "(index, ");
4763                        jw.write(JavaUtil.fromObject(curProp.getType(), "value"));
4764                        jw.writeEol(")");
4765                    } else {
4766                        jw.writeEol("throw new IllegalArgumentException(name+\" is not an indexed property for ",
4767                                    className, "\")");
4768                    }
4769                }
4770            }.generate();
4771        jw.endMethod();
4772
4773        jw.beginMethod("getValue", "String name", null, "Object", jw.PUBLIC);
4774        new NamePropertyVisitor("name") {
4775                public void generateProp() throws IOException {
4776                    jw.write("return ");
4777                    if (curProp.isIndexed())
4778                        jw.writeEol(curProp.getReadMethod(false)+"()");
4779                    else
4780                        jw.writeEol(JavaUtil.toObject(curProp.getReadMethod(false)+"()",
4781                                                      curProp.getType(),
4782                                                      config.isForME()));
4783                }
4784            }.generate();
4785        jw.endMethod();
4786
4787        jw.beginMethod("getValue", "String name, int index", null, "Object", jw.PUBLIC);
4788        new NamePropertyVisitor("name") {
4789                public boolean skip() {
4790                    return !curProp.isIndexed();
4791                }
4792                
4793                public void generateProp() throws IOException {
4794                    jw.write("return ");
4795                    jw.writeEol(JavaUtil.toObject(curProp.getReadMethod(true)+"(index)",
4796                                                  curProp.getType(),
4797                                                  config.isForME()));
4798                }
4799
4800                public void postGenerate() throws IOException {}
4801            }.generate();
4802        new NamePropertyVisitor("name") {
4803                public void preGenerate() throws IOException {}
4804                
4805                public boolean skip() {
4806                    return curProp.isIndexed();
4807                }
4808                
4809                public void generateProp() throws IOException {
4810                    jw.beginIf("index > 0");
4811                    jw.writeEol("throw new IllegalArgumentException(\"index > 0\")");
4812                    jw.end();
4813                    jw.write("return ");
4814                    jw.writeEol(JavaUtil.toObject(curProp.getReadMethod(false)+"()",
4815                                                  curProp.getType(),
4816                                                  config.isForME()));
4817                }
4818            }.generate();
4819        jw.endMethod();
4820
4821        jw.beginMethod("mergeUpdate",
4822                       "org.netbeans.modules.schema2beans.BaseBean sourceBean",
4823                       null, "void", jw.PUBLIC);
4824        //jw.writeEol("System.out.println(\"mergeUpdate for \"+getClass())");
4825
jw.writeEol(fullClassName, " source = (", fullClassName, ") sourceBean");
4826        boolean isArrayStyle = (config.getIndexedPropertyType() == null);
4827        for (int i = 0; i < size; i++) {
4828            Property a = (Property) attrList.get(i);
4829            boolean indexed = a.isIndexed();
4830            String JavaDoc type = a.getType().intern();
4831            boolean willCopy = genCopyWillCopy(a);
4832            String JavaDoc getter = "source."+a.getReadMethod(false)+"()";
4833            String JavaDoc signatureType = a.getSignatureType(packageName);
4834            String JavaDoc baseFullClassName = a.getTypeFullClassName(packageName);
4835            String JavaDoc fullClassName;
4836            if (indexed) {
4837                fullClassName = baseFullClassName + "[]";
4838            } else
4839                fullClassName = baseFullClassName;
4840            jw.begin();
4841            jw.write(fullClassName, " srcProperty = ");
4842            if (!signatureType.equals(baseFullClassName))
4843                jw.write("(", fullClassName, ") ");
4844            jw.writeEol(getter);
4845            String JavaDoc srcProperty = "srcProperty";
4846            if (a.isBean) {
4847                if (indexed) {
4848                    jw.writeEol("int destSize = ", a.getSizeMethod(), "()");
4849                    jw.beginIf("destSize == srcProperty.length");
4850                    srcProperty = "srcProperty[i]";
4851                    jw.beginFor("int i = 0", "i < srcProperty.length", "++i");
4852                    genMergeUpdateBean(a, srcProperty, indexed, signatureType,
4853                                       baseFullClassName, isArrayStyle, true);
4854                    jw.endElseBegin();
4855                    jw.writeEol(fullClassName, " destArray = new ",
4856                                baseFullClassName,
4857                                "[srcProperty.length]");
4858                    jw.beginFor("int i = 0", "i < srcProperty.length", "++i");
4859                    genMergeUpdateBean(a, srcProperty, indexed, signatureType,
4860                                       baseFullClassName, isArrayStyle, false);
4861                    jw.end();
4862                    jw.writeEol(a.getWriteMethod(), "(destArray)");
4863                    jw.end();
4864                } else {
4865                    genMergeUpdateBean(a, srcProperty, indexed, signatureType,
4866                                       baseFullClassName, isArrayStyle, false);
4867                }
4868
4869            } else if (indexed && (willCopy || isArrayStyle)) {
4870                jw.writeEol(fullClassName, " destArray = new ",
4871                            baseFullClassName,
4872                            "[srcProperty.length]");
4873                jw.beginFor("int i = 0", "i < srcProperty.length", "++i");
4874                srcProperty = "srcProperty[i]";
4875                jw.write("destArray[i] = ");
4876                genCopy(srcProperty, a, "false");
4877                jw.eol();
4878                jw.end();
4879                jw.writeEol(a.getWriteMethod(), "(destArray)");
4880            } else {
4881                jw.write(a.getWriteMethod(), "(");
4882                genCopy(srcProperty, a, "false");
4883                jw.writeEol(")");
4884            }
4885            jw.end();
4886        }
4887        jw.endMethod();
4888
4889        if (beanElement.isRoot()) {
4890            jw.beginMethod("isRoot", "", null, "boolean", jw.PUBLIC);
4891            jw.writeEol("return true");
4892            jw.endMethod();
4893
4894            jw.beginMethod("createGraph",
4895                           "java.io.InputStream in, boolean validate",
4896                           "java.io.IOException, javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException",
4897                           className, jw.PUBLIC | jw.STATIC | jw.IO);
4898            //jw.beginTry();
4899
jw.writeEol("return read(new org.xml.sax.InputSource(in), validate, null, null)");
4900            /*
4901            jw.endCatch("javax.xml.parsers.ParserConfigurationException e");
4902            jw.writeEol("throw new java.lang.RuntimeException(e)");
4903            jw.endCatch("org.xml.sax.SAXException e");
4904            jw.writeEol("throw new java.lang.RuntimeException(e)");
4905            jw.endCatch("java.io.IOException e");
4906            jw.writeEol("throw new java.lang.RuntimeException(e)");
4907            jw.end();
4908            */

4909            jw.endMethod();
4910
4911            jw.beginMethod("createGraph", "java.io.InputStream in",
4912                           "java.io.IOException, javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException",
4913                           className, jw.PUBLIC | jw.STATIC | jw.IO);
4914            jw.writeEol("return createGraph(in, false)");
4915            jw.endMethod();
4916
4917            jw.beginMethod("createGraph", "", null, className, jw.PUBLIC | jw.STATIC | jw.IO);
4918            jw.writeEol("return new ", className, "()");
4919            jw.endMethod();
4920
4921            jw.beginMethod("createGraph", "org.w3c.dom.Document document", null, className, jw.PUBLIC | jw.STATIC);
4922            jw.writeEol("return read(document)");
4923            jw.endMethod();
4924
4925            jw.pushSelect(CONSTRUCTOR_SECTION);
4926            jw.beginConstructor(className, "org.w3c.dom.Node doc, int currentlyUnusedOptions");
4927            jw.writeEol("this()");
4928            jw.writeEol("readFromDocument((org.w3c.dom.Document) doc)");
4929            jw.end();
4930            jw.cr();
4931            jw.popSelect();
4932        } else {
4933            jw.bigComment("@deprecated");
4934            jw.beginMethod("write", "java.io.Writer out, String encoding",
4935                           "java.io.IOException", "void", jw.PUBLIC | jw.IO);
4936            jw.writeEol("writeNode(out)");
4937            jw.endMethod();
4938
4939            jw.bigComment("@deprecated");
4940            jw.beginMethod("write", "java.io.OutputStream out",
4941                           "java.io.IOException", "void", jw.PUBLIC | jw.IO);
4942            jw.writeEol("java.io.PrintWriter pw = new java.io.PrintWriter(out)");
4943            jw.writeEol("writeNode(pw)");
4944            jw.writeEol("pw.flush()");
4945            jw.endMethod();
4946        }
4947    }
4948
4949    private void genMergeUpdateBean(Property a, String JavaDoc srcProperty,
4950                                    boolean indexed, String JavaDoc signatureType,
4951                                    String JavaDoc baseFullClassName,
4952                                    boolean isArrayStyle,
4953                                    boolean mergeEach) throws IOException {
4954        //jw.writeEol("System.out.println(\"mergeEach="+mergeEach+"\")");
4955
String JavaDoc attr = "_" + a.name;
4956        jw.writeEol(baseFullClassName, " dest");
4957        if (!indexed)
4958            jw.writeEol("boolean needToSet = false");
4959        jw.beginIf(srcProperty+" == null");
4960        jw.writeEol("dest = null");
4961        if (!indexed)
4962            jw.writeEol("needToSet = true");
4963        jw.endElseBegin();
4964        if (indexed) {
4965            jw.beginIf("i < destSize");
4966        }
4967        jw.write("dest = ");
4968        if (!signatureType.equals(baseFullClassName))
4969            jw.write("(", baseFullClassName, ") ");
4970        jw.write(a.getReadMethod(indexed), "(");
4971        if (indexed)
4972            jw.write("i");
4973        jw.writeEol(")");
4974        if (indexed) {
4975            if (!mergeEach) {
4976                jw.beginIf("!"+srcProperty+".equals(dest)");
4977                jw.comment("It's different, so have it just dup the source one.");
4978                jw.writeEol("dest = null");
4979                jw.end();
4980            }
4981            jw.endElseBegin();
4982            jw.writeEol("dest = null");
4983            jw.end();
4984        }
4985        //jw.writeEol("System.out.println(\"dest=\"+dest)");
4986
jw.beginIf("dest == null");
4987        jw.comment("Use a temp variable, and store it after we've merged everything into it, so as to make it only 1 change event.");
4988        jw.writeEol("dest = new ", baseFullClassName, "(", srcProperty+", this, false)");
4989        if (!indexed) {
4990            jw.writeEol("needToSet = true");
4991            jw.endElseBegin();
4992            jw.writeEol("dest.mergeUpdate(", srcProperty, ")");
4993            jw.end();
4994        } else {
4995            if (mergeEach) {
4996                jw.endElseBegin();
4997                jw.writeEol("dest.mergeUpdate(", srcProperty, ")");
4998                jw.end();
4999            }
5000        }
5001        jw.end();
5002        if (indexed) {
5003            if (mergeEach) {
5004                jw.comment("Merge events were generated by the above dest.mergeUpdate, so just set it directly now.");
5005                if (isArrayStyle) {
5006                    jw.writeEol(attr, "[index] = value");
5007                } else {
5008                    jw.writeEol(attr, ".set(i, dest)");
5009                }
5010            } else {
5011                jw.writeEol("destArray[i] = dest");
5012            }
5013            jw.end();
5014        } else {
5015            jw.beginIf("needToSet");
5016            jw.write(a.getWriteMethod(), "(");
5017            jw.writeEol("dest)");
5018            jw.end();
5019        }
5020    }
5021
5022    public void genTrailer(int out) {
5023        select(out);
5024        if (metaElement != null && metaElement.getUserCode() != null) {
5025            String JavaDoc userCode = metaElement.getUserCode();
5026            cr(); gencr(userCode);
5027        }
5028    }
5029
5030    public void genFinishClass(int out) {
5031        select(out);
5032        end();
5033        cr();
5034    }
5035
5036    public void setInvalidPropertyNames(Map invalidNames) {
5037        invalidNames.put("Class", null);
5038        if (config.isExtendBaseBean()) {
5039            invalidNames.put("Property", null);
5040            invalidNames.put("AttributeNames", null);
5041        }
5042    }
5043
5044    protected void beginAttrIterator(String JavaDoc attr, Property a,
5045                                     String JavaDoc elementName) throws IOException {
5046        String JavaDoc fullType = getTypeFullClassName(a);
5047        boolean isArrayStyle = (config.getIndexedPropertyType() == null);
5048        if (isArrayStyle) {
5049            jw.beginFor("int elementIndex = 0", "elementIndex < "+attr+".length",
5050                        "++elementIndex");
5051        } else {
5052            jw.beginFor("java.util.Iterator it = "+attr+".iterator()",
5053                        "it.hasNext()", "");
5054        }
5055        jw.write(fullType);
5056        jw.write(" ", elementName, " = ");
5057        if (isArrayStyle) {
5058            jw.writeEol(attr, "[elementIndex]");
5059        } else {
5060            jw.writeEol(JavaUtil.fromObject(fullType, "it.next()"));
5061        }
5062    }
5063
5064    protected void genNewEvent(Property a, String JavaDoc index,
5065                               String JavaDoc oldValue, String JavaDoc newValue,
5066                               String JavaDoc type) throws IOException {
5067        jw.write("new java.beans.PropertyChangeEvent(this, nameSelf()+\"/");
5068        jw.write(a.getEventName());
5069        if (index.equals(""))
5070            jw.write("\"");
5071        else if (index.equals("-1"))
5072            jw.write(".", index, "\"");
5073        else
5074            jw.write(".\"+Integer.toHexString(", index, ")");
5075        jw.write(", ");
5076        if ("null".equals(oldValue))
5077            jw.write("null");
5078        else
5079            jw.write(JavaUtil.toObject(oldValue, type, config.isForME()));
5080        jw.write(", ");
5081        if ("null".equals(newValue))
5082            jw.write("null");
5083        else
5084            jw.write(JavaUtil.toObject(newValue, type, config.isForME()));
5085        jw.write(")");
5086    }
5087
5088    protected boolean hasDeepCopyConstructor() {
5089        return true;
5090    }
5091}
5092
Popular Tags