Esempio n. 1
0
        /// <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>
        public static 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);
        }
Esempio n. 2
0
        private void DoFields(SupportClass.ListCollectionSupport fieldList, SupportClass.SetSupport imports,
                              IDictionary class2classmap, StringWriter writer)
        {
            for (IEnumerator fields = fieldList.GetEnumerator(); fields.MoveNext();)
            {
                FieldProperty field = (FieldProperty)fields.Current;

                if (field.GeneratedAsProperty)
                {
                    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();
            }
        }
        /// <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>
        public static 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;
        }
Esempio n. 4
0
 private void InitBlock()
 {
     //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.ArrayList' and 'System.Collections.ArrayList' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1186"'
     objects = new ArrayList();
     //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.ArrayList' and 'System.Collections.ArrayList' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1186"'
     joinConditions = new ArrayList();
     //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.ArrayList' and 'System.Collections.ArrayList' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1186"'
     criteria = new ArrayList();
     //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.ArrayList' and 'System.Collections.ArrayList' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1186"'
     params_Renamed = new SupportClass.ListCollectionSupport();
     //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.ArrayList' and 'System.Collections.ArrayList' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1186"'
     criteriaParamTypes = new SupportClass.ListCollectionSupport();
 }
Esempio n. 5
0
        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);
            }
        }
Esempio n. 6
0
 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);
 }
Esempio n. 7
0
        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);
        }
Esempio n. 8
0
        protected internal virtual string MakeSupportField(string fieldName, SupportClass.ListCollectionSupport fieldList)
        {
            string suffix     = "";
            bool   needSuffix = false;

            for (IEnumerator fields = fieldList.GetEnumerator(); fields.MoveNext();)
            {
                string name = ((FieldProperty)fields.Current).FieldName;
                if (name.Equals(fieldName))
                {
                    needSuffix = true;
                }
                suffix += name;
            }
            return(needSuffix ? fieldName + "_" + suffix : fieldName);
        }
Esempio n. 9
0
 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());
     }
 }
Esempio n. 10
0
 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);
     }
 }
Esempio n. 11
0
        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());
        }
Esempio n. 12
0
        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());
        }
Esempio n. 13
0
        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());
        }
Esempio n. 14
0
        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());
        }
Esempio n. 15
0
        /// <summary> Load meta attributes from jdom element into a MultiMap.
        ///
        /// </summary>
        /// <returns> MultiMap
        /// </returns>
        protected internal static MultiMap loadMetaMap(Element element)
        {
            MultiMap result = new MultiHashMap();

            SupportClass.ListCollectionSupport metaAttributeList = new SupportClass.ListCollectionSupport();
            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);
        }
Esempio n. 16
0
 private void InitBlock()
 {
     fields = new SupportClass.ListCollectionSupport();
     imports = new SupportClass.TreeSetSupport();
     subclasses = new SupportClass.ListCollectionSupport();
     //ensure imports System...
     imports.Add("System");
 }
Esempio n. 17
0
        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();
            }
        }
        public static void Main(String[] args)
        {
            nsmgr = new XmlNamespaceManager(new NameTable());
            nsmgr.AddNamespace("urn", "urn:nhibernate-mapping-2.2");

            children = new ArrayList();
            allMaps = new MultiMap();

            File.Delete("error-log.txt");

            // DOMConfigurator is deprecated in the latest log4net, but we are using an earlier
            // version that comes with NVelocity.
            XmlConfigurator.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);
            }

            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="))
                    {
                        FileInfo configFile = new FileInfo(args[i].Substring(9));

                        // parse config xml file
                        Document document = new XmlDocument();
                        document.Load(configFile.FullName);
                        globalMetas = MetaAttributeHelper.LoadAndMergeMetaMap((document["codegen"]), null);
                        IEnumerator generateElements = document["codegen"].SelectNodes("generate").GetEnumerator();

                        while (generateElements.MoveNext())
                        {
                            generators.Add(new Generator(configFile.Directory, (Element) generateElements.Current));
                        }
                    }
                    else if (args[i].StartsWith("--output="))
                    {
                        outputDir = args[i].Substring(9);
                    }
                }
                else if (args[i].IndexOf("*") > -1)
                {
                    // Handle wildcards
                    mappingFiles.AddRange(GetFiles(args[i]));
                }
                else
                {
                    mappingFiles.Add(args[i]);
                }
            }

            // if no config xml file, add a default generator
            if (generators.Count == 0)
            {
                generators.Add(new Generator(new DirectoryInfo(Environment.CurrentDirectory)));
            }

            Hashtable classMappings = new Hashtable();
            for (IEnumerator iter = mappingFiles.GetEnumerator(); iter.MoveNext(); )
            {
                log.Info(iter.Current.ToString());

                string mappingFile = (string)iter.Current;
                if (!Path.IsPathRooted(mappingFile))
                {
                    mappingFile = Path.Combine(Environment.CurrentDirectory, mappingFile);
                }
                if (!File.Exists(mappingFile))
                    throw new FileNotFoundException("Mapping file does not exist.", mappingFile);

                // parse the mapping file
                NameTable nt = new NameTable();
                nt.Add("urn:nhibernate-mapping-2.2");
                Document document = new XmlDocument(nt);
                document.Load(mappingFile);

                Element rootElement = document["hibernate-mapping"];

                if (rootElement == null)
                    continue;

                XmlAttribute a = rootElement.Attributes["namespace"];
                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);

                // Ok, pickup subclasses that we found before their superclasses
                ProcessChildren(classMappings);

                // generate source files
                for (IEnumerator iterator = generators.GetEnumerator(); iterator.MoveNext(); )
                {
                    Generator g = (Generator)iterator.Current;
                    g.BaseDirName = outputDir;
                    g.Generate(classMappings);
                }
            }
        }
