Update of /cvsroot/nhibernate/NHibernateContrib/src/NHibernate.Tool.hbm2net In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv26138/NHibernate.Tool.hbm2net Added Files: .cvsignore AbstractRenderer.cs App.config AssemblyInfo.cs BasicRenderer.cs ClassMapping.cs ClassName.cs CodeGenerator.cs convert.vm DOMRenderer.cs FieldProperty.cs FinderRenderer.cs Generator.cs JavaTool.cs MappingElement.cs MetaAttributeHelper.cs MethodSignatureBuilder.cs NHibernate.Tool.hbm2net-1.1.csproj NHibernate.Tool.hbm2net.build QueryBuilder.cs Renderer.cs StringResourceLoader.cs SupportClass.cs VelocityRenderer.cs Log Message: Moved NHibernate.Tasks and NHibernate.Tool.hbm2net over to the NHibernateContrib module. --- NEW FILE: Renderer.cs --- using System; using System.Collections; using System.Collections.Specialized; using System.IO; namespace NHibernate.Tool.hbm2net { public interface Renderer { /// <summary>Called with the optional list of properties from config.xml </summary> void configure(NameValueCollection properties); /// <summary> </summary> /// <param name="savedToPackage">what package is this class placed in /// </param> /// <param name="savedToClass">what classname does it really get /// </param> /// <param name="classMapping">what classmapping is this for /// </param> /// <param name="class2classmap">A complete map from classname to the classmapping /// </param> /// <param name="writer">where we want the output /// @throws Exception /// </param> void render(String savedToPackage, String savedToClass, ClassMapping classMapping, IDictionary class2classmap, StreamWriter writer); /// <summary> Called by the generator to determine the package name of the rendered class. /// /// </summary> /// <param name="classMapping">The class mapping of the generated class /// </param> /// <returns> the package name the class should be saved to /// </returns> String getSaveToPackage(ClassMapping classMapping); /// <summary> Called by the generator to determine the class name of the rendered class. /// /// </summary> /// <param name="classMapping">The class mapping of the generated class /// </param> /// <returns> the class name the class should be saved to /// </returns> String getSaveToClassName(ClassMapping classMapping); } } --- NEW FILE: MetaAttributeHelper.cs --- using System; using System.Collections; using System.Text; using MultiHashMap = System.Collections.Hashtable; using MultiMap = System.Collections.Hashtable; using Element = System.Xml.XmlElement; namespace NHibernate.Tool.hbm2net { /// <summary> Helper for loading, merging and accessing <meta> tags. /// /// </summary> /// <author> max /// /// /// </author> public class MetaAttributeHelper { internal class MetaAttribute { internal String value_Renamed; internal bool inheritable = true; internal MetaAttribute(String value_Renamed, bool inherit) { this.value_Renamed = value_Renamed; this.inheritable = inherit; } public override String ToString() { return value_Renamed; } } /// <summary> Load meta attributes from jdom element into a MultiMap. /// /// </summary> /// <returns> MultiMap /// </returns> static protected internal MultiMap loadMetaMap(Element element) { MultiMap result = new MultiHashMap(); SupportClass.ListCollectionSupport metaAttributeList = new SupportClass.ListCollectionSupport(); metaAttributeList.AddAll(element.SelectNodes("meta", CodeGenerator.nsmgr)); metaAttributeList.AddAll(element.SelectNodes("urn:meta", CodeGenerator.nsmgr)); for (IEnumerator iter = metaAttributeList.GetEnumerator(); iter.MoveNext(); ) { Element metaAttrib = (Element) iter.Current; // does not use getTextNormalize() or getTextTrim() as that would remove the formatting in new lines in items like description for javadocs. String attribute = (metaAttrib.Attributes["attribute"] == null?string.Empty:metaAttrib.Attributes["attribute"].Value); String value_Renamed = metaAttrib.InnerText; String inheritStr = (metaAttrib.Attributes["inherit"] == null?null:metaAttrib.Attributes["inherit"].Value); bool inherit = true; if ((Object) inheritStr != null) { try { inherit = Boolean.Parse(inheritStr); } catch{} } MetaAttribute ma = new MetaAttribute(value_Renamed, inherit); if (result[attribute] == null) result[attribute] = new SupportClass.ListCollectionSupport(); ((SupportClass.ListCollectionSupport)result[attribute]).Add(ma); } return result; } /// <summary> Merges a Multimap with inherited maps. /// Values specified always overrules/replaces the inherited values. /// /// </summary> /// <returns> a MultiMap with all values from local and extra values /// from inherited /// </returns> static public MultiMap mergeMetaMaps(MultiMap local, MultiMap inherited) { MultiHashMap result = new MultiHashMap(); SupportClass.PutAll(result, local); if (inherited != null) { for (IEnumerator iter = new SupportClass.SetSupport(inherited.Keys).GetEnumerator(); iter.MoveNext(); ) { String key = (String) iter.Current; if (!local.ContainsKey(key)) { // inheriting a meta attribute only if it is inheritable ArrayList ml = (ArrayList) inherited[key]; for (IEnumerator iterator = ml.GetEnumerator(); iterator.MoveNext(); ) { MetaAttribute element = (MetaAttribute) iterator.Current; if (element.inheritable) { if (result[key] == null) result[key] = new SupportClass.ListCollectionSupport(); ((SupportClass.ListCollectionSupport)result[key]).Add(element); } } } } } return result; } /// <summary> Method loadAndMergeMetaMap.</summary> /// <returns> MultiMap /// </returns> public static MultiMap loadAndMergeMetaMap(Element classElement, MultiMap inheritedMeta) { return mergeMetaMaps(loadMetaMap(classElement), inheritedMeta); } public static String getMetaAsString(SupportClass.ListCollectionSupport meta, String seperator) { StringBuilder buf = new StringBuilder(); bool first = true; for (IEnumerator iter = meta.GetEnumerator(); iter.MoveNext(); ) { if (first) first = false; else buf.Append(seperator); buf.Append(iter.Current); } return buf.ToString(); } internal static bool getMetaAsBool(SupportClass.ListCollectionSupport c, bool defaultValue) { if (c == null || c.IsEmpty()) { return defaultValue; } else { try { //return System.Boolean.Parse(c.GetEnumerator().Current.ToString()); return Convert.ToBoolean(c[0].ToString()); } catch{} return defaultValue; } } internal static String getMetaAsString(SupportClass.ListCollectionSupport c) { if (c == null || c.IsEmpty()) { return string.Empty; } else { StringBuilder sb = new StringBuilder(); for (IEnumerator iter = c.GetEnumerator(); iter.MoveNext(); ) { Object element = iter.Current; sb.Append(element.ToString()); } return sb.ToString(); } } } } --- NEW FILE: FinderRenderer.cs --- using System; using System.Collections; using System.IO; using System.Reflection; using log4net; namespace NHibernate.Tool.hbm2net { /// <summary> <p>Title: Basic Finder Generator for Hibernate 2</p> /// <p>Description: Generate basic finders for hibernate properties. /// This requires two things in the hbm.xml files. /// /// The first is an indication of which fields you want to generate finders for. /// You indicate that with a meta block inside a property tag such as /// /// <property name="name" column="name" type="string"> /// <meta attribute="finder-method">findByName</meta> /// </property> /// /// The finder method name will be the text enclosed in the meta tags. /// /// If you want to generate a finder based on a join you can do something like this: /// /// <set name="games" inverse="true" lazy="true" table="GamePlayers"> /// <meta attribute="foreign-finder-name">findSavedGames</meta> /// <meta attribute="foreign-finder-field">save</meta> /// <meta attribute="foreign-join-field">players</meta> /// <key column="playerID"/> /// <many-to-many class="com.whatever.Game" column="gameID"/> /// </set> /// /// Where foreign-finder-name will be the name of the finder when generated, foreign-finder-field is the field in /// the foreign class that you will want as a paramter to the finder (the criteria in the query) and foreign-join-field /// is the field in teh foreign class that joins to this object (in case there are more than one collection of these /// objects in the foreign class). /// /// After you've defined your finders, the second thing to do is to create a config file for hbm2net of the format: /// /// <codegen> /// <generate renderer="NHibernate.Tool.hbm2net.BasicRenderer"/> /// <generate suffix="Finder" renderer="NHibernate.Tool.hbm2net.FinderRenderer"/> /// </codegen> /// /// And then use the param to hbm2net --config=xxx.xml where xxx.xml is the config file you /// just created. /// /// An optional parameter is meta tag at the class level of the format: /// /// <meta attribute="session-method">com.whatever.SessionTable.getSessionTable().getSession();</meta> /// /// Which would be the way in which you get sessions if you use the Thread Local Session pattern /// like I do. /// </p> /// <p>Copyright: Copyright (c) 2003</p> /// </summary> /// <author> Matt Hall (matt2k(at)users.sf.net) /// </author> /// <author> Max Rydahl Andersen (small adjustments and bugfixes) /// </author> /// <version> 1.0 /// </version> public class FinderRenderer:AbstractRenderer { private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public FinderRenderer() { InitBlock(); } private void InitBlock() { object tempObject; tempObject = "Character"; primitiveToObject["char"] = tempObject; object tempObject2; tempObject2 = "Byte"; primitiveToObject["byte"] = tempObject2; object tempObject3; tempObject3 = "Short"; primitiveToObject["short"] = tempObject3; object tempObject4; tempObject4 = "Integer"; primitiveToObject["int"] = tempObject4; object tempObject5; tempObject5 = "Long"; primitiveToObject["long"] = tempObject5; object tempObject6; tempObject6 = "Boolean"; primitiveToObject["boolean"] = tempObject6; object tempObject7; tempObject7 = "Float"; primitiveToObject["float"] = tempObject7; object tempObject8; tempObject8 = "Double"; primitiveToObject["double"] = tempObject8; hibType["char"] = "Hibernate.CHARACTER"; hibType["byte"] = "Hibernate.BYTE"; tempObject3 = "Hibernate.SHORT"; hibType["short"] = "Hibernate.SHORT"; tempObject4 = "Hibernate.INTEGER"; hibType["int"] = tempObject4; tempObject5 = "Hibernate.LONG"; hibType["long"] = tempObject5; tempObject6 = "Hibernate.INTEGER"; hibType["Integer"] = tempObject6; tempObject7 = "Hibernate.BOOLEAN"; hibType["boolean"] = tempObject7; tempObject8 = "Hibernate.FLOAT"; hibType["float"] = tempObject8; object tempObject9; tempObject9 = "Hibernate.DOUBLE"; hibType["double"] = tempObject9; object tempObject10; tempObject10 = "Hibernate.STRING"; hibType["String"] = tempObject10; object tempObject11; tempObject11 = "Hibernate.LOCALE"; hibType["Locale"] = tempObject11; } private const String MT_FINDERMETHOD = "finder-method"; private const String MT_FOREIGNFINDERMETHOD = "foreign-finder-name"; private const String MT_FOREIGNFINDERFIELD = "foreign-finder-field"; private const String MT_FOREIGNJOINFIELD = "foreign-join-field"; /// <summary> Render finder classes.</summary> /// <exception cref=""> Exception /// </exception> public override void render(String savedToPackage, String savedToClass, ClassMapping classMapping, IDictionary class2classmap, StreamWriter mainwriter) { genPackageDelaration(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()); } /// <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 //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilIteratorhasNext"' for (IEnumerator fields = classMapping.Fields.GetEnumerator(); fields.MoveNext(); ) { //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilIteratornext"' FieldProperty field = (FieldProperty) fields.Current; 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, " + JavaTool.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 + "(" + JavaTool.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); //UPGRADE_TODO: Method 'java.util.Map.get' was converted to 'System.Collections.IDictionary.Item' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilMapget_javalangObject"' 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; //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilIteratorhasNext"' for (IEnumerator foreignFields = foreignClass.Fields.GetEnumerator(); foreignFields.MoveNext(); ) { //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilIteratornext"' FieldProperty f = (FieldProperty) foreignFields.Current; 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.addParam("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.addParam(classMapping.Name + " " + classMapping.Name.ToLower()); // And the foreign class field msb.addParam(JavaTool.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(); } //UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilHashMap"' //UPGRADE_NOTE: The initialization of 'primitiveToObject' was moved to static method 'NHibernate.Tool.hbm2net.FinderRenderer'. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1005"' internal static IDictionary primitiveToObject; /// <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(); } /// <summary> Gets the fieldAsObject attribute of the FinderRenderer object /// /// </summary> /// <returns> /// </returns> public static String getFieldAsObject(bool prependThis, FieldProperty field) { ClassName type = field.ClassType; if (type != null && type.Primitive && !type.Array) { //UPGRADE_TODO: Method 'java.util.Map.get' was converted to 'System.Collections.IDictionary.Item' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilMapget_javalangObject"' String typeName = (String) primitiveToObject[type.Name]; typeName = "new " + typeName + "( "; typeName += (prependThis?"this.":""); return typeName + field.FieldName + " )"; } return field.FieldName; } /// <summary> Coversion map for field types to Hibernate types, might be good to move /// this to some other more general class /// </summary> //UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilHashMap"' //UPGRADE_NOTE: The initialization of 'hibType' was moved to static method 'NHibernate.Tool.hbm2net.FinderRenderer'. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1005"' internal static IDictionary hibType; /// <summary> Return the hibernate type string for the given field /// /// </summary> /// <returns> /// </returns> public static String getFieldAsHibernateType(bool prependThis, FieldProperty field) { ClassName type = field.ClassType; //UPGRADE_TODO: Method 'java.util.Map.get' was converted to 'System.Collections.IDictionary.Item' which has a different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1073_javautilMapget_javalangObject"' String hibTypeString = (String) hibType[type.Name]; if ((Object) hibTypeString != null) { return hibTypeString; } else { return "Hibernate.OBJECT"; } } static FinderRenderer() { primitiveToObject = new Hashtable(); hibType = new Hashtable(); } } } --- NEW FILE: CodeGenerator.cs --- using System; using System.Collections; using System.IO; using System.Reflection; using System.Xml; using log4net; using log4net.Config; using MultiHashMap = System.Collections.Hashtable; using MultiMap = System.Collections.Hashtable; using Document = System.Xml.XmlDocument; using Element = System.Xml.XmlElement; namespace NHibernate.Tool.hbm2net { /// <summary> </summary> public class CodeGenerator { private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); internal static XmlNamespaceManager nsmgr; [STAThread] public static void Main(String[] args) { nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace("urn", "urn:nhibernate-mapping-2.0"); File.Delete("error-log.txt"); DOMConfigurator.Configure(new FileInfo("NHibernate.Tool.hbm2net.exe.config")); if (args.Length == 0) { Console.Error.WriteLine("No arguments provided. Nothing to do. Exit."); Environment.Exit(- 1); } try { ArrayList mappingFiles = new ArrayList(); String outputDir = null; SupportClass.ListCollectionSupport generators = new SupportClass.ListCollectionSupport(); MultiMap globalMetas = new MultiHashMap(); // parse command line parameters for (int i = 0; i < args.Length; i++) { if (args[i].StartsWith("--")) { if (args[i].StartsWith("--config=")) { // parse config xml file Document document = new XmlDocument(); document.Load(args[i].Substring(9)); globalMetas = MetaAttributeHelper.loadAndMergeMetaMap((document["codegen"]), null); IEnumerator generateElements = document["codegen"].SelectNodes("generate").GetEnumerator(); while (generateElements.MoveNext()) { generators.Add(new Generator((Element) generateElements.Current)); } } else if (args[i].StartsWith("--output=")) { outputDir = args[i].Substring(9); } } else { mappingFiles.Add(args[i]); } } // if no config xml file, add a default generator if (generators.Count == 0) { generators.Add(new Generator()); } Hashtable classMappings = new Hashtable(); for (IEnumerator iter = mappingFiles.GetEnumerator(); iter.MoveNext(); ) { try { log.Info(iter.Current.ToString()); // parse the mapping file NameTable nt = new NameTable(); nt.Add("urn:nhibernate-mapping-2.0"); Document document = new XmlDocument(nt); document.Load((String) iter.Current); Element rootElement = document["hibernate-mapping"]; if (rootElement == null) continue; XmlAttribute a = rootElement.Attributes["package"]; String pkg = null; if (a != null) { pkg = a.Value; } MappingElement me = new MappingElement(rootElement, null); IEnumerator classElements = rootElement.SelectNodes("urn:class", nsmgr).GetEnumerator(); MultiMap mm = MetaAttributeHelper.loadAndMergeMetaMap(rootElement, globalMetas); handleClass(pkg, me, classMappings, classElements, mm, false); classElements = rootElement.SelectNodes("urn:subclass", nsmgr).GetEnumerator(); handleClass(pkg, me, classMappings, classElements, mm, true); classElements = rootElement.SelectNodes("urn:joined-subclass", nsmgr).GetEnumerator(); handleClass(pkg, me, classMappings, classElements, mm, true); } catch(Exception exc) { log.Error("Error in map",exc); } } // generate source files for (IEnumerator iterator = generators.GetEnumerator(); iterator.MoveNext(); ) { Generator g = (Generator) iterator.Current; g.BaseDirName = outputDir; g.generate(classMappings); } } catch (Exception e) { SupportClass.WriteStackTrace(e, Console.Error); } } 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); } 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 + ">"); } ClassMapping superclass = (ClassMapping) classMappings[ex]; if (superclass == null) { throw new MappingException("Cannot extend unmapped class " + ex); } ClassMapping subclassMapping = new ClassMapping(classPackage, me, superclass.ClassName, superclass, clazz, mm); superclass.addSubClass(subclassMapping); } } } } } --- NEW FILE: Generator.cs --- using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Reflection; using log4net; using NHibernate.Util; using Element = System.Xml.XmlElement; namespace NHibernate.Tool.hbm2net { /// <summary> </summary> public class Generator { private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private void InitBlock() { suffix = string.Empty; prefix = string.Empty; } virtual public String BaseDirName { get { return baseDirName; } set { if ((Object) value != null) { this.baseDirName = value; } } } private String rendererClass = "NHibernate.Tool.hbm2net.VelocityRenderer"; private String baseDirName = "generated"; private String packageName = null; private String suffix; private String prefix; private String extension = "cs"; private bool lowerFirstLetter = false; public static NameValueCollection params_Renamed = new NameValueCollection(); /// <summary> Constructs a new Generator using the defaults.</summary> public Generator() { InitBlock(); } /// <summary> Constructs a new Generator, configured from XML.</summary> public Generator(Element generateElement) { InitBlock(); String value_Renamed = null; // set rendererClass field if ((Object) (this.rendererClass = (generateElement.Attributes["renderer"] == null?null:generateElement.Attributes["renderer"].Value)) == null) { throw new Exception("attribute renderer is required."); } // set dirName field if ((Object) (value_Renamed = (generateElement.Attributes["dir"] == null?null:generateElement.Attributes["dir"].Value)) != null) { this.baseDirName = value_Renamed; } // set packageName field this.packageName = (generateElement.Attributes["package"] == null?null:generateElement.Attributes["package"].Value); // set prefix if ((Object) (value_Renamed = (generateElement.Attributes["prefix"] == null?null:generateElement.Attributes["prefix"].Value)) != null) { this.prefix = value_Renamed; } // set suffix if ((Object) (value_Renamed = (generateElement.Attributes["suffix"] == null?null:generateElement.Attributes["suffix"].Value)) != null) { this.suffix = value_Renamed; } // set extension if ((Object) (value_Renamed = (generateElement.Attributes["extension"] == null?null:generateElement.Attributes["extension"].Value)) != null) { this.extension = value_Renamed; } // set lowerFirstLetter value_Renamed = (generateElement.Attributes["lowerFirstLetter"] == null?null:generateElement.Attributes["lowerFirstLetter"].Value); try { this.lowerFirstLetter = Boolean.Parse(value_Renamed); } catch{} IEnumerator iter = generateElement.SelectNodes("param").GetEnumerator(); while (iter.MoveNext()) { Element childNode = (Element) iter.Current; params_Renamed[childNode.Attributes["name"].Value] = childNode.InnerText; } } /// <summary> </summary> public virtual void generate(IDictionary classMappingsCol) { log.Info("Generating " + classMappingsCol.Count + " in " + BaseDirName); Renderer renderer = (Renderer) SupportClass.CreateNewInstance(System.Type.GetType(this.rendererClass)); /// <summary>Configure renderer </summary> renderer.configure(params_Renamed); /// <summary>Running through actual classes </summary> for (IEnumerator classMappings = classMappingsCol.Values.GetEnumerator(); classMappings.MoveNext(); ) { ClassMapping classMapping = (ClassMapping) classMappings.Current; writeRecur(classMapping, classMappingsCol, renderer); } /// <summary>Running through components </summary> for (IEnumerator cmpMappings = ClassMapping.Components; cmpMappings.MoveNext(); ) { ClassMapping mapping = (ClassMapping) cmpMappings.Current; write(mapping, classMappingsCol, renderer); } } private void writeRecur(ClassMapping classMapping, IDictionary class2classmap, Renderer renderer) { write(classMapping, class2classmap, renderer); if (!(classMapping.Subclasses.Count == 0)) { IEnumerator it = classMapping.Subclasses.GetEnumerator(); while (it.MoveNext()) { writeRecur((ClassMapping) it.Current, class2classmap, renderer); } } } /// <summary> </summary> private void write(ClassMapping classMapping, IDictionary class2classmap, Renderer renderer) { String saveToPackage = renderer.getSaveToPackage(classMapping); String saveToClassName = renderer.getSaveToClassName(classMapping); FileInfo dir = this.getDir(saveToPackage); FileInfo file = new FileInfo(dir.FullName + "\\" + this.getFileName(saveToClassName)); log.Debug("Writing " + file); StreamWriter writer = new StreamWriter(new FileStream(file.FullName, FileMode.Create)); renderer.render(getPackageName(saveToPackage), getName(saveToClassName), classMapping, class2classmap, writer); writer.Close(); } /// <summary> </summary> private String getFileName(String className) { return this.getName(className) + "." + this.extension; } /// <summary> </summary> private String getName(String className) { String name = null; if (this.lowerFirstLetter) { name = className.Substring(0, (1) - (0)).ToLower() + className.Substring(1, (className.Length) - (1)); } else { name = className; } return this.prefix + name + this.suffix; } private String getPackageName(String packageName) { if ((Object) this.packageName == null) { return (Object) packageName == null?string.Empty:packageName; } else { return this.packageName; } } /// <summary> </summary> private FileInfo getDir(String packageName) { FileInfo baseDir = new FileInfo(this.baseDirName); FileInfo dir = null; String p = getPackageName(packageName); dir = new FileInfo(baseDir.FullName + "\\" + p.Replace(StringHelper.Dot, Path.DirectorySeparatorChar)); // if the directory exists, make sure it is a directory bool tmpBool; if (File.Exists(dir.FullName)) tmpBool = true; else tmpBool = Directory.Exists(dir.FullName); if (tmpBool) { if (!Directory.Exists(dir.FullName)) { throw new Exception("The path: " + dir.FullName + " exists, but is not a directory"); } } // else make the directory and any non-existent parent directories else { if (!Directory.CreateDirectory(dir.FullName).Exists) { throw new Exception("unable to create directory: " + dir.FullName); } } return dir; } } } --- NEW FILE: BasicRenderer.cs --- using System; using StringHelper = NHibernate.Util.StringHelper; namespace NHibernate.Tool.hbm2net { public class BasicRenderer:AbstractRenderer { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public BasicRenderer() { InitBlock(); } private void InitBlock() { javaTool = new JavaTool(); primitiveToObject["char"] = "Character"; primitiveToObject["byte"] = "Byte"; primitiveToObject["short"] = "Short"; primitiveToObject["int"] = "Integer"; primitiveToObject["long"] = "Long"; primitiveToObject["boolean"] = "Boolean"; primitiveToObject["float"] = "Float"; primitiveToObject["double"] = "Double"; } protected internal const int ORDINARY = 0; protected internal const int BOUND = 1; protected internal const int CONSTRAINT = 3; //any constraint properties are bound as well internal JavaTool javaTool; public override void render(System.String savedToPackage, System.String savedToClass, ClassMapping classMapping, System.Collections.IDictionary class2classmap, System.IO.StreamWriter mainwriter) { mainwriter.WriteLine("using System;"); mainwriter.WriteLine(@"//------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Runtime Version: {0} // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> //------------------------------------------------------------------------------ ",Guid.Empty.GetType().Assembly.ImageRuntimeVersion); genPackageDelaration(savedToPackage, classMapping, mainwriter); mainwriter.WriteLine("{"); // switch to another writer to be able to insert the actually // used imports when whole class has been rendered. System.IO.StringWriter writer = new System.IO.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" + javaTool.toJavaDoc(classMapping.getMetaAsString("class-description"), 0) + "\n/// </summary>"); } System.String classScope = classMapping.Scope; System.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 (javaTool.hasExtends(classMapping) || javaTool.hasImplements(classMapping)) { writer.Write(" : "); } if (javaTool.hasExtends(classMapping)) { writer.Write(javaTool.getExtends(classMapping)); } if (javaTool.hasExtends(classMapping) && javaTool.hasImplements(classMapping)) { writer.Write(", "); } if (javaTool.hasImplements(classMapping)) { writer.Write(javaTool.getImplements(classMapping)); } writer.WriteLine(" {"); writer.WriteLine(); // switch to another writer to be able to insert the // veto- and changeSupport fields System.IO.StringWriter propWriter = new System.IO.StringWriter(); if (!classMapping.Interface) { doFields(classMapping, class2classmap, propWriter); doConstructors(savedToClass, classMapping, class2classmap, propWriter); } System.String vetoSupport = makeSupportField("vetos", classMapping.AllFields); System.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"); System.Collections.IEnumerator iter = extras.GetEnumerator(); while (iter.MoveNext()) { System.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}"); } /// <summary> Method doSupportMethods.</summary> /// <param name="changeSupport"></param> /// <param name="fieldTypes"></param> /// <param name="vetoSupport"></param> /// <param name="writer"></param> private void doSupportMethods(int fieldTypes, System.String vetoSupport, System.String changeSupport, System.IO.StringWriter writer) { if ((fieldTypes & CONSTRAINT) == CONSTRAINT) { writer.WriteLine(" public void addVetoableChangeListener( VetoableChangeListener l ) {"); writer.WriteLine(" " + vetoSupport + ".addVetoableChangeListener(l);"); writer.WriteLine(" }"); writer.WriteLine(" public void removeVetoableChangeListener( VetoableChangeListener l ) {"); writer.WriteLine(" " + vetoSupport + ".removeVetoableChangeListener(l);"); writer.WriteLine(" }"); writer.WriteLine(); } if ((fieldTypes & BOUND) == BOUND) { writer.WriteLine(" public void addPropertyChangeListener( PropertyChangeListener l ) {"); writer.WriteLine(" " + changeSupport + ".addPropertyChangeListener(l);"); writer.WriteLine(" }"); writer.WriteLine(" public void removePropertyChangeListener( PropertyChangeListener l ) {"); writer.WriteLine(" " + changeSupport + ".removePropertyChangeListener(l);"); writer.WriteLine(" }"); writer.WriteLine(); } } /// <summary> Method doSupports.</summary> /// <param name="vetoSupport"> /// </param> /// <param name="changeSupport"> /// </param> /// <param name="writer"> /// </param> private void doSupports(int fieldTypes, ClassMapping classMapping, System.String vetoSupport, System.String changeSupport, System.IO.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(); } } public virtual void doConstructors(System.String savedToClass, ClassMapping classMapping, System.Collections.IDictionary class2classmap, System.IO.StringWriter writer) { // full constructor SupportClass.ListCollectionSupport allFieldsForFullConstructor = classMapping.AllFieldsForFullConstructor; writer.WriteLine(" /// <summary>\n /// full constructor\n /// </summary>"); System.String fullCons = " public " + savedToClass + StringHelper.OpenParen; fullCons += javaTool.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 (System.Collections.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 (System.Collections.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>"); System.String minCons = " public " + savedToClass + "("; bool first = true; for (System.Collections.IEnumerator fields = allFieldsForMinimalConstructor.GetEnumerator(); fields.MoveNext(); ) { if (first) first = false; else minCons = minCons + ", "; FieldProperty field = (FieldProperty) fields.Current; minCons = minCons + JavaTool.shortenType(JavaTool.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 (System.Collections.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 (System.Collections.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 virtual void doFields(ClassMapping classMapping, System.Collections.IDictionary class2classmap, System.IO.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); } private void doFields(SupportClass.ListCollectionSupport fieldList, SupportClass.SetSupport imports, System.Collections.IDictionary class2classmap, System.IO.StringWriter writer) { for (System.Collections.IEnumerator fields = fieldList.GetEnumerator(); fields.MoveNext(); ) { FieldProperty field = (FieldProperty) fields.Current; if (field.GeneratedAsProperty) { System.String fieldScope = getFieldScope(field, "scope-field", "private"); writer.WriteLine(" /// <summary>\n /// Holder for " + (field.Nullable && !field.Identifier?"nullable ":string.Empty) + (field.Identifier?"identifier":"persistent") + " field " + field.FieldName + "\n /// </summary>"); writer.Write(" " + fieldScope + " " + field.FullyQualifiedTypeName + " " + field.fieldcase); if (field.getMeta("default-value") != null) { writer.Write(" = " + field.getMetaAsString("default-value")); } writer.WriteLine(';'); } writer.WriteLine(); } } public virtual void doEqualsAndHashCode(System.String savedToClass, ClassMapping classMapping, System.IO.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 (System.Collections.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 (System.Collections.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 (System.Collections.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 (System.Collections.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(); } } public virtual void doToString(ClassMapping classMapping, System.IO.StringWriter writer) { writer.WriteLine(" public override string ToString()"); writer.WriteLine(" {"); writer.WriteLine(" System.Text.StringBuilder sb = new System.Text.StringBuilder();"); for (System.Collections.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(); } internal static System.Collections.IDictionary primitiveToObject; public virtual int doFieldAccessors(ClassMapping classMapping, System.Collections.IDictionary class2classmap, System.IO.StringWriter writer, System.String vetoSupport, System.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; } private int doFields(ClassMapping classMapping, System.Collections.IDictionary class2classmap, System.IO.StringWriter writer, System.String vetoSupport, System.String changeSupport, int fieldTypes, SupportClass.ListCollectionSupport fieldz) { // field accessors for (System.Collections.IEnumerator fields = fieldz.GetEnumerator(); fields.MoveNext(); ) { FieldProperty field = (FieldProperty) fields.Current; if (field.GeneratedAsProperty) { // getter System.String getAccessScope = getFieldScope(field, "scope-get", "public"); if (field.getMeta("field-description") != null) { //writer.WriteLine(" /** \n" + javaTool.toJavaDoc(field.getMetaAsString("field-description"), 4) + " */"); writer.WriteLine(" /// <summary>\n" + javaTool.toJavaDoc(field.getMetaAsString("field-description"), 4) + "\n /// </summary>"); } writer.Write(" " + getAccessScope + " " + 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) { System.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; } } System.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 doImports(ClassMapping classMapping, System.IO.StreamWriter writer) { writer.WriteLine(javaTool.genImports(classMapping)); writer.WriteLine(); } protected internal virtual System.String makeSupportField(System.String fieldName, SupportClass.ListCollectionSupport fieldList) { System.String suffix = ""; bool needSuffix = false; for (System.Collections.IEnumerator fields = fieldList.GetEnumerator(); fields.MoveNext(); ) { System.String name = ((FieldProperty) fields.Current).FieldName; if (name.Equals(fieldName)) needSuffix = true; suffix += name; } return needSuffix?fieldName + "_" + suffix:fieldName; } private System.String getFieldAsObject(bool prependThis, FieldProperty field) { ClassName type = field.ClassType; if (type != null && type.Primitive && !type.Array) { System.String typeName = (System.String) primitiveToObject[type.Name]; typeName = "new " + typeName + "( "; typeName += (prependThis?"this.":""); return typeName + field.FieldName + " )"; } return (prependThis?"this.":"") + field.FieldName; } static BasicRenderer() { primitiveToObject = new System.Collections.Hashtable(); } } } --- NEW FILE: ClassMapping.cs --- using System; using System.Collections; using System.IO; using System.Reflection; using System.Xml; using log4net; using NHibernate.Type; using NHibernate.Util; using CompositeUserType = NHibernate.ICompositeUserType; using UserType = NHibernate.IUserType; using Type = NHibernate.Type.TypeType; using Element = System.Xml.XmlElement; using MultiMap = System.Collections.Hashtable; namespace NHibernate.Tool.hbm2net { public class ClassMapping:MappingElement { private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private void InitBlock() { fields = new SupportClass.ListCollectionSupport(); imports = new SupportClass.TreeSetSupport(); subclasses = new SupportClass.ListCollectionSupport(); } virtual public SupportClass.ListCollectionSupport Fields { get { return fields; } } virtual public SupportClass.SetSupport Imports { get { return imports; } } /// <summary>shorthand method for getClassName().getFullyQualifiedName() </summary> virtual public String FullyQualifiedName { get { return ClassName.FullyQualifiedName; } } /// <summary>shorthand method for getClassName().getName() </summary> virtual public String Name { get { return ClassName.Name; } } /// <summary>shorthand method for getClassName().getPackageName() </summary> virtual public String PackageName { get { return ClassName.PackageName; } } virtual public ClassName ClassName { get { return name; } } virtual public String GeneratedName { get { return generatedName.Name; } } virtual public String GeneratedPacka... [truncated message content] |