This class extends normal Java properties by adding the possibility to use the same key many times concatenating the value strings instead of overwriting them.

The Extended Properties syntax is explained here:

  • Each property has the syntax key = value
  • The key may use any character but the equal sign '='.
  • value may be separated on different lines if a backslash is placed at the end of the line that continues below.
  • If value is a list of strings, each token is separated by a comma ','.
  • Commas in each token are escaped placing a backslash right before the comma.
  • If a key is used more than once, the values are appended like if they were on the same line separated with commas.
  • Blank lines and lines starting with character '#' are skipped.
  • If a property is named "include" (or whatever is defined by setInclude() and getInclude() and the value of that property is the full path to a file on disk, that file will be included into the ConfigurationsRepository. You can also pull in files relative to the parent configuration file. So if you have something like the following: include = additional.properties Then "additional.properties" is expected to be in the same directory as the parent configuration file. Duplicate name values will be replaced, so be careful.

Here is an example of a valid extended properties file:

 # lines starting with # are comments # This is the simplest property key = value # A long property may be separated on multiple lines longvalue = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # This is a property with many tokens tokens_on_a_line = first token, second token # This sequence generates exactly the same result tokens_on_multiple_lines = first token tokens_on_multiple_lines = second token # commas may be escaped in tokens commas.excaped = Hi\, what'up? 

NOTE: this class has not been written for performance nor low memory usage. In fact, it's way slower than it could be and generates too much memory garbage. But since performance is not an issue during intialization (and there is not much time to improve it), I wrote it this way. If you don't like it, go ahead and tune it up!

Inheritance: System.Collections.Hashtable
Beispiel #1
1
 static NVelocityHelper()
 {
     _velocity = new VelocityEngine();
     var props = new ExtendedProperties();
     props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, ConfigurationManager.AppSettings["TemplateFolder"]);
     _velocity.Init(props);
 }
Beispiel #2
1
 static NVelocity()
 {
     filePath = Utils.GetMapPath(BaseConfigs.GetForumPath);
     engine = new VelocityEngine();
     props = new ExtendedProperties();
     props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
     props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
     props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, filePath);
     engine.Init(props);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="NVelocityViewEngine"/> class.
        /// </summary>
        /// <param name="assemblies">The assemblies.</param>
        /// <param name="extensionMethodTypes">The extension method types.</param>
        public NVelocityViewEngine(IEnumerable<Assembly> assemblies, params Type[] extensionMethodTypes)
        {
            var properties = new ExtendedProperties();
            properties.AddProperty("resource.loader", "parials");
            properties.AddProperty("parials.resource.loader.class", typeof(PartialFileResourceLoader).AssemblyQualifiedName.Replace(",", ";"));
            properties.AddProperty("parials.resource.loader.assembly", assemblies.Select(a => a.FullName).ToList());
            _engine = new VelocityEngine();
            _engine.Init(properties);

            _extensionMethods = extensionMethodTypes.SelectMany(type => type.GetMethods(BindingFlags.Public | BindingFlags.Static)).Select(method => new DynamicDispatchMethod(method)).ToArray();
        }
 private static string ApplyTemplate(string template, VelocityContext context)
 {
     VelocityEngine velocity = new VelocityEngine();
     ExtendedProperties props = new ExtendedProperties();
     velocity.Init(props);
     using (var writer = new StringWriter(CultureInfo.CurrentCulture))
     {
         velocity.Evaluate(context, writer, string.Empty, template);
         return writer.GetStringBuilder().ToString();
     }
 }
Beispiel #5
1
 static HtmlPage()
 {
     Engine = new VelocityEngine();
     //Engine = NVelocityTemplateEngine.NVelocityEngineFactory.CreateNVelocityAssemblyEngine(Assembly.GetExecutingAssembly().GetName().Name, false);
     //Engine = NVelocityTemplateEngine.NVelocityEngineFactory.CreateNVelocityMemoryEngine(true);
     var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("WebServerTestApp.Views.default.aspx.htm");
     var sr = new StreamReader(stream);
     template = sr.ReadToEnd();
     sr.Dispose();
     ExtendedProperties props = new ExtendedProperties();
     Engine.Init(props);
 }
        public string RenderTemplate(string masterPage, string templateName, IDictionary<string, object> data)
        {
            if (string.IsNullOrEmpty(templateName))
            {
                throw new ArgumentException("The \"templateName\" parameter must be specified", "templateName");
            }

            var name = !string.IsNullOrEmpty(masterPage)
                 ? masterPage : templateName;

            var engine = new VelocityEngine();
            var props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, _templatesPath);
            engine.Init(props);
            var template = engine.GetTemplate(name);
            template.Encoding = Encoding.UTF8.BodyName;
            var context = new VelocityContext();

            var templateData = data ?? new Dictionary<string, object>();
            foreach (var key in templateData.Keys)
            {
                context.Put(key, templateData[key]);
            }

            if (!string.IsNullOrEmpty(masterPage))
            {
                context.Put("childContent", templateName);
            }

            using (var writer = new StringWriter())
            {
                engine.MergeTemplate(name, context, writer);
                return writer.GetStringBuilder().ToString();
            }
        }