Esempio n. 19
0
 private void InitBlock()
 {
     //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.ArrayList' and 'System.Collections.ArrayList' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1186"'
     objects = new ArrayList();
     //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.ArrayList' and 'System.Collections.ArrayList' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1186"'
     joinConditions = new ArrayList();
     //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.ArrayList' and 'System.Collections.ArrayList' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1186"'
     criteria = new ArrayList();
     //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.ArrayList' and 'System.Collections.ArrayList' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1186"'
     params_Renamed = new SupportClass.ListCollectionSupport();
     //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.ArrayList' and 'System.Collections.ArrayList' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1186"'
     criteriaParamTypes = new SupportClass.ListCollectionSupport();
 }
Esempio n. 20
0
        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;
            }
        }
Esempio n. 21
0
        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}");
        }
Esempio n. 22
0
        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();
            }
        }
Esempio n. 23
0
        public static void Generate(String[] args, IFileCreationObserver fileCreationObserver)
        {
            //this has to change... dirty things during porting
            ClassMapping.ResetComponents();
            nsmgr = new XmlNamespaceManager(new NameTable());
            nsmgr.AddNamespace("urn", "urn:nhibernate-mapping-2.2");
            children = new ArrayList();
            allMaps  = new MultiMap();
            ArrayList mappingFiles = new ArrayList();
            string    outputDir    = null;

            SupportClass.ListCollectionSupport generators = new SupportClass.ListCollectionSupport();
            MultiMap globalMetas = new MultiHashMap();

            // parse command line parameters
            cmdLine = new Hbm2NetParameters(args);
            try
            {
                cmdLine.Parse();
                if (0 == cmdLine.FileNames.Count())
                {
                    Console.Error.WriteLine("No input file(s) specified");
                    throw new NotEnougthParametersException();
                }
            }
            catch (NotEnougthParametersException)
            {
                Console.Error.WriteLine(string.Format("Use:hbm2net {0} files.hbm.xml ( wildcards allowed )", cmdLine.GetShortHelp()));
                Console.Error.WriteLine(cmdLine.GetHelp());
                Environment.Exit(-1);
            }
            if (!string.IsNullOrEmpty(cmdLine.ConfigFile))
            {
                if (File.Exists(cmdLine.ConfigFile))
                {
                    try
                    {
                        FileInfo configFile = new FileInfo(cmdLine.ConfigFile);
                        // parse config xml file
                        Document document = new XmlDocument();
                        document.Load(configFile.FullName);
                        var cfgValidator = new ConfigurationValidator();
                        cfgValidator.Validate(document);
                        if (!string.IsNullOrEmpty(cfgValidator.WarningMessage))
                        {
                            log.Warn("Configuration:" + cfgValidator.WarningMessage);
                        }
                        globalMetas = MetaAttributeHelper.LoadAndMergeMetaMap((document["codegen"]), null);
                        IEnumerator generateElements = document["codegen"].SelectNodes("generate").GetEnumerator();
                        while (generateElements.MoveNext())
                        {
                            generators.Add(new Generator(configFile.Directory, (Element)generateElements.Current));
                        }
                    }
                    catch (ConfigurationValidationException validationException)
                    {
                        Console.Error.WriteLine("Error validating configuration file:" + validationException.Message);
                        Environment.Exit(-1);
                    }
                    catch (Exception genericException)
                    {
                        Console.Error.WriteLine("Error reading configuration file:" + genericException.Message);
                        Environment.Exit(-1);
                    }
                }
                else
                {
                    log.Error("Configuration file:" + cmdLine.ConfigFile + " does not exist");
                    Environment.Exit(-1);
                }
            }
            if (generators.Count == 0)
            {
                log.Info("No configuration file specified: using T4 generator with default template.");
                T4Render t4 = new T4Render();
                t4.Configure(new DirectoryInfo(Directory.GetCurrentDirectory()), new NameValueCollection());
                generators.Add(new Generator(t4));
            }
            if (!string.IsNullOrEmpty(cmdLine.OutputDir))
            {
                outputDir = cmdLine.OutputDir;
            }
            foreach (string inFile in cmdLine.FileNames)
            {
                if (inFile.IndexOf("*") > -1)
                {
                    mappingFiles.AddRange(GetFiles(inFile));
                }
                else
                {
                    mappingFiles.Add(inFile);
                }
            }

            Hashtable classMappings = new Hashtable();

            for (IEnumerator iter = mappingFiles.GetEnumerator(); iter.MoveNext();)
            {
                log.Info(string.Concat("Handling:", iter.Current.ToString()));


                string mappingFile = (string)iter.Current;
                if (!Path.IsPathRooted(mappingFile))
                {
                    mappingFile = Path.Combine(Environment.CurrentDirectory, mappingFile);
                }
                if (!File.Exists(mappingFile))
                {
                    throw new FileNotFoundException("Mapping file does not exist.", mappingFile);
                }

                // parse the mapping file
                NameTable nt = new NameTable();
                nt.Add("urn:nhibernate-mapping-2.2");
                Document document = new XmlDocument(nt);
                document.Load(mappingFile);
                FileInfo mappingFileInfo = new FileInfo(mappingFile);
                SourceFileInfoMap.Instance.Add(document, mappingFileInfo);
                Element rootElement = document["hibernate-mapping"];

                if (rootElement == null)
                {
                    continue;
                }

                XmlAttribute a   = rootElement.Attributes["namespace"];
                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);

                // Ok, pickup subclasses that we found before their superclasses
                ProcessChildren(classMappings);
            }
            // generate source files
            for (IEnumerator iterator = generators.GetEnumerator(); iterator.MoveNext();)
            {
                Generator g = (Generator)iterator.Current;
                g.BaseDirName = outputDir ?? ".\\";
                g.Generate(classMappings, fileCreationObserver, cmdLine.CheckTime != null);
            }
        }
