public ClassMapping(string classPackage, MappingElement parentElement, ClassName superClass, ClassMapping superClassMapping, Element classElement, MultiMap inheritedMeta) : this(classPackage, parentElement, superClass, classElement, inheritedMeta) { this.superClassMapping = superClassMapping; if (this.superClassMapping != null) { AddImport(superClassMapping.FullyQualifiedName); SupportClass.ListCollectionSupport l = this.superClassMapping.AllFieldsForFullConstructor; for (IEnumerator iter = l.GetEnumerator(); iter.MoveNext();) { FieldProperty element = (FieldProperty) iter.Current; ClassName ct = element.ClassType; if (ct != null) { // add imports for superclasses possible fields. //addImport(ct); } else { //addImport(element.FullyQualifiedTypeName); } } } }
public virtual string GetPackageDeclaration(string savedToPackage, ClassMapping classMapping) { if ((Object) savedToPackage != null && !savedToPackage.Trim().Equals("")) { return "namespace " + savedToPackage + ""; } else if ((Object) classMapping.GeneratedPackageName != null) { return "namespace " + classMapping.GeneratedPackageName + ""; } return ""; }
protected internal virtual void GeneratePackageDelaration(string savedToPackage, ClassMapping classMapping, StreamWriter w) { string string_Renamed = GetPackageDeclaration(savedToPackage, classMapping); if (string_Renamed.Length > 0) { w.WriteLine(string_Renamed); } else { w.WriteLine("// default package"); } }
public virtual string FieldsAsArguments(SupportClass.ListCollectionSupport fieldslist, ClassMapping classMapping, IDictionary class2classmap) { StringBuilder buf = new StringBuilder(); bool first = true; for (IEnumerator fields = fieldslist.GetEnumerator(); fields.MoveNext();) { if (first) first = false; else buf.Append(", "); FieldProperty field = (FieldProperty) fields.Current; buf.Append(field.fieldcase); } return buf.ToString(); }
public virtual string GenerateImports(ClassMapping classMapping) { StringBuilder buf = new StringBuilder(); for (IEnumerator imports = classMapping.Imports.GetEnumerator(); imports.MoveNext();) { buf.Append("using " + imports.Current + ";\n"); } SupportClass.ListCollectionSupport imports2 = classMapping.GetMeta("extra-import"); if (imports2 != null) { for (IEnumerator it = imports2.GetEnumerator(); it.MoveNext();) { string cname = it.Current.ToString(); buf.Append("using " + cname + ";\n"); } } return buf.ToString(); }
private static void HandleClass(string classPackage, MappingElement me, Hashtable classMappings, IEnumerator classElements, MultiMap mm, bool extendz) { while (classElements.MoveNext()) { Element clazz = (Element) classElements.Current; if (!extendz) { ClassMapping cmap = new ClassMapping(classPackage, clazz, me, mm); SupportClass.PutElement(classMappings, cmap.FullyQualifiedName, cmap); SupportClass.PutElement(allMaps, cmap.FullyQualifiedName, cmap); } else { string ex = clazz.Attributes["extends"] == null ? null : clazz.Attributes["extends"].Value; if ((object) ex == null) { throw new MappingException("Missing extends attribute on <" + clazz.LocalName + " name=" + clazz.Attributes["name"].Value + ">"); } int commaIndex = ex.IndexOf(','); if (commaIndex > -1) { //suppress the leading AssemblyName ex = ex.Substring(0, commaIndex).Trim(); } ClassMapping superclass = (ClassMapping) allMaps[ex]; if (superclass == null) { // Haven't seen the superclass yet, so record this and process at the end SubclassMapping orphan = new SubclassMapping(classPackage, me, ex, clazz, mm); children.Add(orphan); } else { ClassMapping subclassMapping = new ClassMapping(classPackage, me, superclass.ClassName, superclass, clazz, mm); superclass.AddSubClass(subclassMapping); SupportClass.PutElement(allMaps, subclassMapping.FullyQualifiedName, subclassMapping); } } } }
public virtual int DoFieldAccessors(ClassMapping classMapping, IDictionary class2classmap, StringWriter writer, string vetoSupport, string changeSupport) { int fieldTypes = ORDINARY; if (classMapping.SuperInterface) { fieldTypes = DoFields(classMapping, class2classmap, writer, vetoSupport, changeSupport, fieldTypes, classMapping.AllFields); } SupportClass.ListCollectionSupport fieldz = classMapping.Fields; fieldTypes = DoFields(classMapping, class2classmap, writer, vetoSupport, changeSupport, fieldTypes, fieldz); return fieldTypes; }
public virtual string FieldsAsParameters(SupportClass.ListCollectionSupport fieldslist, ClassMapping classMapping, IDictionary class2classmap) { StringBuilder buf = new StringBuilder(); bool first = true; for (IEnumerator fields = fieldslist.GetEnumerator(); fields.MoveNext();) { if (first) first = false; else buf.Append(", "); FieldProperty field = (FieldProperty) fields.Current; buf.Append(ShortenType(field.FullyQualifiedTypeName, classMapping.Imports) + " " + field.fieldcase); } return buf.ToString(); }
public virtual bool HasImplements(ClassMapping cmap) { return GetImplements(cmap).Length != 0; }
/// <summary> Returns "package packagename;" where packagename is either the declared packagename, /// or the one provide via meta attribute "generated-class". /// /// Returns "// default package" if no package declarition available. /// /// </summary> /// <returns> /// </returns> public virtual string GetPackageDeclaration(ClassMapping cm) { if ((object) cm.GeneratedPackageName != null) { return "namespace " + cm.GeneratedPackageName + ""; } else { return "// default namespace"; } }
/// <summary> Method doSupports.</summary> /// <param name="vetoSupport"> /// </param> /// <param name="changeSupport"> /// </param> /// <param name="writer"> /// </param> private void DoSupports(int fieldTypes, ClassMapping classMapping, string vetoSupport, string changeSupport, StringWriter writer) { if ((fieldTypes & CONSTRAINT) == CONSTRAINT) { writer.WriteLine(" private VetoableChangeSupport " + vetoSupport + " = new VetoableChangeSupport(this);"); writer.WriteLine(); } if ((fieldTypes & BOUND) == BOUND) { writer.WriteLine(" private PropertyChangeSupport " + changeSupport + " = new PropertyChangeSupport(this);"); writer.WriteLine(); } }
private int DoFields(ClassMapping classMapping, IDictionary class2classmap, StringWriter writer, string vetoSupport, string changeSupport, int fieldTypes, SupportClass.ListCollectionSupport fieldz) { // field accessors for (IEnumerator fields = fieldz.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty) fields.Current; if (field.GeneratedAsProperty) { // getter string getAccessScope = GetFieldScope(field, "scope-get", "public"); if (field.GetMeta("field-description") != null) { //writer.WriteLine(" /** \n" + languageTool.toJavaDoc(field.getMetaAsString("field-description"), 4) + " */"); writer.WriteLine(" /// <summary>\n" + languageTool.ToJavaDoc(field.GetMetaAsString("field-description"), 4) + "\n /// </summary>"); } writer.Write(" " + getAccessScope + " virtual " + field.FullyQualifiedTypeName + " " + field.Propcase); if (classMapping.Interface) { writer.WriteLine(";"); } else { writer.WriteLine(); writer.WriteLine(" {"); writer.WriteLine(" get { return this." + field.fieldcase + "; }"); //writer.WriteLine(" {"); //writer.WriteLine(" return this." + field.FieldName + ";"); //writer.WriteLine(" }"); } // setter int fieldType = 0; if (field.GetMeta("beans-property-type") != null) { string beansPropertyType = field.GetMetaAsString("beans-property-type").Trim().ToLower(); if (beansPropertyType.Equals("constraint")) { fieldTypes = (fieldTypes | CONSTRAINT); fieldType = CONSTRAINT; } else if (beansPropertyType.Equals("bound")) { fieldTypes = (fieldTypes | BOUND); fieldType = BOUND; } } string setAccessScope = GetFieldScope(field, "scope-set", "public"); writer.Write(" set"); writer.Write((fieldType & CONSTRAINT) == CONSTRAINT ? " throws PropertyVetoException " : ""); if (classMapping.Interface) { writer.WriteLine(";"); } else { writer.WriteLine(); writer.WriteLine(" {"); if ((fieldType & CONSTRAINT) == CONSTRAINT || (fieldType & BOUND) == BOUND) { writer.WriteLine(" object oldValue = " + GetFieldAsObject(true, field) + ";"); } if ((fieldType & CONSTRAINT) == CONSTRAINT) { writer.WriteLine(" " + vetoSupport + ".fireVetoableChange(\"" + field.fieldcase + "\","); writer.WriteLine(" oldValue,"); writer.WriteLine(" " + GetFieldAsObject(false, field) + ");"); } writer.WriteLine(" this." + field.fieldcase + " = value;"); if ((fieldType & BOUND) == BOUND) { writer.WriteLine(" " + changeSupport + ".firePropertyChange(\"" + field.fieldcase + "\","); writer.WriteLine(" oldValue,"); writer.WriteLine(" " + GetFieldAsObject(false, field) + ");"); } writer.WriteLine(" }"); } writer.WriteLine(" }"); writer.WriteLine(); // add/remove'rs (commented out for now) /* if(field.getForeignClass()!=null) { ClassName foreignClass = field.getForeignClass(); string trueforeign = getTrueTypeName(foreignClass, class2classmap); classMapping.addImport(trueforeign); // Try to identify the matching set method on the child. ClassMapping forignMap = (ClassMapping) class2classmap.get(foreignClass.getFullyQualifiedName()); if(forignMap!=null) { Iterator foreignFields = forignMap.getFields().iterator(); while (foreignFields.hasNext()) { Field ffield = (Field) foreignFields.next(); if(ffield.isIdentifier()) { log.Debug("Trying to match " + ffield.getName() + " with " + field.getForeignKeys()); } } } else { log.Error("Could not find foreign class's mapping - cannot provide bidirectional setters!"); } string addAccessScope = getFieldScope(field, "scope", "scope-add"); writer.println(" " + setAccessScope + " void add" + field.getAsSuffix() + StringHelper.OPEN + shortenType(trueforeign, classMapping.getImports()) + " a" + field.getName() + ") {"); writer.println(" this." + getterType + field.getAsSuffix() + "().add(a" + field.getName() + ");"); writer.println(" a" + field.getName() + ".setXXX(this);"); writer.println(" }"); writer.println(); } */ } } return fieldTypes; }
public virtual void DoConstructors(string savedToClass, ClassMapping classMapping, IDictionary class2classmap, StringWriter writer) { // full constructor SupportClass.ListCollectionSupport allFieldsForFullConstructor = classMapping.AllFieldsForFullConstructor; writer.WriteLine(" /// <summary>\n /// full constructor\n /// </summary>"); string fullCons = " public " + savedToClass + StringHelper.OpenParen; fullCons += languageTool.FieldsAsParameters(allFieldsForFullConstructor, classMapping, class2classmap); writer.Write(fullCons + ")"); //invoke super to initialize superclass... SupportClass.ListCollectionSupport supersConstructorFields = classMapping.FieldsForSupersFullConstructor; if (!(supersConstructorFields.Count == 0)) { writer.Write(" : base("); bool first = true; for (IEnumerator fields = supersConstructorFields.GetEnumerator(); fields.MoveNext();) { if (first) first = false; else writer.Write(", "); FieldProperty field = (FieldProperty) fields.Current; writer.Write(field.FieldName); } writer.Write(")"); } writer.WriteLine(); writer.WriteLine(" {"); // initialisation of localfields for (IEnumerator fields = classMapping.LocalFieldsForFullConstructor.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty) fields.Current; if (field.GeneratedAsProperty) { writer.WriteLine(" this." + field.FieldName + " = " + field.FieldName + ";"); } } writer.WriteLine(" }"); writer.WriteLine(); // no args constructor (if fullconstructor had any arguments!) if (allFieldsForFullConstructor.Count > 0) { writer.WriteLine(" /// <summary>\n /// default constructor\n /// </summary>"); writer.WriteLine(" public " + savedToClass + "() {"); writer.WriteLine(" }"); writer.WriteLine(); } // minimal constructor (only if the fullconstructor had any arguments) if ((allFieldsForFullConstructor.Count > 0) && classMapping.NeedsMinimalConstructor()) { SupportClass.ListCollectionSupport allFieldsForMinimalConstructor = classMapping.AllFieldsForMinimalConstructor; writer.WriteLine(" /// <summary>\n /// minimal constructor\n /// </summary>"); string minCons = " public " + savedToClass + "("; bool first = true; for (IEnumerator fields = allFieldsForMinimalConstructor.GetEnumerator(); fields.MoveNext();) { if (first) first = false; else minCons = minCons + ", "; FieldProperty field = (FieldProperty) fields.Current; minCons = minCons + LanguageTool.ShortenType(LanguageTool.GetTrueTypeName(field, class2classmap), classMapping.Imports) + " " + field.FieldName; } writer.Write(minCons + ")"); // invoke super to initialize superclass... SupportClass.ListCollectionSupport supersMinConstructorFields = classMapping.FieldsForSupersMinimalConstructor; if (!(supersMinConstructorFields.Count == 0)) { writer.Write(" : base("); bool first2 = true; for (IEnumerator fields = supersMinConstructorFields.GetEnumerator(); fields.MoveNext();) { if (first2) first2 = false; else writer.Write(StringHelper.CommaSpace); FieldProperty field = (FieldProperty) fields.Current; writer.Write(field.FieldName); } writer.Write(")"); } writer.WriteLine(); writer.WriteLine(" {"); // initialisation of localfields for (IEnumerator fields = classMapping.LocalFieldsForMinimalConstructor.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty) fields.Current; if (field.GeneratedAsProperty) { writer.WriteLine(" this." + field.FieldName + " = " + field.FieldName + ";"); } } writer.WriteLine(" }"); writer.WriteLine(); } }
public override void Render(string savedToPackage, string savedToClass, ClassMapping classMapping, IDictionary class2classmap, StreamWriter mainwriter) { mainwriter.WriteLine("using System;"); mainwriter.WriteLine( @"//------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> //------------------------------------------------------------------------------ "); GeneratePackageDelaration(savedToPackage, classMapping, mainwriter); mainwriter.WriteLine("{"); // switch to another writer to be able to insert the actually // used imports when whole class has been rendered. StringWriter writer = new StringWriter(); // class declaration if (classMapping.GetMeta("class-description") == null) { writer.WriteLine( @" /// <summary> /// POJO for {0} /// </summary> /// <remark> /// This class is autogenerated /// </remark> ", classMapping.ClassName); } else { writer.WriteLine("/// <summary>\n" + languageTool.ToJavaDoc(classMapping.GetMetaAsString("class-description"), 0) + "\n/// </summary>"); } string classScope = classMapping.Scope; string declarationType = classMapping.DeclarationType; //classMapping.addImport(typeof(System.Runtime.Serialization.ISerializable)); //string modifiers = classMapping.getModifiers(); if (classMapping.ShouldBeAbstract() && (classScope.IndexOf("abstract") == - 1)) { writer.Write("abstract " + classScope + " " + declarationType + " " + savedToClass); } else { writer.Write(classScope + " " + declarationType + " " + savedToClass); } if (languageTool.HasExtends(classMapping) || languageTool.HasImplements(classMapping)) { writer.Write(" : "); } if (languageTool.HasExtends(classMapping)) { writer.Write(languageTool.GetExtends(classMapping)); } if (languageTool.HasExtends(classMapping) && languageTool.HasImplements(classMapping)) { writer.Write(", "); } if (languageTool.HasImplements(classMapping)) { writer.Write(languageTool.GetImplements(classMapping)); } writer.WriteLine(" {"); writer.WriteLine(); // switch to another writer to be able to insert the // veto- and changeSupport fields StringWriter propWriter = new StringWriter(); if (!classMapping.Interface) { DoFields(classMapping, class2classmap, propWriter); DoConstructors(savedToClass, classMapping, class2classmap, propWriter); } string vetoSupport = MakeSupportField("vetos", classMapping.AllFields); string changeSupport = MakeSupportField("changes", classMapping.AllFields); int fieldTypes = DoFieldAccessors(classMapping, class2classmap, propWriter, vetoSupport, changeSupport); if (!classMapping.Interface) { DoSupportMethods(fieldTypes, vetoSupport, changeSupport, propWriter); DoToString(classMapping, propWriter); DoEqualsAndHashCode(savedToClass, classMapping, propWriter); } if (classMapping.GetMeta("class-code") != null) { propWriter.WriteLine("// The following is extra code specified in the hbm.xml files"); SupportClass.ListCollectionSupport extras = classMapping.GetMeta("class-code"); IEnumerator iter = extras.GetEnumerator(); while (iter.MoveNext()) { string code = iter.Current.ToString(); propWriter.WriteLine(code); } propWriter.WriteLine("// end of extra code specified in the hbm.xml files"); } propWriter.WriteLine("}"); //insert change and VetoSupport if (!classMapping.Interface) { DoSupports(fieldTypes, classMapping, vetoSupport, changeSupport, writer); } writer.Write(propWriter.ToString()); // finally write the imports DoImports(classMapping, mainwriter); mainwriter.Write(writer.ToString()); mainwriter.WriteLine("\n}"); }
public virtual void DoToString(ClassMapping classMapping, StringWriter writer) { writer.WriteLine(" public override string ToString()"); writer.WriteLine(" {"); writer.WriteLine(" System.Text.StringBuilder sb = new System.Text.StringBuilder();"); for (IEnumerator fields = classMapping.AllFields.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty) fields.Current; // If nothing is stated about id then include it in toString() if (field.Identifier && field.GetMeta("use-in-tostring") == null) { writer.WriteLine(" sb.AppendFormat(\"{0}={{0}} \", {0});", field.fieldcase); } else if (field.GetMetaAsBool("use-in-tostring")) { writer.WriteLine(" sb.AppendFormat(\"{0}={{0}} \", {0});", field.fieldcase); } } writer.WriteLine(" return sb.ToString();"); writer.WriteLine(" }"); writer.WriteLine(); }
public virtual void DoImports(ClassMapping classMapping, StreamWriter writer) { writer.WriteLine(languageTool.GenerateImports(classMapping)); writer.WriteLine(); }
public virtual void DoFields(ClassMapping classMapping, IDictionary class2classmap, StringWriter writer) { // fields if (!classMapping.Interface) { if (classMapping.SuperInterface) { DoFields(classMapping.AllFields, classMapping.Imports, class2classmap, writer); } } SupportClass.ListCollectionSupport fieldList = classMapping.Fields; SupportClass.SetSupport imports = classMapping.Imports; DoFields(fieldList, imports, class2classmap, writer); }
public virtual string GetExtends(ClassMapping cmap) { string extendz = string.Empty; if (cmap.Interface) { if (cmap.SuperClassMapping != null && cmap.SuperClassMapping.Interface) { extendz += cmap.SuperClassMapping.Name; } if (cmap.GetMeta(extendz) != null) { if ((Object) extendz != null) { extendz += ","; } extendz = cmap.GetMetaAsString("extends"); } } else if ((Object) cmap.SuperClass != null) { if (cmap.SuperClassMapping != null && cmap.SuperClassMapping.Interface) { // class cannot extend it's superclass because the superclass is marked as an interface } else { extendz = cmap.SuperClass; } } else if (cmap.GetMeta("extends") != null) { extendz = cmap.GetMetaAsString("extends"); } return extendz; }
public virtual string GetImplements(ClassMapping cmap) { SupportClass.ListCollectionSupport interfaces = new SupportClass.ListCollectionSupport(); // implement proxy, but NOT if the proxy is the class it self! if ((Object) cmap.Proxy != null && (!cmap.Proxy.Equals(cmap.FullyQualifiedName))) { interfaces.Add(cmap.Proxy); } if (!cmap.Interface) { if (cmap.SuperClassMapping != null && cmap.SuperClassMapping.Interface) { interfaces.Add(cmap.SuperClassMapping.ClassName.FullyQualifiedName); } if (cmap.GetMeta("implements") != null) { interfaces.AddAll(cmap.GetMeta("implements")); } //interfaces.Add(typeof(System.Runtime.Serialization.ISerializable).FullName); } else { // interfaces can't implement suff } if (interfaces.Count > 0) { StringBuilder sbuf = new StringBuilder(); bool first = true; for (IEnumerator iter = interfaces.GetEnumerator(); iter.MoveNext();) { if (first) first = false; else sbuf.Append(","); sbuf.Append(ShortenType(iter.Current.ToString(), cmap.Imports)); } return sbuf.ToString(); } else { return string.Empty; } }
public virtual void AddSubClass(ClassMapping subclassMapping) { subclasses.Add(subclassMapping); }
public virtual bool HasExtends(ClassMapping cmap) { return GetExtends(cmap).Length != 0; }
protected internal virtual void InitWith(string classPackage, ClassName mySuperClass, Element classElement, bool component, MultiMap inheritedMeta) { IsComponent = component; string fullyQualifiedName = (classElement.Attributes[component ? "class" : "name"] == null ? string.Empty : classElement.Attributes[component ? "class" : "name"].Value); if (fullyQualifiedName.IndexOf('.') < 0 && (object) classPackage != null && classPackage.Trim().Length > 0) { fullyQualifiedName = classPackage + "." + fullyQualifiedName; } log.Debug("Processing mapping for class: " + fullyQualifiedName); MetaAttribs = MetaAttributeHelper.LoadAndMergeMetaMap(classElement, inheritedMeta); // class & package names name = new ClassName(fullyQualifiedName); if (GetMeta("generated-class") != null) { generatedName = new ClassName(GetMetaAsString("generated-class").Trim()); shouldBeAbstract_Renamed_Field = true; log.Warn("Generating " + generatedName + " instead of " + name); } else { generatedName = name; } XmlAttribute @abstract = classElement.Attributes["abstract"]; if (null != @abstract) { bool.TryParse(@abstract.Value, out shouldBeAbstract_Renamed_Field); } if (mySuperClass != null) { this.superClass = mySuperClass.Name; AddImport(mySuperClass); // can only be done AFTER this class gets its own name. } // get the properties defined for this class SupportClass.ListCollectionSupport propertyList = new SupportClass.ListCollectionSupport(); propertyList.AddAll(classElement.SelectNodes("urn:property", CodeGenerator.nsmgr)); propertyList.AddAll(classElement.SelectNodes("urn:version", CodeGenerator.nsmgr)); propertyList.AddAll(classElement.SelectNodes("urn:timestamp", CodeGenerator.nsmgr)); propertyList.AddAll(classElement.SelectNodes("urn:key-property", CodeGenerator.nsmgr)); propertyList.AddAll(classElement.SelectNodes("urn:any", CodeGenerator.nsmgr)); // get the properties inside a <join/> mapping... var joins = classElement.SelectNodes("urn:join",CodeGenerator.nsmgr); foreach (XmlNode join in joins) { propertyList.AddAll( join.SelectNodes("urn:property", CodeGenerator.nsmgr)); } // get all many-to-one associations defined for the class SupportClass.ListCollectionSupport manyToOneList = new SupportClass.ListCollectionSupport(); manyToOneList.AddAll(classElement.SelectNodes("urn:many-to-one", CodeGenerator.nsmgr)); manyToOneList.AddAll(classElement.SelectNodes("urn:key-many-to-one", CodeGenerator.nsmgr)); XmlAttribute att = classElement.Attributes["proxy"]; if (att != null) { proxyClass = att.Value; if (proxyClass.IndexOf(",") > 0) proxyClass = proxyClass.Substring(0, proxyClass.IndexOf(",")); } Element id = classElement["id"]; if (id != null) { propertyList.Insert(0, id); // implementEquals(); } // composite id Element cmpid = classElement["composite-id"]; if (cmpid != null) { string cmpname = (cmpid.Attributes["name"] == null ? null : cmpid.Attributes["name"].Value); string cmpclass = (cmpid.Attributes["class"] == null ? null : cmpid.Attributes["class"].Value); if ((Object) cmpclass == null || cmpclass.Equals(string.Empty)) { //Embedded composite id //implementEquals(); propertyList.AddAll(0, cmpid.SelectNodes("urn:key-property", CodeGenerator.nsmgr)); manyToOneList.AddAll(0, cmpid.SelectNodes("urn:key-many-to-one", CodeGenerator.nsmgr)); if( manyToOneList.Count == 0 ) ImplementEquals(); } else { //Composite id class ClassMapping mapping = new ClassMapping(classPackage, cmpid, this, true, MetaAttribs); MultiMap metaForCompositeid = MetaAttributeHelper.LoadAndMergeMetaMap(cmpid, MetaAttribs); mapping.ImplementEquals(); ClassName classType = new ClassName(cmpclass); // add an import and field for this property AddImport(classType); if (cmpname != null) { FieldProperty cmpidfield = new FieldProperty(cmpid, this, cmpname, classType, false, true, false, metaForCompositeid); AddFieldProperty(cmpidfield); } else { //composite id with class MUST have a property name associated with... log.Error("Composite id with class MUST have a property name. In:"+mapping.Name); } object tempObject; tempObject = mapping; components[mapping.FullyQualifiedName] = tempObject; } } // checked after the default sets of implement equals. if (GetMetaAsBool("implement-equals")) { ImplementEquals(); } // derive the class imports and fields from the properties for (IEnumerator properties = propertyList.GetEnumerator(); properties.MoveNext();) { Element property = (Element) properties.Current; MultiMap metaForProperty = MetaAttributeHelper.LoadAndMergeMetaMap(property, MetaAttribs); string propertyName = (property.Attributes["name"] == null ? null : property.Attributes["name"].Value); if ((Object) propertyName == null || propertyName.Trim().Equals(string.Empty)) { continue; //since an id doesn't necessarily need a name } // ensure that the type is specified string type = (property.Attributes["type"] == null ? null : property.Attributes["type"].Value); if ((Object) type == null && cmpid != null) { // for composite-keys type = (property.Attributes["class"] == null ? null : property.Attributes["class"].Value); } if ("timestamp".Equals(property.LocalName)) { type = "System.DateTime"; } if ("any".Equals(property.LocalName)) { type = "System.Object"; } if ((Object) type == null || type.Trim().Equals(string.Empty)) { if (property == id) { Element generator = property["generator"]; string generatorClass = generator.Attributes["class"] == null ? string.Empty : generator.Attributes["class"].Value; switch (generatorClass) { case "uuid.hex": type = "String"; break; case "guid": case "guid.native": case "guid.comb": type = "Guid"; break; default: type = "Int32"; break; } } else type = "String"; log.Warn("property \"" + propertyName + "\" in class " + Name + " is missing a type attribute, guessing " + type); } // handle in a different way id and properties... // ids may be generated and may need to be of object type in order to support // the unsaved-value "null" value. // Properties may be nullable (ids may not) if (property == id) { Element generator = property["generator"]; string unsavedValue = (property.Attributes["unsaved-value"] == null ? null : property.Attributes["unsaved-value"].Value); bool mustBeNullable = ((Object) unsavedValue != null && unsavedValue.Equals("null")); bool generated = !(generator.Attributes["class"] == null ? string.Empty : generator.Attributes["class"].Value).Equals("assigned"); ClassName rtype = GetFieldType(type, mustBeNullable, false); AddImport(rtype); FieldProperty idField = new FieldProperty(property, this, propertyName, rtype, false, true, generated, metaForProperty); AddFieldProperty(idField); } else { string notnull = (property.Attributes["not-null"] == null ? null : property.Attributes["not-null"].Value); // if not-null property is missing lets see if it has been // defined at column level if ((Object) notnull == null) { Element column = property["column"]; if (column != null) notnull = (column.Attributes["not-null"] == null ? null : column.Attributes["not-null"].Value); } bool nullable = ((Object) notnull == null || notnull.Equals("false")); bool key = property.LocalName.StartsWith("key-"); //a composite id property ClassName t = GetFieldType(type); AddImport(t); FieldProperty stdField = new FieldProperty(property, this, propertyName, t, nullable && !key, key, false, metaForProperty); AddFieldProperty(stdField); } } // one to ones for (IEnumerator onetoones = classElement.SelectNodes("urn:one-to-one", CodeGenerator.nsmgr).GetEnumerator(); onetoones.MoveNext();) { Element onetoone = (Element) onetoones.Current; MultiMap metaForOneToOne = MetaAttributeHelper.LoadAndMergeMetaMap(onetoone, MetaAttribs); string propertyName = (onetoone.Attributes["name"] == null ? string.Empty : onetoone.Attributes["name"].Value); // ensure that the class is specified string clazz = (onetoone.Attributes["class"] == null ? string.Empty : onetoone.Attributes["class"].Value); if (clazz.Length == 0) { log.Warn("one-to-one \"" + name + "\" in class " + Name + " is missing a class attribute"); continue; } ClassName cn = GetFieldType(clazz); AddImport(cn); FieldProperty fm = new FieldProperty(onetoone, this, propertyName, cn, true, metaForOneToOne); AddFieldProperty(fm); } // many to ones - TODO: consolidate with code above for (IEnumerator manytoOnes = manyToOneList.GetEnumerator(); manytoOnes.MoveNext();) { Element manyToOne = (Element) manytoOnes.Current; MultiMap metaForManyToOne = MetaAttributeHelper.LoadAndMergeMetaMap(manyToOne, MetaAttribs); string propertyName = (manyToOne.Attributes["name"] == null ? string.Empty : manyToOne.Attributes["name"].Value); // ensure that the type is specified string type = (manyToOne.Attributes["class"] == null ? string.Empty : manyToOne.Attributes["class"].Value); if (type.Length == 0) { log.Warn("many-to-one \"" + propertyName + "\" in class " + Name + " is missing a class attribute"); continue; } ClassName classType = new ClassName(type); // is it nullable? string notnull = (manyToOne.Attributes["not-null"] == null ? null : manyToOne.Attributes["not-null"].Value); bool nullable = ((Object) notnull == null || notnull.Equals("false")); bool key = manyToOne.LocalName.StartsWith("key-"); //a composite id property // add an import and field for this property AddImport(classType); FieldProperty f = new FieldProperty(manyToOne, this, propertyName, classType, nullable && !key, key, false, metaForManyToOne); AddFieldProperty(f); } // collections DoCollections(classPackage, classElement, "list", "System.Collections.Generic.IList", "System.Collections.Generic.List", MetaAttribs); DoCollections(classPackage, classElement, "map", "System.Collections.Generic.IDictionary", "System.Collections.Generic.Dictionary", MetaAttribs); DoCollections(classPackage, classElement, "set", "Iesi.Collections.Generic.ISet", "Iesi.Collections.Generic.HashedSet", MetaAttribs); DoCollections(classPackage, classElement, "bag", "System.Collections.Generic.IList", "System.Collections.Generic.List", MetaAttribs); DoCollections(classPackage, classElement, "idbag", "System.Collections.Generic.IList", "System.Collections.Generic.List", MetaAttribs); DoArrays(classElement, "array", MetaAttribs); DoArrays(classElement, "primitive-array", MetaAttribs); //dynamic-component foreach (Element dync in classElement.SelectNodes("urn:dynamic-component", CodeGenerator.nsmgr)) { MultiMap metaForDync = MetaAttributeHelper.LoadAndMergeMetaMap(dync, MetaAttribs); string propertyName = (dync.Attributes["name"] == null ? string.Empty : dync.Attributes["name"].Value); FieldProperty dynfield = new FieldProperty(dync, this, propertyName, new ClassName("System.Collections.Generic.IDictionary"), false, metaForDync); dynfield.AddGenericArgument(new ClassName("System.String")); dynfield.AddGenericArgument(new ClassName("System.Object")); AddImport("System.Collections.Generic.IDictionary"); AddFieldProperty(dynfield); } //components for (IEnumerator iter = classElement.SelectNodes("urn:component", CodeGenerator.nsmgr).GetEnumerator(); iter.MoveNext();) { Element cmpe = (Element) iter.Current; MultiMap metaForComponent = MetaAttributeHelper.LoadAndMergeMetaMap(cmpe, MetaAttribs); string cmpname = (cmpe.Attributes["name"] == null ? null : cmpe.Attributes["name"].Value); string cmpclass = (cmpe.Attributes["class"] == null ? null : cmpe.Attributes["class"].Value); if ((Object) cmpclass == null || cmpclass.Equals(string.Empty)) { log.Warn("component \"" + cmpname + "\" in class " + Name + " does not specify a class"); continue; } ClassMapping mapping = new ClassMapping(classPackage, cmpe, this, true, MetaAttribs); ClassName classType = new ClassName(cmpclass); // add an import and field for this property AddImport(classType); FieldProperty ff = new FieldProperty(cmpe, this, cmpname, classType, false, metaForComponent); AddFieldProperty(ff); object tempObject2; tempObject2 = mapping; components[mapping.FullyQualifiedName] = tempObject2; } // subclasses (done last so they can access this superclass for info) for (IEnumerator iter = classElement.SelectNodes("urn:subclass", CodeGenerator.nsmgr).GetEnumerator(); iter.MoveNext();) { Element subclass = (Element) iter.Current; ClassMapping subclassMapping = new ClassMapping(classPackage, this, name, this, subclass, MetaAttribs); AddSubClass(subclassMapping); } for (IEnumerator iter = classElement.SelectNodes("urn:joined-subclass", CodeGenerator.nsmgr).GetEnumerator(); iter.MoveNext();) { Element subclass = (Element) iter.Current; ClassMapping subclassMapping = new ClassMapping(classPackage, this, name, this, subclass, MetaAttribs); AddSubClass(subclassMapping); } ValidateMetaAttributes(); }
/// <summary> Create finders for properties that have the <meta atttribute="finder-method"> /// finderName</meta> block defined. Also, create a findAll(Session) method. /// /// </summary> public virtual void DoFinders(ClassMapping classMapping, IDictionary class2classmap, StringWriter writer) { // Find out of there is a system wide way to get sessions defined string sessionMethod = classMapping.GetMetaAsString("session-method").Trim(); // fields foreach (FieldProperty field in classMapping.Fields) { if (field.GetMeta(MT_FINDERMETHOD) != null) { string finderName = field.GetMetaAsString(MT_FINDERMETHOD); if ("".Equals(sessionMethod)) { // Make the method signature require a session to be passed in writer.WriteLine(" public static List " + finderName + "(Session session, " + LanguageTool.GetTrueTypeName(field, class2classmap) + " " + field.FieldName + ") " + "throws SQLException, HibernateException {"); } else { // Use the session method to get the session to execute the query writer.WriteLine(" public static List " + finderName + "(" + LanguageTool.GetTrueTypeName(field, class2classmap) + " " + field.FieldName + ") " + "throws SQLException, HibernateException {"); writer.WriteLine(" Session session = " + sessionMethod); } writer.WriteLine(" List finds = session.find(\"from " + classMapping.FullyQualifiedName + " as " + classMapping.Name.ToLower() + " where " + classMapping.Name.ToLower() + "." + field.FieldName + "=?\", " + GetFieldAsObject(false, field) + ", " + GetFieldAsHibernateType(false, field) + ");"); writer.WriteLine(" return finds;"); writer.WriteLine(" }"); writer.WriteLine(); } else if (field.GetMeta(MT_FOREIGNFINDERMETHOD) != null) { string finderName = field.GetMetaAsString(MT_FOREIGNFINDERMETHOD); string fieldName = field.GetMetaAsString(MT_FOREIGNFINDERFIELD); string joinFieldName = field.GetMetaAsString(MT_FOREIGNJOINFIELD); // Build the query QueryBuilder qb = new QueryBuilder(); qb.LocalClass = classMapping; qb.SetForeignClass(field.ForeignClass, class2classmap, joinFieldName); ClassMapping foreignClass = (ClassMapping) class2classmap[field.ForeignClass.FullyQualifiedName]; if (foreignClass == null) { // Can't find the class, return log.Error("Could not find the class " + field.ForeignClass.Name); return; } FieldProperty foreignField = null; foreach (FieldProperty f in foreignClass.Fields) { if (f.FieldName.Equals(fieldName)) { foreignField = f; } } if (foreignField != null) { qb.AddCritera(foreignClass, foreignField, "="); } else { // Can't find the field, return log.Error("Could not find the field " + fieldName + " that was supposed to be in class " + field.ForeignClass.Name); return; } MethodSignatureBuilder msb = new MethodSignatureBuilder(finderName, "List", "public static"); if ("".Equals(sessionMethod)) { // Make the method signature require a session to be passed in msb.AddParameter("Session session"); /* writer.println(" public static List " + finderName + "(Session session, " + getTrueTypeName(foreignField, class2classmap) + " " + foreignField.getName() + ") " + "throws SQLException, HibernateException {");*/ } else { // Use the session method to get the session to execute the query /* writer.println(" public static List " + finderName + "(" + getTrueTypeName(foreignField, class2classmap) + " " + foreignField.getName() + ") " + "throws SQLException, HibernateException {"); writer.println(" Session session = " + sessionMethod);*/ } // Always need the object we're basing the query on msb.AddParameter(classMapping.Name + " " + classMapping.Name.ToLower()); // And the foreign class field msb.AddParameter(LanguageTool.GetTrueTypeName(foreignField, class2classmap) + " " + foreignField.FieldName); msb.AddThrows("SQLException"); msb.AddThrows("HibernateException"); writer.WriteLine(" " + msb.BuildMethodSignature()); if (!"".Equals(sessionMethod)) { writer.WriteLine(" Session session = " + sessionMethod); } writer.WriteLine(" List finds = session.find(\"" + qb.Query + "\", " + qb.ParamsAsString + ", " + qb.ParamTypesAsString + ");"); writer.WriteLine(" return finds;"); writer.WriteLine(" }"); writer.WriteLine(); } } // Create the findAll() method if ("".Equals(sessionMethod)) { writer.WriteLine(" public static List findAll" + "(Session session) " + "throws SQLException, HibernateException {"); } else { writer.WriteLine(" public static List findAll() " + "throws SQLException, HibernateException {"); writer.WriteLine(" Session session = " + sessionMethod); } writer.WriteLine(" List finds = session.find(\"from " + classMapping.Name + " in class " + classMapping.PackageName + "." + classMapping.Name + "\");"); writer.WriteLine(" return finds;"); writer.WriteLine(" }"); writer.WriteLine(); }
/// <summary> Render finder classes.</summary> /// <exception cref="Exception">Exception</exception> public override void Render(string savedToPackage, string savedToClass, ClassMapping classMapping, IDictionary class2classmap, StreamWriter mainwriter) { GeneratePackageDelaration(savedToPackage, classMapping, mainwriter); mainwriter.WriteLine(); // switch to another writer to be able to insert the actually // used imports when whole class has been rendered. StringWriter writer = new StringWriter(); writer.WriteLine("/** Automatically generated Finder class for " + savedToClass + ".\n" + " * @author Hibernate FinderGenerator " + " **/"); string classScope = "public"; writer.Write(classScope + " class " + savedToClass); // always implements Serializable writer.Write(" implements Serializable"); writer.WriteLine(" {"); writer.WriteLine(); // switch to another writer to be able to insert the // veto- and changeSupport fields StringWriter propWriter = new StringWriter(); DoFinders(classMapping, class2classmap, propWriter); propWriter.WriteLine("}"); writer.Write(propWriter.ToString()); // finally write the imports DoImports(classMapping, mainwriter); mainwriter.Write(writer.ToString()); }
public override void Render(string savedToPackage, string savedToClass, ClassMapping classMapping, IDictionary class2classmap, StreamWriter writer) { }
public virtual void DoEqualsAndHashCode(string savedToClass, ClassMapping classMapping, StringWriter writer) { if (classMapping.MustImplementEquals()) { writer.WriteLine(" public override bool Equals(object obj) {"); writer.WriteLine(" if(this == obj) return true;"); writer.WriteLine(" if((obj == null) || (obj.GetType() != this.GetType())) return false;"); writer.WriteLine(" " + savedToClass + " castObj = (" + savedToClass + ") obj;"); writer.Write(" return (castObj != null) "); int usedFields = 0; SupportClass.ListCollectionSupport idFields = new SupportClass.ListCollectionSupport(); for (IEnumerator fields = classMapping.Fields.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty) fields.Current; if (field.GetMetaAsBool("use-in-equals")) { writer.Write(" && (this." + field.fieldcase + " == castObj." + field.fieldcase + ")"); usedFields++; } if (field.Identifier) { idFields.Add(field); } } if (usedFields == 0) { log.Warn("No properties has been marked as being used in equals/hashcode for " + classMapping.Name + ". Using object identifier which is RARELY safe to use! See http://hibernate.org/109.html"); for (IEnumerator fields = idFields.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty) fields.Current; writer.Write(" && (this." + field.fieldcase + " == castObj." + field.fieldcase + ")"); } } writer.WriteLine(";"); writer.WriteLine(" }"); writer.WriteLine(); writer.WriteLine(" public override int GetHashCode() {"); writer.WriteLine(" int hash = 69;"); //writer.Write(" return"); for (IEnumerator fields = classMapping.Fields.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty) fields.Current; if (field.GetMetaAsBool("use-in-equals")) { //writer.Write("\n " + field.FieldName + ".GetHashCode() ^"); writer.WriteLine(" hash = 31 * hash + " + field.fieldcase + ".GetHashCode();"); } } if (usedFields == 0) { for (IEnumerator fields = idFields.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty) fields.Current; //writer.Write("\n " + field.FieldName + ".GetHashCode() ^"); writer.WriteLine(" hash = 31 * hash + " + field.fieldcase + ".GetHashCode();"); } } //writer.WriteLine(" 0;"); writer.WriteLine(" return hash;"); writer.WriteLine(" }"); writer.WriteLine(); } }
/// <summary> Generate the imports for the finder class. /// /// </summary> public virtual void DoImports(ClassMapping classMapping, StreamWriter writer) { // imports is not included from the class it self as this is a separate generated class. /* classMapping.getImports().add("java.io.Serializable"); for (Iterator imports = classMapping.getImports().iterator(); imports.hasNext(); ) { writer.println("import " + imports.next() + ";"); }*/ // Imports for finders writer.WriteLine("import java.io.Serializable;"); writer.WriteLine("import java.util.List;"); writer.WriteLine("import java.sql.SQLException;"); writer.WriteLine(); // * import is bad style. But better than importing classing that we don't necesarrily uses... writer.WriteLine("import NHibernate.*;"); writer.WriteLine("import NHibernate.type.Type;"); // writer.println("import NHibernate.Hibernate;"); // writer.println("import NHibernate.HibernateException;"); writer.WriteLine(); }
private void DoCollections(string classPackage, Element classElement, string xmlName, string interfaceClass, string implementingClass, MultiMap inheritedMeta) { string originalInterface = interfaceClass; string originalImplementation = implementingClass; for (IEnumerator collections = classElement.SelectNodes("urn:" + xmlName, CodeGenerator.nsmgr).GetEnumerator(); collections.MoveNext();) { Element collection = (Element) collections.Current; MultiMap metaForCollection = MetaAttributeHelper.LoadAndMergeMetaMap(collection, inheritedMeta); string propertyName = (collection.Attributes["name"] == null ? string.Empty : collection.Attributes["name"].Value); //TODO: map and set in .net // Small hack to switch over to sortedSet/sortedMap if sort is specified. (that is sort != unsorted) string sortValue = (collection.Attributes["sort"] == null ? null : collection.Attributes["sort"].Value); if ((object) sortValue != null && !"unsorted".Equals(sortValue) && !"".Equals(sortValue.Trim())) { if ("map".Equals(xmlName)) { interfaceClass = typeof(IDictionary<,>).FullName; implementingClass = typeof(IDictionary<,>).FullName; } else if ("set".Equals(xmlName)) { interfaceClass = typeof(ISet<>).FullName; implementingClass = typeof(ISet<>).FullName; } } else { interfaceClass = originalInterface; implementingClass = originalImplementation; } ClassName interfaceClassName = new ClassName(interfaceClass); ClassName implementationClassName = new ClassName(implementingClass); // add an import and field for this collection AddImport(interfaceClassName); AddImport(implementationClassName); ClassName foreignClass = null; SupportClass.SetSupport foreignKeys = null; // Collect bidirectional data if (collection.SelectNodes("urn:one-to-many", CodeGenerator.nsmgr).Count != 0) { foreignClass = new ClassName(collection["one-to-many"].Attributes["class"].Value); } else if (collection.SelectNodes("urn:many-to-many", CodeGenerator.nsmgr).Count != 0) { foreignClass = new ClassName(collection["many-to-many"].Attributes["class"].Value); } // Do the foreign keys and import if (foreignClass != null) { // Collect the keys foreignKeys = new SupportClass.HashSetSupport(); if (collection["key"].Attributes["column"] != null) foreignKeys.Add(collection["key"].Attributes["column"].Value); for (IEnumerator iter = collection["key"].SelectNodes("urn:column", CodeGenerator.nsmgr).GetEnumerator(); iter.MoveNext();) { if (((Element) iter.Current).Attributes["name"] != null) foreignKeys.Add(((Element) iter.Current).Attributes["name"].Value); } AddImport(foreignClass); } FieldProperty cf = new FieldProperty(collection, this, propertyName, interfaceClassName, implementationClassName, false, foreignClass, foreignKeys, metaForCollection); AddFieldProperty(cf); if (collection.SelectNodes("urn:composite-element", CodeGenerator.nsmgr).Count != 0) { for ( IEnumerator compositeElements = collection.SelectNodes("urn:composite-element", CodeGenerator.nsmgr).GetEnumerator(); compositeElements.MoveNext();) { Element compositeElement = (Element) compositeElements.Current; string compClass = compositeElement.Attributes["class"].Value; try { ClassMapping mapping = new ClassMapping(classPackage, compositeElement, this, true, MetaAttribs); ClassName classType = new ClassName(compClass); // add an import and field for this property AddImport(classType); object tempObject; tempObject = mapping; components[mapping.FullyQualifiedName] = tempObject; } catch (Exception e) { log.Error("Error building composite-element " + compClass, e); } } } if (collection.SelectNodes("urn:composite-index", CodeGenerator.nsmgr).Count != 0) { for ( IEnumerator compositeElements = collection.SelectNodes("urn:composite-index", CodeGenerator.nsmgr).GetEnumerator(); compositeElements.MoveNext(); ) { Element compositeElement = (Element)compositeElements.Current; string compClass = compositeElement.Attributes["class"].Value; try { ClassMapping mapping = new ClassMapping(classPackage, compositeElement, this, true, MetaAttribs); mapping.ImplementEquals(); ClassName classType = new ClassName(compClass); // add an import and field for this property AddImport(classType); object tempObject; tempObject = mapping; components[mapping.FullyQualifiedName] = tempObject; } catch (Exception e) { log.Error("Error building composite-index " + compClass, e); } } } ExtractGenericArguments(cf,xmlName); } }
/* * (non-Javadoc) * * @see NHibernate.Tool.hbm2net.Renderer#render(java.lang.String, * java.lang.String, NHibernate.Tool.hbm2net.ClassMapping, * java.util.Map, java.io.PrintWriter) */ public override void Render(string savedToPackage, string savedToClass, ClassMapping classMapping, IDictionary class2classmap, StreamWriter writer) { VelocityContext context = new VelocityContext(); context.Put("savedToPackage", savedToPackage); context.Put("savedToClass", savedToClass); context.Put("clazz", classMapping); context.Put("class2classmap", class2classmap); context.Put("languageTool", new LanguageTool()); context.Put("runtimeversion", Guid.Empty.GetType().Assembly.ImageRuntimeVersion); StringWriter sw = new StringWriter(); context.Put("classimports", "$classimports"); // First run - writes to in-memory string template.Merge(context, sw); context.Put("classimports", new LanguageTool().GenerateImports(classMapping)); // Second run - writes to file (allows for placing imports correctly and optimized ;) ve.Evaluate(context, writer, "hbm2net", sw.ToString()); }
/// <summary> /// Find parents for any orphans /// </summary> /// <returns></returns> private static bool FindParents(Hashtable classMappings) { if (children.Count == 0) { // No parents to find return false; } else { bool found = false; foreach (SubclassMapping child in children) { if (child.Orphaned) { ClassMapping superclass = (ClassMapping) allMaps[child.SuperClass]; if (superclass != null) { ClassMapping subclassMapping = new ClassMapping(child.ClassPackage, child.MappingElement, superclass.ClassName, superclass, child.Clazz, child.MultiMap); superclass.AddSubClass(subclassMapping); // NB Can't remove it from the iterator, so record that we've found the parent. child.Orphaned = false; found = true; } } } // Tell them if we found any return found; } }