Beispiel #7
0
        public static string Format(HttpContext context, string pattern, VelocityContext velocitycontext)
        {
                using (var writer = new StringWriter())
                {
                    try
                    {
                        if (!_isInitialized)
                        {
                            var props = new ExtendedProperties();
                            props.AddProperty("file.resource.loader.path",
                                              new ArrayList(new[]
                                                                {
                                                                    ".",
                                                                    Path.Combine(
                                                                        context.Server.MapPath(feed.HandlerBasePath),
                                                                        "Patterns")
                                                                }));
                            Velocity.Init(props);
                            _isInitialized = true;
                        }
                        //Load patterns
                        var template = Patterns.Get(pattern, () => LoadTemplate(pattern));

                        template.Merge(velocitycontext, writer);
                        return writer.GetStringBuilder().ToString();

                    }
                    catch (Exception)
                    {
                        //Format failed some way
                        return writer.GetStringBuilder().ToString();
                    }
                }
        }
		public void Initialize()
		{
            ActiveRecordStarter.Initialize( new XmlConfigurationSource("activeRecord.xml"),
              typeof(Acl) ,
              typeof(Category) ,
              typeof(Chat) ,
              typeof(ChatMessage) ,
              typeof(ConfigCombo) ,
              typeof(ConfigModel) ,
              typeof(Container) ,
              typeof(Content) ,
              typeof(DataModel) ,
              typeof(Field) ,
              typeof(FieldTemplate) ,
              typeof(CastlePortal.File) ,
              typeof(Forum) ,
              typeof(ForumFolder) ,
              typeof(ForumMessage) ,
              typeof(Group) ,
              typeof(Menu) ,
              typeof(Role) ,
              typeof(CastlePortal.Template) ,
              typeof(CastlePortal.Type) ,
              typeof(Language),
              typeof(MenuTranslation),
              typeof(TypeTranslation),
              typeof(User)
           );
           
           velocity = new VelocityEngine();
           ExtendedProperties props = new ExtendedProperties();
           velocity.Init(props);
		}
		private void SetLoaderPath(ExtendedProperties properties)
		{
			string loaderPath = "";
			// TODO: Solve multiple loader path problem in NVelocity
			if (Template.FileName == "")
			{
				loaderPath = BaseFolder;
			}
			else
			{
				loaderPath = Path.GetDirectoryName(Template.GetFullPath());
				if (loaderPath.IndexOf(BaseFolder) < 0 && loaderPath != BaseFolder)
				{
					loaderPath = BaseFolder + "," + loaderPath;
				}
				else if (loaderPath != BaseFolder)
				{
					loaderPath += "," + BaseFolder;
				}
			}
			// HACK: Setting loader path to base folder until loader problem is solved
			//loaderPath = BaseFolder;
			//System.Diagnostics.Debug.WriteLine("NVeleocity:loaderPath=" + loaderPath);
			if (properties.Contains("file.resource.loader.path"))
			{
				properties["file.resource.loader.path"] = loaderPath;
			}
			else
			{
				properties.AddProperty("file.resource.loader.path", loaderPath);
			}
		}
		protected void InitialiseNVelocity(string templatePath) {

			ExtendedProperties props = new ExtendedProperties();
			props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplatePath);
			
			Velocity.Init(props);
		}
        public static void CreateCode(string filepath, string outputpath, VelocityContext context)
        {
            StreamWriter writer=null;
            try
            {
                VelocityEngine engine = null;//new VelocityEngine();
                ExtendedProperties extendedProperties = new ExtendedProperties();
                //extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, filepath.Substring(0, filepath.LastIndexOf("\\")));

                engine.Init(extendedProperties);
                //Template template = engine.GetTemplate(filepath.Substring(filepath.LastIndexOf("\\")+1));
                //FileStream fos = new FileStream(outputpath + "\\1.vm", FileMode.Create);
                //writer = new StreamWriter(fos);
                //template.Merge(context, writer);
                //writer.Flush();
                //writer.Close();
                StringWriter output=new StringWriter();
                engine.Evaluate(context, output, "", filepath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
Beispiel #12
0
        public void Test()
        {
            var velocityEngine = new VelocityEngine();

            ExtendedProperties extendedProperties = new ExtendedProperties();
            extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH);

            velocityEngine.Init(extendedProperties);

            VelocityContext context = new VelocityContext();

            context.Put("yada", "line");

            Template template = velocityEngine.GetTemplate(
                GetFileName(null, "nv37", TemplateTest.TMPL_FILE_EXT));

            StringWriter writer = new StringWriter();

            #pragma warning disable 612,618
            velocityEngine.MergeTemplate("nv37.vm", context, writer);
            #pragma warning restore 612,618

            //template.Merge(context, writer);

            Console.WriteLine(writer);
        }
 private static ExtendedProperties GetBasicProperties()
 {
     ExtendedProperties properties = new ExtendedProperties();
     properties.AddProperty("resource.loader", "assembly");
     properties.AddProperty("assembly.resource.loader.class",
         "NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader, NVelocity");
     return properties;
 }
        public NVelocityTemplateRepository(string templateDirectory)
        {
            engine = new VelocityEngine();
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templateDirectory);

            engine.Init(props);
        }
Beispiel #15
0
 private VelocityEngine CreateVelocityEngine()
 {
     var velocity = new VelocityEngine();
     var props = new ExtendedProperties();
     props.SetProperty("file.resource.loader.path", _templateDirectory);
     velocity.Init(props);
     return velocity;
 }
 /// <inheritdoc />
 public VelocityEngine CreateVelocityEngine()
 {
     var properties = new ExtendedProperties();
     SetupVelocityEngine(properties);
     var engine = new VelocityEngine(properties);
     engine.Init();
     return engine;
 }
Beispiel #17
0
 public TemplateHelper(string templatePath)
 {
     velocity = new VelocityEngine();
     ExtendedProperties props = new ExtendedProperties();
     props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath);
     props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
     velocity.Init(props);
     context = new VelocityContext();
 }
        public virtual bool Configure()
        {
            _engine = new VelocityEngine();
            var props = new ExtendedProperties();
            props.AddProperty("file.resource.loader.path", TemplatePath);
            _engine.Init(props);

            return true;
        }
