|
What this is
Other links
The source code
/*
* Sun Public License Notice
*
* The contents of this file are subject to the Sun Public License
* Version 1.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://www.sun.com/
*
* The Original Code is NetBeans. The Initial Developer of the Original
* Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun
* Microsystems, Inc. All Rights Reserved.
*/
package org.netbeans.modules.schema2beansdev;
import java.util.*;
import java.io.*;
import org.netbeans.modules.schema2beans.*;
import org.netbeans.modules.schema2beansdev.metadd.*;
import org.netbeans.modules.schema2beansdev.gen.*;
public class JavaBeanClass extends AbstractCodeGeneratorClass implements CodeGeneratorClass {
// No element type number can be this one.
final protected int elementTypeSetnull = -1;
JavaBeanClass(BeanBuilder.BeanElement be, GenBeans.Config config) {
init(be, config);
}
/**
* Generate the java code in the out stream, using the optional
* metaDD bean graph.
*/
public void generate(OutputStream out, MetaDD mdd) throws IOException {
this.mdd = mdd;
metaElement = getMetaElement(beanElement);
if (metaElement != null && metaElement.isSkipGeneration()) {
config.messageOut.println(Common.getMessage("MSG_SkippingGeneration"));
return;
}
findAttributeOwners();
genAllParts();
select(DECL_SECTION);
cr();
printGenBuffers(out);
}
protected void genAllParts() throws IOException {
genHeader(HEADER_SECTION);
genPackage(HEADER_SECTION);
genImports(HEADER_SECTION);
genClassName(HEADER_SECTION);
genConstructor();
genAccessors();
if (!config.isMinFeatures())
genDeepCopy();
if (config.isGenerateXMLIO() || config.isDumpToString()) {
genXMLIO();
}
if (config.isGenerateValidate()) {
genValidate();
}
if (config.isGeneratePropertyEvents()) {
genPropertyEvents();
}
if (config.isGenerateStoreEvents()) {
genStoreEvents();
}
if (config.isVetoable()) {
genVetoable();
}
if (config.isGenerateTransactions()) {
genTransactions();
}
if (config.isGenerateHasChanged()) {
genHasChanged();
}
if (config.isGenerateSwitches()) {
generateSwitches();
}
if (!config.isMinFeatures())
genPropertiesByName();
if (config.isKeepElementPositions()) {
genElementPositions();
}
if (beanElement.isRoot && config.isProcessDocType()) {
genProcessDocType();
}
if (!config.isMinFeatures()) {
genName();
genChildBeans();
}
genEqualsHashCode();
if (config.isDumpToString()) {
genToString();
}
if (config.isExtendBaseBean())
genExtendBaseBean();
genTrailer(TRAILER_SECTION);
genFinishClass(TRAILER_SECTION);
try {
select(TRAILER_SECTION);
printSchema();
} catch (IOException ioe) {
// Do not generate the schema comment
}
}
protected void genMadeChange() throws IOException {
if (config.isGenerateHasChanged()) {
jw.writeEol("_setChanged(true)");
}
}
/**
* Whenever we create a constructor, call this method first.
*/
protected void genExtendBaseBeanConstructor() throws IOException {
if (config.isExtendBaseBean()) {
jw.writeEol("super(null, baseBeanRuntimeVersion)");
//jw.writeEol("System.out.println(\"Created class \"+getClass())");
}
}
public void genHeader(int out) throws IOException {
select(out);
gencr("/**");
gencr(" * This generated bean class " + className);
gencr(" * matches the schema element '" + beanElement.node.getName()+"'.");
if (!beanElement.isRoot) {
jw.writecr(" * The root bean class is "+rootBeanElement.getClassType());
}
gencr(" *");
printComment(" * ");
if (config.isGenerateTimeStamp())
gencr(" * Generated on " + new Date());
if (beanElement.isRoot) {
gencr(" *");
gencr(" * This class matches the root element of the "+(config.getSchemaTypeNum() == GenBeans.Config.DTD ? "DTD" : "XML Schema")+",");
gencr(" * and is the root of the bean graph.");
gencr(" *");
dumpBeanTree(jw, " * "+jw.getIndent(), jw.getIndent());
gencr(" *");
}
gencr(" * @"+Common.GENERATED_TAG);
gencr(" */"); cr();
}
public void genPackage(int out) {
select(out);
if (packageName != null) {
gen(PACKAGE, packageName);
eol();
cr();
}
}
public void genImports(int out) {
select(out);
}
public void genClassName(int out) {
String name = null;
String impName = null;
select(out);
gen(PUBLIC, CLASS, className);
if (mdd != null) {
if (metaElement != null) {
name = metaElement.getExtends();
impName = metaElement.getImplements();
}
if (name == null) {
name = mdd.getExtends();
}
if (impName == null) {
impName = mdd.getImplements();
}
}
if (name != null) {
gen(" extends ");
gencr(name);
}
if (impName != null) {
gen(" implements ", impName);
}
sp();
begin();
}
public void genConstructor() throws IOException {
int size = attrList.size();
if (!config.isMinFeatures()) {
jw.select(DECL_SECTION);
for (int i = 0; i < size; i++) {
Property a = (Property)attrList.get(i);
jw.write("public static final String ", a.constName,
" = \"", a.name);
jw.writeEolNoI18N("\"");
}
jw.cr();
}
jw.select(CONSTRUCTOR_SECTION);
jw.bigComment("Normal starting point constructor.");
jw.beginConstructor(className);
if (config.isExtendBaseBean()) {
jw.select(DECL_SECTION);
jw.write("private static final org.netbeans.modules.schema2beans.Version baseBeanRuntimeVersion = new org.netbeans.modules.schema2beans.Version(" +
Version.MAJVER, ", ");
jw.write(Version.MINVER + ", ");
jw.writeEol(Version.PTCVER + ")");
jw.select(CONSTRUCTOR_SECTION);
jw.writeEol("this(null, baseBeanRuntimeVersion)");
jw.end();
jw.cr();
jw.bigComment("This constructor is here for BaseBean compatibility.");
jw.beginConstructor(className, "java.util.Vector comps, org.netbeans.modules.schema2beans.Version baseBeanRuntimeVersion");
}
genExtendBaseBeanConstructor();
if (config.isMakeDefaults() || config.isSetDefaults()) {
for (int i = 0; i < size; i++) {
Property a = (Property)attrList.get(i);
boolean indexed = a.isIndexed();
boolean isScalar = a.isScalar();
if (indexed || isScalar || a.ored)
continue;
if (a.getDefaultValue() != null)
continue;
String type = a.getType();
String attr = "_"+a.name;
if (a.elementInstance == Common.TYPE_1) {
// There has to be at least 1 of them.
List exceps = JavaUtil.exceptionsFromParsingText(type, false);
if (!exceps.isEmpty()) {
jw.beginTry();
}
gen(attr, " = ");
genNewDefault(a, true);
eol();
if (a.isBean && config.isGenerateParentRefs()) {
jw.writeEol(attr, "._setParent(this)");
}
if (!exceps.isEmpty()) {
end();
genRethrowExceptions(exceps);
}
}
}
}
jw.end();
jw.cr();
// Create a constructor that has all of the required parameters.
List requiredParameters = new LinkedList();
for (int i = 0; i < size; i++) {
Property a = (Property)attrList.get(i);
// Is the property optional?
if (!a.ored && (a.elementInstance == Common.TYPE_1 || a.elementInstance == Common.TYPE_1_N))
requiredParameters.add(a);
}
if (!config.isMinFeatures() && requiredParameters.size() > 0) {
String parameters = null;
for (Iterator it = requiredParameters.iterator(); it.hasNext(); ) {
Property a = (Property) it.next();
if (parameters != null)
parameters += ", ";
else
parameters = "";
String type = a.getType();
String baseType = type;
if (a.isIndexed())
type = baseType + "[]";
String fullClassType = getTypeFullClassName(a, type);
parameters += fullClassType + " " + a.instanceOf();
}
jw.bigComment("Required parameters constructor");
jw.beginConstructor(className, parameters);
genExtendBaseBeanConstructor();
for (Iterator it = requiredParameters.iterator(); it.hasNext(); ) {
Property a = (Property) it.next();
boolean indexed = a.isIndexed();
String type = a.getType();
String baseType = type;
if (indexed)
type = baseType + "[]";
String attr = "_"+a.name;
SchemaRep.WhiteSpace ws = (SchemaRep.WhiteSpace) a.searchExtraData(SchemaRep.WhiteSpace.class);
if (!indexed) {
if (ws != null)
genWhiteSpaceRestriction(ws, a.instanceOf(), baseType);
jw.write(attr, " = ");
jw.writeEol(a.instanceOf());
if (a.isBean && config.isGenerateParentRefs()) {
jw.beginIf(attr+" != null");
jw.writeEol(attr, "._setParent(this)");
jw.end();
}
} else {
jw.beginIf(a.instanceOf() + "!= null");
if ("java.util.ArrayList".equals(config.getIndexedPropertyType())) {
jw.write("((", config.getIndexedPropertyType(),
") ", attr);
jw.writeEol(").ensureCapacity(",
a.instanceOf(), ".length)");
}
jw.beginFor("int i = 0", "i < "+a.instanceOf()+".length",
"++i");
if (ws != null)
genWhiteSpaceRestriction(ws, a.instanceOf()+"[i]",
baseType);
if (a.isBean && config.isGenerateParentRefs()) {
jw.beginIf(a.instanceOf()+"[i] != null");
jw.writeEol(a.instanceOf(), "[i]._setParent(this)");
jw.end();
}
jw.write(attr, ".add(",
JavaUtil.toObject(a.instanceOf()+"[i]", baseType,
config.isForME()));
jw.writeEol(")");
jw.end();
jw.end();
}
}
jw.end();
jw.cr();
}
}
public void genAccessors() throws IOException {
int size = attrList.size();
for (int i = 0; i < size; i++) {
Property a = (Property)attrList.get(i);
boolean indexed = a.isIndexed();
boolean isArrayStyle = (config.getIndexedPropertyType() == null);
boolean isWrapper = false;
boolean isScalar = a.isScalar();
String scalarType = a.getScalarType();
String attr = "_"+a.name;
String propertyName = a.beanIntrospectorName();
MetaElement me = getMetaElement(a);
String type = a.getType();
String baseType = type;
if (indexed)
type = baseType + "[]";
Signatures sigs = getSignatures(a);
Signature sig;
//System.out.println("a.name="+a.name+" a.type="+a.type+" a.dtdName="+a.dtdName+" isWrapper="+isWrapper+" a.classType="+a.classType+" me="+me);
select(DECL_SECTION);
if (indexed) {
if (isArrayStyle) {
gen(PRIVATE, baseType+"[]", attr);
gen(" = new ", baseType, "[0]");
eol();
} else {
gen(PRIVATE, "java.util.List", attr);
gen(" = new "+config.getIndexedPropertyType()+"();");
tabIn();
comment("List<"+baseType+">");
}
} else {
gen(PRIVATE, type, attr);
if (a.getDefaultValue() != null && (a.elementInstance == Common.TYPE_1 || a.elementInstance == Common.TYPE_1_N)) {
gen(" = ");
if (!JavaUtil.checkValueToType(type, a.getDefaultValue())) {
config.messageOut.println(Common.getMessage("MSG_NotAGoodValue", a.getDefaultValue(), type));
}
gen(JavaUtil.instanceFrom(type, a.getDefaultValue()));
}
eol();
}
select(ACCESS_SECTION);
comment("This attribute is ", Common.instanceToString(a.elementInstance));
// Generate setter
gen(sigs.findSignature(SETTER));
sp();
begin();
if (a.getPropertyInterface() != null) {
jw.writeEol(type+" value = ("+type+") valueInterface");
}
if (indexed) {
gen("if (value == null)");
cr();
tabIn();
if (baseType.equals("byte[]"))
jw.writeEol("value = new byte[0][0]");
else
jw.writeEol("value = new ", baseType, "[0]");
}
if (!indexed) {
SchemaRep.WhiteSpace ws = (SchemaRep.WhiteSpace) a.searchExtraData(SchemaRep.WhiteSpace.class);
if (ws != null)
genWhiteSpaceRestriction(ws, "value", baseType);
}
if (config.isGeneratePropertyEvents() || config.isVetoable()) {
if (indexed) {
jw.beginIf("value.length == "+a.getSizeMethod()+"()");
jw.writeEol("boolean same = true");
jw.beginFor("int i = 0", "i < value.length", "++i");
jw.beginIf("!("+JavaUtil.genEquals(type, "value[i]",
a.getReadMethod(true) + "(i)")+")");
jw.writeEol("same = false");
jw.writeEol("break");
jw.end();
jw.end();
jw.beginIf("same");
} else {
jw.beginIf(JavaUtil.genEquals(type, "value", attr));
}
jw.comment("No change.");
jw.writeEol("return");
jw.end();
if (indexed)
jw.end();
if (a.isBean) {
if (config.isGeneratePropertyEvents())
comment("Make the foreign beans take on our property change event listeners.");
if (config.isGenerateParentRefs())
comment("Maintain the parent reference.");
String iterVar = "value";
if (indexed) {
jw.beginFor("int i = 0", "i < value.length", "++i");
iterVar = "value[i]";
}
jw.beginIf(iterVar+" != null");
if (config.isGeneratePropertyEvents())
geneol(iterVar+"._setPropertyChangeSupport(eventListeners)");
if (config.isVetoable())
geneol(iterVar+"._setVetoableChangeSupport(vetos)");
if (config.isGenerateParentRefs())
jw.writeEol(iterVar+"._setParent(this)");
jw.end();
if (indexed)
jw.end();
}
jw.writeEol("java.beans.PropertyChangeEvent event = null");
gen("if (");
jw.setFirst(" || ");
if (config.isGeneratePropertyEvents()) {
jw.writeNext("eventListeners != null");
}
if (config.isGenerateStoreEvents()) {
jw.writeNext("storeEvents");
}
if (config.isVetoable()) {
jw.writeNext("vetos != null");
}
gen(") ");
begin();
if (indexed) {
jw.comment("See if only 1 thing changed.");
jw.writeEol("int addIndex = -1");
jw.writeEol("int removeIndex = -1");
jw.writeEol("int oldSize = size", a.name, "()");
jw.writeEol("int newSize = value.length");
jw.beginIf("oldSize + 1 == newSize || oldSize == newSize + 1");
jw.writeEol("boolean checkAddOrRemoveOne = true");
jw.writeEol("int oldIndex = 0, newIndex = 0");
jw.beginFor("",
"oldIndex < oldSize && newIndex < newSize",
"++newIndex, ++oldIndex");
//jw.writeEol("System.out.println(\"oldIndex=\"+oldIndex+\" newIndex=\"+newIndex)");
//jw.writeEol("System.out.println(\"addIndex=\"+addIndex+\" removeIndex=\"+removeIndex)");
jw.beginIf(JavaUtil.genEquals(baseType, "value[newIndex]",
a.getReadMethod(true)+"(oldIndex)"));
jw.comment("Same, so just continue.");
jw.endElseBeginIf("addIndex != -1 || removeIndex != -1");
jw.comment("More than 1 difference detected.");
jw.writeEol("addIndex = removeIndex = -1");
jw.writeEol("checkAddOrRemoveOne = false");
jw.writeEol("break");
jw.endElseBeginIf("oldIndex + 1 < oldSize && ("+JavaUtil.genEquals(baseType, "value[newIndex]", a.getReadMethod(true)+"(oldIndex+1)")+")");
jw.writeEol("removeIndex = oldIndex");
jw.writeEol("++oldIndex");
jw.endElseBeginIf("newIndex + 1 < newSize && ("+JavaUtil.genEquals(baseType, "value[newIndex+1]", a.getReadMethod(true)+"(oldIndex)")+")");
jw.writeEol("addIndex = newIndex");
jw.writeEol("++newIndex");
jw.endElseBegin();
jw.comment("More than 1 difference.");
jw.writeEol("addIndex = removeIndex = -1");
jw.writeEol("checkAddOrRemoveOne = false");
jw.writeEol("break");
jw.end();
jw.end(); // for
// Only do this check if we fell off the end (oldIndex == newIndex)
jw.beginIf("checkAddOrRemoveOne && addIndex == -1 && removeIndex == -1");
jw.beginIf("oldSize + 1 == newSize");
jw.comment("Added last one");
jw.writeEol("addIndex = oldSize");
jw.endElseBeginIf("oldSize == newSize + 1");
jw.comment("Removed last one");
jw.writeEol("removeIndex = newSize");
jw.end();
jw.end();
jw.end();
//jw.writeEol("System.out.println(\"addIndex=\"+addIndex+\" removeIndex=\"+removeIndex)");
jw.beginIf("addIndex >= 0");
jw.write("event = ");
genNewEvent(a, "addIndex", "null", "value[addIndex]", baseType);
jw.eol();
if (!isArrayStyle && !config.isVetoable() && !config.isKeepElementPositions() && !config.isGenerateStoreEvents()) {
SchemaRep.WhiteSpace ws = (SchemaRep.WhiteSpace) a.searchExtraData(SchemaRep.WhiteSpace.class);
if (ws != null)
genWhiteSpaceRestriction(ws, "value[addIndex]", baseType);
jw.writeEol(attr+".add(addIndex, value[addIndex])");
genMadeChange();
jw.writeEol("eventListeners.firePropertyChange(event)");
jw.writeEol("return");
}
jw.endElseBeginIf("removeIndex >= 0");
jw.write("event = ");
genNewEvent(a, "removeIndex", a.getReadMethod(true)+"(removeIndex)", "null", baseType);
jw.eol();
if (!isArrayStyle && !config.isVetoable() && !config.isKeepElementPositions() && !config.isGenerateStoreEvents()) {
jw.writeEol(attr+".remove(removeIndex)");
genMadeChange();
jw.writeEol("eventListeners.firePropertyChange(event)");
jw.writeEol("return");
}
jw.endElseBegin();
}
jw.write("event = ");
genNewEvent(a, indexed ? "-1" : "",
a.getReadMethod(false)+"()",
"value", type);
jw.eol();
end();
if (indexed) {
jw.end();
}
}
if (config.isVetoable()) {
gencr("if (vetos != null)");
tabIn();
geneol("vetos.fireVetoableChange(event)");
}
if (indexed) {
if (config.isKeepElementPositions()) {
jw.comment("Figure out where this type belongs.");
jw.writeEol("int elementCount = fetchChildCount()");
jw.writeEol("int destPos = 0");
jw.writeEol("int srcPos = 0");
// Remove all of the old entries
jw.beginFor("", "destPos < elementCount && srcPos < value.length",
"++destPos");
jw.beginIf("elementTypesByPosition[destPos] == "+i);
jw.comment("replace it");
jw.writeEol("elementsByPosition[destPos] = value[srcPos++]");
jw.end();
jw.end();
jw.comment("Handle when the replacement array is smaller.");
jw.beginWhile("destPos < elementCount");
jw.beginIf("elementTypesByPosition[destPos] == "+i);
jw.writeEol("deleteElement(destPos)");
jw.writeEol("--elementCount");
jw.endElseBegin();
jw.writeEol("++destPos");
jw.end();
jw.end();
jw.comment("Handle when replacement array is larger.");
jw.beginFor("", "srcPos < value.length", "++srcPos");
jw.writeEol("insertElementByPosition(destPos++, ",
JavaUtil.toObject("value[srcPos]", baseType,
config.isForME()),
", "+i+")");
jw.end();
}
if (isArrayStyle) {
jw.writeEol(attr, " = value");
} else {
jw.writeEol(attr, ".clear()");
if ("java.util.ArrayList".equals(config.getIndexedPropertyType())) {
jw.writeEol("((", config.getIndexedPropertyType(),
") "+attr, ").ensureCapacity(value.length)");
}
jw.beginFor("int i = 0", "i < value.length", "++i");
SchemaRep.WhiteSpace ws = (SchemaRep.WhiteSpace) a.searchExtraData(SchemaRep.WhiteSpace.class);
if (ws != null)
genWhiteSpaceRestriction(ws, "value[i]", baseType);
jw.write(attr, ".add(");
String objectValue = JavaUtil.toObject("value[i]", baseType,
config.isForME());
jw.writeEol(objectValue, ")");
jw.end();
}
} else {
geneol(attr+" = value");
if (config.isKeepElementPositions()) {
jw.comment("Figure out where this type belongs.");
jw.writeEol("int elementCount = fetchChildCount()");
jw.writeEol("int pos = findFirstOfElementType("+i+")");
if (!isScalar) {
jw.beginIf("value != null");
}
jw.beginIf("pos >= elementCount");
jw.comment("It's the last one to be added");
jw.writeEol("expandElementsByPosition(elementCount+1)");
jw.writeEol("elementTypesByPosition[pos] = "+i);
jw.end();
jw.writeEol("elementsByPosition[pos] = ",
JavaUtil.toObject("value", type,
config.isForME()));
if (!isScalar) {
jw.endElseBegin();
jw.beginIf("pos < elementCount");
jw.writeEol("deleteElement(pos)");
jw.end();
jw.end();
}
}
}
genMadeChange();
if (config.isGeneratePropertyEvents()) {
if (config.isGenerateStoreEvents()) {
gencr("if (storeEvents)");
tabIn();
geneol("storedEvents.add(event)");
gen("else ");
}
gencr("if (event != null)");
tabIn();
geneol("eventListeners.firePropertyChange(event)");
}
genResetMutuallyExclusive(a, true);
end();
cr();
if (indexed) {
gen(sigs.findSignature(SETTERINDEXED));
sp();
begin();
if (a.getPropertyInterface() != null) {
jw.writeEol(baseType+" value = ("+baseType+") valueInterface");
}
if (config.isGeneratePropertyEvents()) {
jw.beginIf(JavaUtil.genEquals(type, "value",
a.getReadMethod(true)+"(index)",
true));
jw.comment("No change.");
jw.writeEol("return");
jw.end();
}
if (a.isBean && config.isGenerateParentRefs()) {
jw.beginIf("value != null");
jw.writeEol("value._setParent(this)");
jw.end();
}
if (config.isGeneratePropertyEvents()) {
if (a.isBean) {
jw.beginIf("value != null");
comment("Make the foreign beans take on our property change event listeners.");
geneol("value._setPropertyChangeSupport(eventListeners)");
if (config.isVetoable())
geneol("value._setVetoableChangeSupport(vetos)");
jw.end();
}
gen("if (");
if (config.isGenerateStoreEvents()) {
gen("storeEvents || ");
}
gen("eventListeners != null) ");
begin();
jw.write("java.beans.PropertyChangeEvent event = ");
genNewEvent(a, "index", a.getReadMethod(true)+"(index)",
"value", baseType);
jw.eol();
if (config.isVetoable()) {
gencr("if (vetos != null)");
tabIn();
geneol("vetos.fireVetoableChange(event)");
}
if (config.isGenerateStoreEvents()) {
gencr("if (storeEvents)");
tabIn();
geneol("storedEvents.add(event)");
gencr("else");
tabIn();
}
geneol("eventListeners.firePropertyChange(event)");
end();
}
if (isArrayStyle) {
jw.writeEol(attr, "[index] = value");
} else {
if (!a.isDirectChild()) {
// Check to see if we need to grow before we set.
jw.beginFor("int size = "+attr+".size()",
"index >= size", "++size");
jw.writeEol(attr, ".add(null)");
jw.end();
}
jw.write(attr, ".set(index, ");
jw.write(JavaUtil.toObject("value", baseType, config.isForME()));
jw.writeEol(")");
}
if (config.isKeepElementPositions()) {
jw.writeEol("int pos = findElementType("+i+", index)");
jw.writeEol("elementsByPosition[pos] = ",
JavaUtil.toObject("value", baseType,
config.isForME()));
}
genMadeChange();
end();
cr();
}
// Generate getter
gen(sigs.findSignature(GETTER));
sp();
begin();
if (indexed && !isArrayStyle) {
if (baseType.equals("byte[]"))
jw.writeEol(type, " arr = new byte[", attr, ".size()][]");
else
jw.writeEol(type, " arr = new ", baseType+"["+attr, ".size()]");
if (isScalar) {
jw.beginFor("int i = 0", "i < arr.length", "++i");
jw.write("arr[i] = ");
jw.write(JavaUtil.fromObject(baseType, attr+".get(i)"));
jw.eol();
jw.end();
jw.write("return arr");
} else {
gen("return ("+type+") "+attr+".toArray(arr)");
}
} else
gen("return "+attr);
eol();
end();
cr();
if (indexed) {
if (!config.isMinFeatures() && !isArrayStyle) {
gen(sigs.findSignature(GETTERLIST));
sp();
begin();
gen("return "+attr);
eol();
end();
cr();
}
gen(sigs.findSignature(GETTERINDEXED));
sp();
begin();
jw.write("return ");
if (isArrayStyle) {
jw.writeEol(attr, "[index]");
} else {
jw.writeEol(JavaUtil.fromObject(baseType, attr+".get(index)"));
}
end();
cr();
comment("Return the number of "+propertyName);
gen(sigs.findSignature(SIZE));
sp();
begin();
if (isArrayStyle) {
jw.writeEol("return ", attr, ".length");
} else {
jw.writeEol("return ", attr, ".size()");
}
end();
cr();
if (!isArrayStyle) {
gen(sigs.findSignature(ADD));
sp();
begin();
if (a.getPropertyInterface() != null) {
jw.writeEol(baseType+" value = ("+baseType+") valueInterface");
}
if (a.isBean && config.isGenerateParentRefs()) {
jw.beginIf("value != null");
jw.writeEol("value._setParent(this)");
jw.end();
}
if (a.isBean && config.isGeneratePropertyEvents()) {
jw.beginIf("value != null");
comment("Make the foreign beans take on our property change event listeners.");
geneol("value._setPropertyChangeSupport(eventListeners)");
if (config.isVetoable())
geneol("value._setVetoableChangeSupport(vetos)");
jw.end();
}
jw.writeEol(attr, ".add(",
JavaUtil.toObject("value", baseType,
config.isForME()),
")");
if (config.isKeepElementPositions()) {
GraphLink gl = a.getGraphLink();
//jw.comment("gl="+gl);
//jw.comment("gl.lastInGroup="+gl.getLastInGroup());
//jw.comment("gl.lastInGroup.object="+gl.getLastInGroup().getObject());
int lastPropNum;
if (gl == null) {
lastPropNum = i;
} else {
Property lastProp = (Property) gl.getLastSibling().getObject();
if (lastProp == a) {
lastPropNum = i;
} else {
for (lastPropNum = 0; lastPropNum < size; ++lastPropNum)
if (attrList.get(lastPropNum) == lastProp)
break;
if (lastPropNum == size) {
jw.comment("Did not find lastPropNum");
lastPropNum = i;
}
}
}
jw.writeEol("int pos = findLastOfElementType("+lastPropNum+")+1");
jw.writeEol("insertElementByPosition(pos, ",
JavaUtil.toObject("value", baseType,
config.isForME()),
", "+i+")");
}
if (config.isGeneratePropertyEvents()) {
gen("if (");
if (config.isGenerateStoreEvents()) {
gen("storeEvents || ");
}
gen("eventListeners != null) ");
begin();
jw.write("java.beans.PropertyChangeEvent event = ");
genNewEvent(a, attr+".size()-1", "null",
"value", baseType);
jw.eol();
if (config.isVetoable()) {
gencr("if (vetos != null)");
tabIn();
geneol("vetos.fireVetoableChange(event)");
}
if (config.isGenerateStoreEvents()) {
gencr("if (storeEvents)");
tabIn();
geneol("storedEvents.add(event)");
gencr("else");
tabIn();
}
geneol("eventListeners.firePropertyChange(event)");
end();
}
jw.writeEol("int positionOfNewItem = "+attr+".size()-1");
if (isMutuallyExclusive(a)) {
jw.beginIf("positionOfNewItem == 0");
genResetMutuallyExclusive(a, false);
jw.end();
}
genMadeChange();
geneol("return positionOfNewItem");
end();
cr();
jw.bigComment("Search from the end looking for @param value, and then remove it.");
gen(sigs.findSignature(REMOVE));
sp();
begin();
if (a.getPropertyInterface() != null) {
jw.writeEol(baseType+" value = ("+baseType+") valueInterface");
}
jw.writeEol("int pos = ", attr, ".indexOf(",
JavaUtil.toObject("value", baseType,
config.isForME())+")");
gen("if (pos >= 0) ");
begin();
geneol(attr+".remove(pos)");
if (config.isKeepElementPositions()) {
jw.writeEol("int elementPos = findElementType("+i+", pos)");
jw.writeEol("deleteElement(elementPos)");
}
if (config.isGeneratePropertyEvents()) {
gen("if (");
if (config.isGenerateStoreEvents()) {
gen("storeEvents || ");
}
gen("eventListeners != null) ");
begin();
gen("java.beans.PropertyChangeEvent event = ");
genNewEvent(a, "pos", "value", "null", baseType);
jw.eol();
if (config.isVetoable()) {
gencr("if (vetos != null)");
tabIn();
geneol("vetos.fireVetoableChange(event)");
}
if (config.isGenerateStoreEvents()) {
gencr("if (storeEvents)");
tabIn();
geneol("storedEvents.add(event)");
gencr("else");
tabIn();
}
geneol("eventListeners.firePropertyChange(event)");
end();
}
end();
genMadeChange();
geneol("return pos");
end();
cr();
}
MetaProperty mp = getMetaProperty(a.name);
GraphNode graphNode = a.getGraphNode();
SchemaRep.Key key = null;
if (graphNode != null)
key = (SchemaRep.Key)
graphNode.searchExtraData(SchemaRep.Key.class);
if (a.isBean &&
((key != null) || (mp != null && mp.isKey()))) {
//System.out.println("mp for "+a.name);
//System.out.println(mp.dumpBeanNode());
config.messageOut.println("Found key: "+key);
SchemaRep.Selector selector = (SchemaRep.Selector)
key.findSubElement(SchemaRep.Selector.class);
SchemaRep.Field field = (SchemaRep.Field)
key.findSubElement(SchemaRep.Field.class);
genFinder(a, graphNode, attr, key.getElementName(),
baseType, a.name,
selector.getXPath(), field.getXPath(), false);
}
} // end if (indexed)
genDefaultsAccessable(a);
if (a.isBean) {
genNewMethod(a.getPropertyInterface(), baseType,
getTypeFullClassName(a));
}
}
if (config.isKeepElementPositions()) {
select(DECL_SECTION);
jw.writeEol("private java.lang.Object[] elementsByPosition = new java.lang.Object[0]"); // we might be storing String, int's, and beans in there.
jw.writeEol("private int[] elementTypesByPosition = new int[0]");
}
if (beanElement.isRoot && !config.isMinFeatures()) {
select(DECL_SECTION);
jw.write("private java.lang.String schemaLocation");
if (mdd.getSchemaLocation() != null) {
jw.write(" = ");
jw.write(JavaUtil.instanceFrom("java.lang.String",
mdd.getSchemaLocation()));
}
jw.eol();
select(ACCESS_SECTION);
jw.beginMethod("_setSchemaLocation", "String location", null, "void", jw.PUBLIC);
jw.writeEol("schemaLocation = location");
genMadeChange();
jw.end();
jw.cr();
jw.beginMethod("_getSchemaLocation", "", null, "String", jw.PUBLIC);
jw.writeEol("return schemaLocation");
jw.endMethod();
}
if (config.isGenerateParentRefs()) {
select(DECL_SECTION);
String parentType = parentBeanType();
jw.writeEol("private ", parentType, " parent");
select(BODY_SECTION);
jw.beginMethod("_setParent", parentType+" parent");
jw.writeEol("this.parent = parent");
jw.endMethod();
jw.beginMethod("_getXPathExpr", "", null, "String", jw.PUBLIC);
jw.beginIf("parent == null");
jw.writeEol("return \"/", beanElement.node.getName(), "\"");
jw.endElseBegin();
jw.writeEol("String parentXPathExpr = parent._getXPathExpr()");
jw.writeEol("String myExpr = parent.nameChild(this, false, false, true)");
jw.writeEol("return parentXPathExpr + \"/\" + myExpr");
jw.end();
jw.endMethod();
jw.beginMethod("_getXPathExpr", "Object childObj", null, "String", jw.PUBLIC);
jw.writeEol("String childName = nameChild(childObj, false, false, true)");
jw.beginIf("childName == null");
jw.writeEol("throw new IllegalArgumentException(\"childObj (\"+childObj.toString()+\") is not a child of this bean ("+className+").\")");
jw.end();
jw.writeEol("return _getXPathExpr() + \"/\" + childName");
jw.endMethod();
}
// Look for finders
for (Iterator it = beanElement.getGraphNode().extraDataIterator(); it.hasNext(); ) {
Object data = it.next();
if (data instanceof BeanBuilder.Finder) {
BeanBuilder.Finder finder = (BeanBuilder.Finder) data;
//System.out.println("Found finder: "+finder);
genFinder(beanElement.getGraphNode(), finder);
}
}
}
protected void genFinder(GraphNode startingGraphNode,
BeanBuilder.Finder finder) throws IOException {
genFinder(startingGraphNode,
finder.getFindExpr(), finder.getByExpr(),
finder.isListFindExpr());
}
protected void genFinder(GraphNode startingGraphNode,
String selectorXPath, String fieldXPath,
boolean isListFindExpr) throws IOException {
genFinder(null, startingGraphNode, null, null, null, null,
selectorXPath, fieldXPath, isListFindExpr);
}
protected void genFinder(Property a, GraphNode startingGraphNode,
String attr, String keyName, String returnType,
String nameToFind,
String selectorXPath, String fieldXPath,
boolean isListFindExpr) throws IOException {
String dtdName = null;
String keyVar = null;
String keyType = null;
String keyTypeInterface = null;
List xpathChain = null;
GraphNode graphNode = startingGraphNode;
Property selectorProp = null;
if (graphNode != null && graphNode.getGraphLink() != null) {
xpathChain = new LinkedList();
GraphLink gl = null;
for (Iterator it = graphNode.getGraphLink().xPathIterator(selectorXPath);
it.hasNext(); ) {
gl = (GraphLink) it.next();
//System.out.println("selector gl="+gl);
if (gl == null)
break;
if (gl.getObject() != null)
xpathChain.add(gl);
}
if (gl != null) {
GraphLink nextStartingLink;
if (gl.element != null) {
nextStartingLink = gl.element.getGraphLink();
} else {
nextStartingLink = gl;
}
selectorProp = (Property) gl.getObject();
if (!fieldXPath.equals(".")) {
//System.out.println("nextStartingLink="+nextStartingLink);
for (Iterator it = nextStartingLink.xPathIterator(fieldXPath);
it.hasNext(); ) {
gl = (GraphLink) it.next();
//System.out.println("field gl="+gl);
if (gl == null) {
break;
}
if (gl.getObject() != null)
xpathChain.add(gl);
}
}
if (gl != null) {
//
// Found the final one.
//
//System.out.println("gl="+gl+" gl.name="+gl.name);
Property finalProp = (Property) gl.getObject();
if (finalProp != null) {
dtdName = finalProp.dtdName;
keyVar = finalProp.instanceOf()+"Key";
keyType = finalProp.getType();
keyTypeInterface = finalProp.getPropertyInterface();
} else {
config.messageOut.println("Warning: finalProp=null while generating finder.");
}
}
}
if (gl == null)
xpathChain = null;
}
//System.out.println("dtdName="+dtdName);
if (dtdName == null) {
dtdName = fieldXPath;
keyVar = Common.convertNameInstance(dtdName);
keyType = "String";
jw.comment("Did not figure out proper expression to find the key. This method may not work.");
jw.comment("selectorXPath="+selectorXPath);
if (selectorProp == null) {
jw.comment(" Failed to find selector.");
} else {
jw.comment(" found selector property name="+selectorProp.dtdName);
}
jw.comment("fieldXPath="+fieldXPath);
xpathChain = null;
}
if (selectorProp != null) {
if (nameToFind == null)
nameToFind = Common.convertName(selectorProp.dtdName);
if (returnType == null) {
if (selectorProp.getPropertyInterface() == null)
returnType = selectorProp.getType();
else
returnType = selectorProp.getPropertyInterface();
}
}
if (keyName == null)
keyName = fieldXPath;
if (returnType == null)
returnType = "String";
if (isListFindExpr) {
returnType = "java.util.List/*<"+returnType+">*/";
jw.bigComment("Search for the key.\n@return all elements found that match.");
} else {
jw.bigComment("Search for the key.\n@return null if the key is not found.");
}
String methodName;
if (isListFindExpr)
methodName = "findAll"+nameToFind;
else
methodName = "find"+nameToFind;
if (!keyName.equals("."))
methodName = methodName+"By"+Common.convertName(keyName);
String arguments;
if (keyTypeInterface == null)
arguments = keyType+" "+keyVar;
else
arguments = keyTypeInterface+" "+keyVar+"Interface";
jw.beginMethod(methodName,
arguments, null, returnType,
jw.PUBLIC | jw.BEANINFO);
if (keyTypeInterface != null)
jw.writeEol(keyVar, " = ("+keyType, ") ", keyVar+"Interface");
if (isListFindExpr)
jw.writeEol("java.util.List _result = new java.util.ArrayList()");
String lastVar, topVar;
if (attr != null) {
beginAttrIterator(attr, a, "_el");
jw.beginIf("_el == null");
jw.writeEol("continue");
jw.end();
lastVar = "_el";
topVar = "_el";
} else {
lastVar = "this";
topVar = "null";
}
if (xpathChain != null) {
GraphLink gl = null;
int foundIndices = 0;
for (Iterator it = xpathChain.iterator();
it.hasNext(); ) {
gl = (GraphLink) it.next();
Property prop = (Property) gl.getObject();
String var = prop.instanceOf()+foundIndices;
if (attr == null && selectorProp == prop)
topVar = var;
if (prop.isIndexed()) {
++foundIndices;
jw.beginFor("int "+var+"Index = 0",
var+"Index < "+lastVar+".size"+prop.name+"()",
var+"Index++");
}
jw.write(prop.getType()+" "+var);
jw.write(" = (", prop.getType(), ") ");
jw.write(lastVar, ".");
jw.write(prop.getReadMethod(prop.isIndexed()));
if (prop.isIndexed())
jw.write("("+var+"Index)");
else
jw.write("()");
jw.eol();
jw.beginIf(var+" == null");
if (!it.hasNext()) {
jw.beginIf(keyVar, " == null");
if (isListFindExpr)
jw.writeEol("_result.add(", topVar, ")");
else
jw.writeEol("return ", topVar);
jw.end();
}
jw.writeEol("continue");
jw.end();
lastVar = var;
}
jw.beginIf(lastVar+".equals("+keyVar+")");
if (isListFindExpr)
jw.writeEol("_result.add(", topVar, ")");
else
jw.writeEol("return ", topVar);
jw.end();
for (; foundIndices > 0; --foundIndices)
jw.end();
}
if (attr != null)
jw.end(); // endAttrIterator
if (isListFindExpr)
jw.writeEol("return _result");
else
jw.writeEol("return ", JavaUtil.nullValueForType(returnType));
jw.endMethod();
}
public void genXMLIO() throws IOException {
select(BODY_SECTION);
String beanName = beanElement.node.getName();
if (beanElement.isRoot) {
if (!config.isStandalone()) {
jw.beginMethod("write", "org.openide.filesystems.FileObject fo",
"java.io.IOException", "void", jw.PUBLIC | jw.IO);
jw.writeEol("org.openide.filesystems.FileLock lock = fo.lock()");
jw.beginTry();
jw.writeEol("java.io.OutputStream out = fo.getOutputStream(lock)");
jw.writeEol("write(out)");
jw.writeEol("out.close()");
jw.endFinallyBegin();
jw.writeEol("lock.releaseLock()");
jw.end();
jw.endMethod();
jw.beginMethod("write", "org.openide.filesystems.FileObject dir, String filename",
"java.io.IOException", "void", jw.PUBLIC | jw.IO);
jw.writeEol("org.openide.filesystems.FileObject file = dir.getFileObject(filename)");
jw.beginIf("file == null");
jw.writeEol("file = dir.createData(filename)");
jw.end();
jw.writeEol("write(file)");
jw.endMethod();
}
jw.beginMethod("write", "java.io.File f",
"java.io.IOException", "void", jw.PUBLIC | jw.IO);
jw.writeEol("java.io.OutputStream out = new java.io.FileOutputStream(f)");
jw.beginTry();
jw.writeEol("write(out)");
jw.endFinallyBegin();
jw.writeEol("out.close()");
jw.end();
jw.endMethod();
jw.beginMethod("write", "java.io.OutputStream out",
"java.io.IOException", "void", jw.PUBLIC | jw.IO);
geneol("write(out, null)");
jw.endMethod();
jw.beginMethod("write", "java.io.OutputStream out, String encoding",
"java.io.IOException", "void", jw.PUBLIC | jw.IO);
geneol("java.io.Writer w");
jw.beginIf("encoding == null");
gen("encoding = \"UTF-8\"");
eolNoI18N();
end();
gen("w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(out, encoding))");
eol();
geneol("write(w, encoding)");
geneol("w.flush()");
jw.endMethod();
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.");
jw.beginMethod("write", "java.io.Writer out, String encoding",
"java.io.IOException", "void", jw.PUBLIC | jw.IO);
gen("out.write(\"\\n\")");
eolNoI18N();
if (config.isProcessDocType()) {
jw.beginIf("docType != null");
jw.writeEol("out.write(docType.toString())");
jw.writeEol("out.write(\"\\n\")");
jw.end();
}
jw.write("writeNode(out, \"", beanName, "\", \"\")");
eolNoI18N();
jw.endMethod();
}
jw.beginMethod("writeNode", "java.io.Writer out",
"java.io.IOException", "void", jw.PUBLIC | jw.IO);
jw.writeEol("String myName");
if (config.isGenerateParentRefs())
jw.beginIf("parent == null");
jw.writeEol("myName = \"", beanName, "\"");
if (config.isGenerateParentRefs()) {
jw.endElseBegin();
jw.writeEol("myName = parent.nameChild(this, false, true)");
jw.beginIf("myName == null");
jw.writeEol("myName = \"", beanName, "\"");
jw.end();
jw.end();
}
jw.write("writeNode(out, myName, \"\")");
eolNoI18N();
jw.endMethod();
jw.beginMethod("writeNode",
"java.io.Writer out, String nodeName, String indent",
"java.io.IOException", "void", jw.PUBLIC | jw.IO);
jw.writeEol("writeNode(out, nodeName, null, indent, new java.util.HashMap())");
jw.endMethod();
jw.bigComment("It's not recommended to call this method directly.");
jw.beginMethod("writeNode",
"java.io.Writer out, String nodeName, String namespace, String indent, java.util.Map namespaceMap",
"java.io.IOException", "void", jw.PUBLIC | jw.IO | jw.UNSUPPORTED);
int size = attrList.size();
Map namespaceToPrefixTable = new HashMap();
geneol("out.write(indent)");
outWrite("<");
jw.beginIf("namespace != null");
jw.writeEol("out.write((String)namespaceMap.get(namespace))");
outWrite(":");
jw.end();
geneol("out.write(nodeName)");
if (beanElement.isRoot && getDefaultNamespace() != null) {
jw.writeEolNoI18N("out.write(\" xmlns='\")");
jw.writeEolNoI18N("out.write("+JavaUtil.instanceFrom("java.lang.String", getDefaultNamespace())+")");
jw.writeEolNoI18N("out.write(\"'\")");
}
if (beanElement.isRoot) {
jw.beginIf("schemaLocation != null");
jw.writeEol("namespaceMap.put(\"http://www.w3.org/2001/XMLSchema-instance\", \"xsi\")");
namespaceToPrefixTable.put("http://www.w3.org/2001/XMLSchema-instance",
"xsi");
jw.writeEol("out.write(\" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='\")");
jw.writeEol("out.write(schemaLocation)");
jw.writeEolNoI18N("out.write(\"'\")");
jw.end();
}
// Deal with namespaces
boolean firstNS = true;
for (int i = 0; i < size; i++) {
Property a = (Property) attrList.get(i);
boolean indexed = a.isIndexed();
String attr = "_" + a.name;
String type = a.getType().intern();
String baseType = type;
if (indexed)
type = (baseType + "[]").intern();
if (isTypeQName(baseType)) {
if (firstNS) {
firstNS = false;
jw.comment("Work out any namespaces.");
jw.writeEol("boolean firstNSAddition = true");
}
if (indexed) {
beginAttrIterator(attr, a, "element");
attr = "element";
}
jw.beginIf(attr+" != null && "+
attr+".getNamespaceURI() != null && !\"\".equals(",
attr, ".getNamespaceURI())");
jw.writeEol("String prefix = (String) namespaceMap.get(", attr, ".getNamespaceURI())");
jw.beginIf("prefix == null || \"\".equals(prefix)");
jw.writeEol("prefix = ", attr, ".getPrefix()");
jw.beginIf("prefix == null || \"\".equals(prefix)");
jw.writeEol("prefix = \"", a.dtdName, "_ns__\"");
jw.end();
jw.comment("Need to make sure it's a unique prefix too.");
jw.writeEol("boolean changed");
jw.write("do ");
jw.begin();
jw.writeEol("changed = false");
jw.beginFor("java.util.Iterator valueIt = namespaceMap.values().iterator()",
"valueIt.hasNext()", "");
jw.writeEol("String otherPrefix = (String) valueIt.next()");
jw.beginIf("prefix.equals(otherPrefix)");
jw.writeEol("prefix += \"_\"");
jw.writeEol("changed = true");
jw.end();
jw.end();
jw.end(false);
jw.writeEol(" while (changed)");
jw.beginIf("firstNSAddition");
jw.writeEol("firstNSAddition = false");
jw.comment("Copy on write");
jw.writeEol("namespaceMap = new java.util.HashMap(namespaceMap)");
jw.end();
jw.writeEol("namespaceMap.put(", attr,
".getNamespaceURI(), prefix)");
jw.writeEol("out.write(\" xmlns:\")");
jw.writeEol("out.write(prefix)");
jw.writeEol("out.write(\"='\")");
jw.writeEol("out.write(", attr, ".getNamespaceURI())");
jw.writeEol("out.write(\"'\")");
jw.end();
jw.end();
if (indexed)
jw.end();
} else if (a.getNamespace() != null && !a.getNamespace().equals(getDefaultNamespace()) && !a.getNamespace().equals("http://www.w3.org/XML/1998/namespace")) {
if (namespaceToPrefixTable.containsKey(a.getNamespace()))
continue;
if (firstNS) {
firstNS = false;
jw.comment("Work out any namespaces.");
jw.writeEol("boolean firstNSAddition = true");
}
String prefix = SchemaRep.namespaceOf(a.dtdName);
if (prefix == null) {
prefix = SchemaRep.guessPrefix(a.getNamespace());
//config.messageOut.println("Guessing prefix for "+a.getNamespace()+" is "+prefix);
}
jw.beginIf("namespaceMap.get(",
JavaUtil.instanceFrom("String",
a.getNamespace()),
") == null");
jw.beginIf("firstNSAddition");
jw.writeEol("firstNSAddition = false");
jw.comment("Copy on write");
jw.writeEol("namespaceMap = new java.util.HashMap(namespaceMap)");
jw.end();
jw.writeEol("namespaceMap.put(",
JavaUtil.instanceFrom("String",
a.getNamespace()),
", \"", prefix+"\")");
outWrite(" xmlns:"+prefix+"='");
outWrite(a.getNamespace());
outWrite("'");
jw.end();
namespaceToPrefixTable.put(a.getNamespace(), prefix);
}
}
List nonDirectAttributes = new LinkedList(); // List
|
| ... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.