Esempio n. 24
0
        /// <summary> Returns all meta items as one large string.
        ///
        /// </summary>
        /// <returns> String
        /// </returns>
        public virtual string GetMetaAsString(string attribute)
        {
            SupportClass.ListCollectionSupport c = GetMeta(attribute);

            return(MetaAttributeHelper.GetMetaAsString(c));
        }
Esempio n. 25
0
        public virtual bool GetMetaAsBool(string attribute, bool defaultValue)
        {
            SupportClass.ListCollectionSupport c = GetMeta(attribute);

            return(MetaAttributeHelper.GetMetaAsBool(c, defaultValue));
        }
Esempio n. 26
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();
        }
Esempio n. 27
0
 private void InitBlock()
 {
     fields = new SupportClass.ListCollectionSupport();
     imports = new SupportClass.TreeSetSupport();
     subclasses = new SupportClass.ListCollectionSupport();
 }
        public static void Generate(String[] args,IFileCreationObserver fileCreationObserver)
        {
            //this has to change... dirty things during porting
            ClassMapping.ResetComponents();
            nsmgr = new XmlNamespaceManager(new NameTable());
            nsmgr.AddNamespace("urn", "urn:nhibernate-mapping-2.2");
            children = new ArrayList();
            allMaps = new MultiMap();
            ArrayList mappingFiles = new ArrayList();
            string outputDir = null;
            SupportClass.ListCollectionSupport generators = new SupportClass.ListCollectionSupport();
            MultiMap globalMetas = new MultiHashMap();
            // parse command line parameters
            cmdLine = new Hbm2NetParameters(args);
            try
            {
                cmdLine.Parse();
                if (0 == cmdLine.FileNames.Count())
                {
                    Console.Error.WriteLine("No input file(s) specified");
                    throw new NotEnougthParametersException();
                }
            }
            catch (NotEnougthParametersException)
            {
                Console.Error.WriteLine(string.Format("Use:hbm2net {0} files.hbm.xml ( wildcards allowed )",cmdLine.GetShortHelp()));
                Console.Error.WriteLine(cmdLine.GetHelp());
                Environment.Exit(-1);
            }
            if (!string.IsNullOrEmpty(cmdLine.ConfigFile))
            {
                if (File.Exists(cmdLine.ConfigFile))
                {
                    try
                    {
                        FileInfo configFile = new FileInfo(cmdLine.ConfigFile);
                        // parse config xml file
                        Document document = new XmlDocument();
                        document.Load(configFile.FullName);
                        var cfgValidator = new ConfigurationValidator();
                        cfgValidator.Validate(document);
                        if (!string.IsNullOrEmpty(cfgValidator.WarningMessage))
                        {
                            log.Warn("Configuration:" + cfgValidator.WarningMessage);
                        }
                        globalMetas = MetaAttributeHelper.LoadAndMergeMetaMap((document["codegen"]), null);
                        IEnumerator generateElements = document["codegen"].SelectNodes("generate").GetEnumerator();
                        while (generateElements.MoveNext())
                        {
                            generators.Add(new Generator(configFile.Directory, (Element)generateElements.Current));
                        }
                    }
                    catch (ConfigurationValidationException validationException)
                    {
                        Console.Error.WriteLine("Error validating configuration file:" + validationException.Message);
                        Environment.Exit(-1);
                    }
                    catch (Exception genericException)
                    {
                        Console.Error.WriteLine("Error reading configuration file:" + genericException.Message);
                        Environment.Exit(-1);
                    }
                }
                else
                {
                    log.Error("Configuration file:" + cmdLine.ConfigFile + " does not exist");
                    Environment.Exit(-1);
                }
            }
            if (generators.Count == 0)
            {
                log.Info("No configuration file specified: using T4 generator with default template.");
                T4Render t4 = new T4Render();
                t4.Configure(new DirectoryInfo(Directory.GetCurrentDirectory()), new NameValueCollection());
                generators.Add(new Generator(t4));
            }
            if (!string.IsNullOrEmpty(cmdLine.OutputDir))
            {
                outputDir = cmdLine.OutputDir;
            }
            foreach (string inFile in cmdLine.FileNames)
            {
                if (inFile.IndexOf("*") > -1)
                {
                    mappingFiles.AddRange(GetFiles(inFile));
                }
                else
                {
                    mappingFiles.Add(inFile);
                }
            }

            Hashtable classMappings = new Hashtable();
            for (IEnumerator iter = mappingFiles.GetEnumerator(); iter.MoveNext(); )
            {
                log.Info(iter.Current.ToString());

                string mappingFile = (string)iter.Current;
                if (!Path.IsPathRooted(mappingFile))
                {
                    mappingFile = Path.Combine(Environment.CurrentDirectory, mappingFile);
                }
                if (!File.Exists(mappingFile))
                    throw new FileNotFoundException("Mapping file does not exist.", mappingFile);

                // parse the mapping file
                NameTable nt = new NameTable();
                nt.Add("urn:nhibernate-mapping-2.2");
                Document document = new XmlDocument(nt);
                document.Load(mappingFile);
                FileInfo mappingFileInfo = new FileInfo(mappingFile);
                SourceFileInfoMap.Instance.Add(document, mappingFileInfo);
                Element rootElement = document["hibernate-mapping"];

                if (rootElement == null)
                    continue;

                XmlAttribute a = rootElement.Attributes["namespace"];
                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);

                // Ok, pickup subclasses that we found before their superclasses
                ProcessChildren(classMappings);

            }
            // generate source files
            for (IEnumerator iterator = generators.GetEnumerator(); iterator.MoveNext(); )
            {
                Generator g = (Generator)iterator.Current;
                g.BaseDirName = outputDir ?? ".\\";
                g.Generate(classMappings,fileCreationObserver,cmdLine.CheckTime!=null);
            }
        }
Esempio n. 29
0
        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);
        }
Esempio n. 30
0
        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();
            }
        }
        /// <summary> Load meta attributes from jdom element into a MultiMap.
        /// 
        /// </summary>
        /// <returns> MultiMap
        /// </returns>
        protected internal static MultiMap loadMetaMap(Element element)
        {
            MultiMap result = new MultiHashMap();
            SupportClass.ListCollectionSupport metaAttributeList = new SupportClass.ListCollectionSupport();
            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;
        }