Beispiel #19
0
 private VelocityEngine GetInitialisedEngine()
 {
     VelocityEngine engine = new VelocityEngine();
     ExtendedProperties properties = new ExtendedProperties();
     properties.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
     properties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, agencyService.CurrentAgency.TemplateDirectory);
     engine.Init(properties);
     return engine;
 }
		/// <summary> 
		/// Initialize the template loader with a
		/// a resources class.
		/// </summary>
		public override void Init(ExtendedProperties configuration)
		{
			assemblyNames = configuration.GetVector("assembly");
			prefixes = configuration.GetVector("prefix");
			if (assemblyNames.Count != prefixes.Count)
			{
				throw new ResourceNotFoundException("Need to specify prefixes!");
			}
		}
        public void  Apply(IEnumerable<ChangeScript> changeScripts)
        {
            string filename = string.Format(CultureInfo.InvariantCulture, "{0}_{1}.vm", this.syntax, this.GetTemplateQualifier());

            var model = new Hashtable();
            
            model.Add("scripts", changeScripts);
            model.Add("changeLogTableName", this.changeLogTableName);
            model.Add("delimiter", this.delimiter);
            model.Add("separator", this.delimiterType is RowDelimiter ? Environment.NewLine : string.Empty);

            try
            {
                ExtendedProperties props = new ExtendedProperties();

                var assemblyName = typeof(TemplateBasedApplier).Assembly.GetName().Name;

                ReplaceManagersWithDbDeployVersions(props, assemblyName);

                if (this.templateDirectory == null)
                {
                    props.AddProperty("resource.loader", "assembly");

                    // The ";" will be replaced by "," in the resource loader factory.
                    // This is because if we add a property with a comma in the value, it will add *two* values to the property.
                    props.AddProperty(
                        "assembly.resource.loader.class",
                        typeof(DbDeployAssemblyResourceLoader).FullName + "; " + assemblyName);

                    props.AddProperty("assembly.resource.loader.assembly", assemblyName);
                    filename = "Net.Sf.Dbdeploy.Resources." + filename;
                }
                else
                {
                    props.SetProperty("file.resource.loader.path", this.templateDirectory.FullName);
                }

                var templateEngine = new VelocityEngine(props);

                var context = new VelocityContext(model);

                Template template = templateEngine.GetTemplate(filename);

                template.Merge(context, this.writer);
            }
            catch (ResourceNotFoundException ex)
            {
                string locationMessage = templateDirectory == null 
                    ? string.Empty 
                    : (" at " + templateDirectory.FullName);

                throw new UsageException(
                    "Could not find template named " + filename + locationMessage + Environment.NewLine + "Check that you have got the name of the database syntax correct.",
                    ex);
            }
        }
        public override void Configure(DirectoryInfo workingDirectory, NameValueCollection props)
        {
            try
            {
                File.Delete("nvelocity.log");
            }
            catch (IOException)
            {
                // TODO: This is evil! need to investigate further. Cannot get
                // exclusive lock on the log file with this assembly now a
                // library (as opposed to an exe). However not convinced that
                // the line isn't a hangover from java conversion. Need to
                // investigate further.
                ;
            }
            base.Configure(workingDirectory, props);
            ExtendedProperties p = new ExtendedProperties();
            string templateName = props["template"];
            string templateSrc;
            if (templateName == null)
            {
                log.Info("No template file was specified, using default");
                p.SetProperty("resource.loader", "class");
                p.SetProperty("class.resource.loader.class", "NHibernate.Tool.hbm2net.StringResourceLoader;NHibernate.Tool.hbm2net");
                templateSrc =
                    new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("NHibernate.Tool.hbm2net.convert.vm")).
                        ReadToEnd();
            }
            else
            {
                // NH-242 raised issue of where NVelocity looks when supplied with a unpathed file name. Hence
                // will take responsiblity of explicitly instructing NVelocity where to look.
                if (!Path.IsPathRooted(templateName))
                {
                    templateName = Path.Combine(this.WorkingDirectory.FullName, templateName);
                }
                if (!File.Exists(templateName))
                {
                    string msg =
                        string.Format("Cannot find template file using absolute path or relative to '{0}'.",
                                      this.WorkingDirectory.FullName);
                    throw new IOException(msg);
                }

                p.SetProperty("resource.loader", "class");
                p.SetProperty("class.resource.loader.class", "NHibernate.Tool.hbm2net.StringResourceLoader;NHibernate.Tool.hbm2net");
                using (StreamReader sr = new StreamReader(File.OpenRead(templateName)))
                {
                    templateSrc = sr.ReadToEnd();
                    sr.Close();
                }
            }
            ve = new VelocityEngine();
            ve.Init(p);
            template = ve.GetTemplate(templateSrc);
        }
	/// <summary>
	/// overridden LoadConfiguration that will create a properties file on the fly
	/// </summary>
	/// <returns></returns>
	protected override ExtendedProperties LoadConfiguration() {
	    ExtendedProperties p = new ExtendedProperties();

	    // override the loader path and log file locations based on where the physical application path is
	    p.SetProperty(NVelocity.Runtime.RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, context.Request.PhysicalApplicationPath);
	    p.SetProperty(NVelocity.Runtime.RuntimeConstants_Fields.RUNTIME_LOG,
			  context.Request.PhysicalApplicationPath + p.GetString(NVelocity.Runtime.RuntimeConstants_Fields.RUNTIME_LOG, "nvelocity.log"));

	    return p;
	}
Beispiel #24
0
	/// <summary>
	/// Load properties from either a file in the templatePath if there
	/// is one or the classPath.
	/// </summary>
	/// <param name="propertiesFile">the properties file to load through
	/// either the templatePath or the classpath.
	/// </param>
	/// <returns>a properties instance filled with the properties found
	/// in the file or an empty instance if no file was found.
	/// </returns>
	public virtual ExtendedProperties load(System.String propertiesFile) {
	    ExtendedProperties properties = new ExtendedProperties();
	    System.String templatePath = Generator.Instance.TemplatePath;
	    if (templatePath != null) {
		properties = loadFromTemplatePath(propertiesFile);
	    } else {
		properties = loadFromClassPath(propertiesFile);
	    }

	    return properties;
	}
Beispiel #25
0
		/// <summary>
		/// Creates an instance of the EmailBuilder using the specified properties.
		/// </summary>
		/// <param name="nvelocityProperties"></param>
		public EmailBuilder(IDictionary<string, object> nvelocityProperties)
		{
			var properties = new ExtendedProperties();

			foreach (var pair in nvelocityProperties)
			{
				properties.AddProperty(pair.Key, pair.Value);
			}

			velocityEngine = new VelocityEngine();
			velocityEngine.Init(properties);
		}
	public override void init(ExtendedProperties configuration) {
	    rsvc.info("FileResourceLoader : initialization starting.");

	    paths = configuration.GetVector("path");

	    // lets tell people what paths we will be using
	    foreach(String path in paths) {
		rsvc.info("FileResourceLoader : adding path '" + path + "'");
	    }

	    rsvc.info("FileResourceLoader : initialization complete.");
	}
 public override void Init(ExtendedProperties configuration)
 {
     this.pluginNameAndPathSplitString = configuration.GetString("class.pluginNameAndPathSplitString");
     if (this.pluginNameAndPathSplitString == null)
         this.pluginNameAndPathSplitString = ":";
     this.viewNamePrefix = configuration.GetString("class.viewNamePrefix");
     if (this.viewNamePrefix == null)
         this.viewNamePrefix = "view/";
     this.viewNameSuffix = configuration.GetString("class.viewNameSuffix");
     if (this.viewNameSuffix == null)
         this.viewNameSuffix = ".html";
 }
		private ExtendedProperties LoadExtendedProperties()
		{
			ExtendedProperties properties = new ExtendedProperties();
			if (File.Exists(BaseFolder + "\\nvelocity.properties"))
			{
				using (FileStream fs = new FileStream(BaseFolder + "\\nvelocity.properties", FileMode.Open, FileAccess.Read))
				{
					properties.Load(fs);
					fs.Flush();
					fs.Close();
				}
			}
			return properties;
		}
Beispiel #29
0
	/// <summary>
	/// Load a properties file from the templatePath defined in the
	/// generator. As the templatePath can contains multiple paths,
	/// it will cycle through them to find the file. The first file
	/// that can be successfully loaded is considered. (kind of
	/// like the java classpath), it is done to clone the Velocity
	/// process of loading templates.
	/// </summary>
	/// <param name="propertiesFile">the properties file to load. It must be
	/// a relative pathname.
	/// </param>
	/// <returns>a properties instance loaded with the properties from
	/// the file. If no file can be found it returns an empty instance.
	/// </returns>
	protected internal virtual ExtendedProperties loadFromTemplatePath(System.String propertiesFile) {
	    ExtendedProperties properties = new ExtendedProperties();
	    System.String templatePath = Generator.Instance.TemplatePath;

	    // We might have something like the following:
	    //
	    // #set ($dbprops = $properties.load("$generator.templatePath/path/props")
	    //
	    // as we have in Torque but we want people to start using
	    //
	    // #set ($dbprops = $properties.load("path/props")
	    //
	    // so that everything works from the filesystem or from
	    // a JAR. So the actual Generator.getTemplatePath()
	    // is not deprecated but it's use in templates
	    // should be.
	    SupportClass.Tokenizer st = new SupportClass.Tokenizer(templatePath, ",");
	    while (st.HasMoreTokens()) {
		System.String templateDir = st.NextToken();
		try {
		    // If the properties file is being pulled from the
		    // file system and someone is using the method whereby
		    // the properties file is assumed to be in the template
		    // path and they are simply using:
		    //
		    // #set ($dbprops = $properties.load("props") (1)
		    //
		    // than we have to tack on the templatePath in order
		    // for the properties file to be found. We want (1)
		    // to work whether the generation is being run from
		    // the file system or from a JAR file.
		    System.String fullPath = propertiesFile;

		    // FIXME probably not that clever since there could be
		    // a mix of file separators and the test will fail :-(
		    if (!fullPath.StartsWith(templateDir)) {
			fullPath = templateDir + "\\" + propertiesFile;
		    }

		    properties.Load(new System.IO.FileStream(fullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read));
		    // first pick wins, we don't need to go further since
		    // we found a valid file.
		    break;
		} catch (System.Exception) {
		    // do nothing
		}
	    }
	    return properties;
	}
        public VelocityTextTemplateEngine(string logTag)
        {
            if (string.IsNullOrEmpty(logTag))
            {
                throw new ArgumentNullException("logTag");
            }

            this.logTag = logTag;
            var props = new ExtendedProperties();
            //Register Log System here
            //We met a fake logging system in NVelocity, shame on NVelocity!
            //https://github.com/castleproject/NVelocity/blob/master/src/NVelocity/Runtime/RuntimeInstance.cs
            //props.AddProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "My LogSystem Name");
            this.engine.Init(props);
        }