/// <seealso cref="org.apache.velocity.runtime.resource.loader.ResourceLoader.init(org.apache.commons.collections.ExtendedProperties)"> /// </seealso> public override void Init(ExtendedProperties configuration) { dataSourceName = StringUtils.NullTrim(configuration.GetString("resource.datasource")); tableName = StringUtils.NullTrim(configuration.GetString("resource.table")); keyColumn = StringUtils.NullTrim(configuration.GetString("resource.keycolumn")); templateColumn = StringUtils.NullTrim(configuration.GetString("resource.templatecolumn")); timestampColumn = StringUtils.NullTrim(configuration.GetString("resource.timestampcolumn")); if (dataSource != null) { if (log.DebugEnabled) { log.Debug("DataSourceResourceLoader: using dataSource instance with table \"" + tableName + "\""); log.Debug("DataSourceResourceLoader: using columns \"" + keyColumn + "\", \"" + templateColumn + "\" and \"" + timestampColumn + "\""); } log.Trace("DataSourceResourceLoader initialized."); } else if (dataSourceName != null) { if (log.DebugEnabled) { log.Debug("DataSourceResourceLoader: using \"" + dataSourceName + "\" datasource with table \"" + tableName + "\""); log.Debug("DataSourceResourceLoader: using columns \"" + keyColumn + "\", \"" + templateColumn + "\" and \"" + timestampColumn + "\""); } log.Trace("DataSourceResourceLoader initialized."); } else { System.String msg = "DataSourceResourceLoader not properly initialized. No DataSource was identified."; log.Error(msg); throw new System.SystemException(msg); } }
public void Initialize(IRuntimeServices rs) { this.rsvc = rs; this.rsvc.Info("Default ResourceManager initializing. (" + base.GetType() + ")"); this.AssembleResourceLoaderInitializers(); for (int i = 0; i < this.sourceInitializerList.Count; i++) { ExtendedProperties extendedProperties = (ExtendedProperties)this.sourceInitializerList[i]; string @string = extendedProperties.GetString("class"); if (@string == null) { this.rsvc.Error("Unable to find '" + extendedProperties.GetString("_RESOURCE_LOADER_IDENTIFIER_") + ".resource.loader.class' specification in configuation. This is a critical value. Please adjust configuration."); } else { ResourceLoader loader = ResourceLoaderFactory.getLoader(this.rsvc, @string); loader.CommonInit(this.rsvc, extendedProperties); loader.Init(extendedProperties); this.resourceLoaders.Add(loader); } } this.logWhenFound = this.rsvc.GetBoolean("resource.manager.logwhenfound", true); string string2 = this.rsvc.GetString("resource.manager.cache.class"); object obj = null; if (string2 != null && string2.Length > 0) { try { Type type = Type.GetType(string2); obj = Activator.CreateInstance(type); } catch (System.Exception var_7_135) { string message = "The specified class for ResourceCache (" + string2 + ") does not exist (or is not accessible to the current classloader)."; this.rsvc.Error(message); obj = null; } if (!(obj is ResourceCache)) { string message = "The specified class for ResourceCache (" + string2 + ") does not implement NVelocity.Runtime.Resource.ResourceCache. Using default ResourceCache implementation."; this.rsvc.Error(message); obj = null; } } if (obj == null) { obj = new ResourceCacheImpl(); } this.globalCache = (ResourceCache)obj; this.globalCache.initialize(this.rsvc); this.rsvc.Info("Default ResourceManager initialization complete."); }
/// <summary> This initialization is used by all resource /// loaders and must be called to set up common /// properties shared by all resource loaders /// </summary> /// <param name="rs"> /// </param> /// <param name="configuration"> /// </param> public virtual void CommonInit(IRuntimeServices rs, ExtendedProperties configuration) { this.rsvc = rs; this.log = rsvc.Log; /* * these two properties are not required for all loaders. * For example, for ClasspathLoader, what would cache mean? * so adding default values which I think are the safest * * don't cache, and modCheckInterval irrelevant... */ try { isCachingOn = configuration.GetBoolean("cache", false); } catch (System.Exception e) { isCachingOn = false; string msg = "Exception parsing cache setting: " + configuration.GetString("cache"); log.Error(msg, e); throw new VelocityException(msg, e); } try { modificationCheckInterval = configuration.GetLong("modificationCheckInterval", 0); } catch (System.Exception e) { modificationCheckInterval = 0; string msg = "Exception parsing modificationCheckInterval setting: " + configuration.GetString("modificationCheckInterval"); log.Error(msg, e); throw new VelocityException(msg, e); } /* * this is a must! */ className = typeof(ResourceCacheImpl).FullName; try { className = configuration.GetString("class", className); } catch (System.Exception e) { string msg = "Exception retrieving resource cache class name"; log.Error(msg, e); throw new VelocityException(msg, e); } }
public void Test_ExtendedProperties() { FileInfo file = new FileInfo("test1.properties"); StreamWriter sw = file.CreateText(); sw.WriteLine("# lines starting with # are comments. Blank lines are ignored"); sw.WriteLine(""); sw.WriteLine("# This is the simplest property"); sw.WriteLine("key = value"); sw.WriteLine(""); sw.WriteLine("# A long property may be separated on multiple lines"); sw.WriteLine("longvalue = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\"); sw.WriteLine(" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); sw.WriteLine(""); sw.WriteLine("# This is a property with many tokens"); sw.WriteLine("tokens_on_a_line = first token, second token"); sw.WriteLine(""); sw.WriteLine("# This sequence generates exactly the same result"); sw.WriteLine("tokens_on_multiple_lines = first token"); sw.WriteLine("tokens_on_multiple_lines = second token"); sw.WriteLine(""); sw.WriteLine("# commas may be escaped in tokens"); sw.WriteLine("commas.excaped = Hi\\, what'up?"); sw.Flush(); sw.Close(); StreamReader sr = file.OpenText(); String s = sr.ReadToEnd(); sr.Close(); // TODO: could build string, then write, then read and compare. ExtendedProperties props = new ExtendedProperties(file.FullName); Assertion.Assert("expected to have 5 properties, had " + props.Count.ToString(), props.Count == 5); Assertion.Assert("key was not correct: " + props.GetString("key"), props.GetString("key").Equals("value")); Assertion.Assert("commas.excaped was not correct: " + props.GetString("commas.excaped"), props.GetString("commas.excaped").Equals("Hi, what'up?")); Object o = props.GetProperty("tokens_on_a_line"); Assertion.Assert("tokens_on_a_line was expected to be an ArrayList", (o is ArrayList)); Assertion.Assert("tokens_on_a_line was expected to be an ArrayList with 2 elements", ((ArrayList)o).Count == 2); StringWriter writer = new StringWriter(); props.Save(writer, "header"); }
/// <summary> Add objects to the context from the current properties. /// * /// </summary> /// <param name="Context">control context to fill with objects /// that are specified in the default.properties /// file /// /// </param> protected internal virtual void fillContextProperties(IContext context) { IDictionaryEnumerator enum_Renamed = props.GetEnumerator(); while (enum_Renamed.MoveNext()) { DictionaryEntry de = (DictionaryEntry)enum_Renamed.Current; String nm = (String)de.Key; if (nm.StartsWith("context.objects.")) { System.String contextObj = (System.String)props.GetString(nm); int colon = nm.LastIndexOf((System.Char) '.'); System.String contextName = nm.Substring(colon + 1); //try { Log.WriteLine(LogPrefix + "loading " + contextObj + " as " + nm); System.Type cls = System.Type.GetType(contextObj); System.Object o = System.Activator.CreateInstance(cls); context.Put(contextName, o); //} catch (System.Exception e) { // SupportClass.WriteStackTrace(e, Console.Error); // //TO DO: Log Something Here //} } } }
public void Test_Run() { String template; Boolean allpass = true; Int32 failures = 0; for (int i = 1;; i++) { template = testProperties.GetString(getTemplateTestKey(i)); if (template != null) { bool pass = RunTest(template); if (!pass) { Console.Out.Write("Adding TemplateTestCase : " + template + "..."); Console.Out.WriteLine("FAIL!"); allpass = false; failures++; } } else { // Assume we're done adding template test cases. break; } } if (!allpass) { Assert.True(false, failures + " templates failed"); } }
public void CommonInit(IRuntimeServices rs, ExtendedProperties configuration) { this.rsvc = rs; this.isCachingOn = configuration.GetBoolean("cache", false); this.modificationCheckInterval = configuration.GetLong("modificationCheckInterval", 0L); this.className = configuration.GetString("class"); }
public override void Init(ExtendedProperties configuration) { if (configuration.GetString("input.encoding") != "UTF-8") { configuration.AddProperty("templateString.encoding", "UTF-8"); } }
/// <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); }
private void initializeDirectiveManager() { String directiveManagerTypeName = configuration.GetString("directive.manager"); if (directiveManagerTypeName == null) { throw new System.Exception("Looks like there's no 'directive.manager' configured. NVelocity can't go any further"); } directiveManagerTypeName = directiveManagerTypeName.Replace(';', ','); Type dirMngType = Type.GetType(directiveManagerTypeName, false, false); if (dirMngType == null) { throw new System.Exception( String.Format("The type {0} could not be resolved", directiveManagerTypeName)); } directiveManager = (IDirectiveManager)Activator.CreateInstance(dirMngType); }
private void VerifyProperties(ExtendedProperties props, String prefix) { Assert.IsTrue(props.Count == 5, "expected to have 5 properties, had " + props.Count); Assert.IsTrue(props.GetString(prefix + "key").Equals("value"), "key was not correct: " + props.GetString(prefix + "key")); // make sure the comma escaping is working correctly Assert.IsTrue(props.GetString(prefix + "commas.excaped").Equals("Hi, what'up?"), "commas.excaped was not correct: " + props.GetString(prefix + "commas.excaped")); // make sure that multiple tokens on a single line are parsed correctly Object o = props.GetProperty(prefix + "tokens_on_a_line"); Assert.IsTrue((o is ArrayList), prefix + "tokens_on_a_line was expected to be an ArrayList"); Assert.IsTrue(((ArrayList)o).Count == 2, prefix + "tokens_on_a_line was expected to be an ArrayList with 2 elements"); // make sure that tokens specified on multiple lines get put together correctly o = props.GetProperty(prefix + "tokens_on_multiple_lines"); Assert.IsTrue((o is ArrayList), prefix + "tokens_on_multiple_lines was expected to be an ArrayList"); Assert.IsTrue(((ArrayList)o).Count == 2, prefix + "tokens_on_multiple_lines was expected to be an ArrayList with 2 elements"); }
/// <summary> /// This initialization is used by all resource /// loaders and must be called to set up common /// properties shared by all resource loaders /// </summary> public void CommonInit(IRuntimeServices rs, ExtendedProperties configuration) { runtimeServices = rs; // these two properties are not required for all loaders. // For example, for ClassPathLoader, what would cache mean? // so adding default values which I think are the safest // don't cache, and modCheckInterval irrelevant... isCachingOn = configuration.GetBoolean("cache", false); modificationCheckInterval = configuration.GetLong("modificationCheckInterval", 0); // this is a must! className = configuration.GetString("class"); }
public NVelocityViewEngine(IDictionary properties) { if (properties == null) { properties = DEFAULT_PROPERTIES; } var props = new ExtendedProperties(); foreach (string key in properties.Keys) { props.AddProperty(key, properties[key]); } _masterFolder = props.GetString("master.folder", string.Empty); _engine = new VelocityEngine(); _engine.Init(props); }
/// <summary> This initialization is used by all resource /// loaders and must be called to set up common /// properties shared by all resource loaders /// </summary> public virtual void commonInit(RuntimeServices rs, ExtendedProperties configuration) { this.rsvc = rs; /* * these two properties are not required for all loaders. * For example, for ClasspathLoader, what would cache mean? * so adding default values which I think are the safest * * don't cache, and modCheckInterval irrelevant... */ isCachingOn_Renamed_Field = configuration.GetBoolean("cache", false); modificationCheckInterval = configuration.GetLong("modificationCheckInterval", 0); /* * this is a must! */ className = configuration.GetString("class"); }
private void VerifyProperties(ExtendedProperties props, String prefix) { Assert.IsTrue(props.Count == 5, "expected to have 5 properties, had " + props.Count); Assert.IsTrue(props.GetString(prefix + "key").Equals("value"), "key was not correct: " + props.GetString(prefix + "key")); // make sure the comma escaping is working correctly Assert.IsTrue(props.GetString(prefix + "commas.excaped").Equals("Hi, what'up?"), "commas.excaped was not correct: " + props.GetString(prefix + "commas.excaped")); // make sure that multiple tokens on a single line are parsed correctly Object o = props.GetProperty(prefix + "tokens_on_a_line"); Assert.IsTrue((o is ArrayList), prefix + "tokens_on_a_line was expected to be an ArrayList"); Assert.IsTrue(((ArrayList) o).Count == 2, prefix + "tokens_on_a_line was expected to be an ArrayList with 2 elements"); // make sure that tokens specified on multiple lines get put together correctly o = props.GetProperty(prefix + "tokens_on_multiple_lines"); Assert.IsTrue((o is ArrayList), prefix + "tokens_on_multiple_lines was expected to be an ArrayList"); Assert.IsTrue(((ArrayList) o).Count == 2, prefix + "tokens_on_multiple_lines was expected to be an ArrayList with 2 elements"); }
/// <seealso cref="org.apache.velocity.runtime.resource.loader.ResourceLoader.Init(org.apache.commons.collections.ExtendedProperties)"> /// </seealso> public override void Init(ExtendedProperties configuration) { log.Trace("StringResourceLoader : initialization starting."); // Get the repository configuration Info string repoClass = configuration.GetString(REPOSITORY_CLASS, REPOSITORY_CLASS_DEFAULT); string repoName = configuration.GetString(REPOSITORY_NAME, REPOSITORY_NAME_DEFAULT); bool isStatic = configuration.GetBoolean(REPOSITORY_STATIC, REPOSITORY_STATIC_DEFAULT); string encoding = configuration.GetString(REPOSITORY_ENCODING); // look for an existing repository of that name and isStatic setting if (isStatic) { this.repository = GetRepository(repoName); if (repository != null && log.DebugEnabled) { log.Debug("Loaded repository '" + repoName + "' from static repo store"); } } else { this.repository = (IStringResourceRepository)rsvc.GetApplicationAttribute(repoName); if (repository != null && log.DebugEnabled) { log.Debug("Loaded repository '" + repoName + "' from application attributes"); } } if (this.repository == null) { // since there's no repository under the repo name, create a new one this.repository = CceateRepository(repoClass, encoding); // and store it according to the isStatic setting if (isStatic) { SetRepository(repoName, this.repository); } else { rsvc.SetApplicationAttribute(repoName, this.repository); } } else { // ok, we already have a repo // Warn them if they are trying to change the class of the repository if (!this.repository.GetType().FullName.Equals(repoClass)) { log.Debug("Cannot change class of string repository '" + repoName + "' from " + this.repository.GetType().FullName + " to " + repoClass + ". The change will be ignored."); } // allow them to change the default encoding of the repo if (encoding != null && !this.repository.Encoding.Equals(encoding)) { if (log.DebugEnabled) { log.Debug("Changing the default encoding of string repository '" + repoName + "' from " + this.repository.Encoding + " to " + encoding); } this.repository.Encoding = encoding; } } log.Trace("StringResourceLoader : initialization complete."); }
/// <summary> Initialize the ResourceManager. /// /// </summary> /// <param name="rsvc"> The Runtime Services object which is associated with this Resource Manager. /// /// </param> /// <throws> Exception </throws> public virtual void Initialize(IRuntimeServices rsvc) { lock (syncOjb) { if (isInit) { log.Debug("Re-initialization of ResourceLoader attempted and ignored."); return; } ResourceLoader resourceLoader = null; this.rsvc = rsvc; log = rsvc.Log; log.Trace("Default ResourceManager initializing. (" + this.GetType() + ")"); AssembleResourceLoaderInitializers(); for (IEnumerator it = sourceInitializerList.GetEnumerator(); it.MoveNext();) { /** * Resource loader can be loaded either via class name or be passed * in as an instance. */ ExtendedProperties configuration = (ExtendedProperties)it.Current; string loaderClass = StringUtils.NullTrim(configuration.GetString("class")); ResourceLoader loaderInstance = (ResourceLoader)configuration["instance"]; if (loaderInstance != null) { resourceLoader = loaderInstance; } else if (loaderClass != null) { resourceLoader = ResourceLoaderFactory.GetLoader(rsvc, loaderClass); } else { string msg = "Unable to find '" + configuration.GetString(RESOURCE_LOADER_IDENTIFIER) + ".resource.loader.class' specification in configuration." + " This is a critical value. Please adjust configuration."; log.Error(msg); throw new System.Exception(msg); } resourceLoader.CommonInit(rsvc, configuration); resourceLoader.Init(configuration); resourceLoaders.Add(resourceLoader); } /* * now see if this is overridden by configuration */ logWhenFound = rsvc.GetBoolean(NVelocity.Runtime.RuntimeConstants.RESOURCE_MANAGER_LOGWHENFOUND, true); /* * now, is a global cache specified? */ string cacheClassName = rsvc.GetString(RuntimeConstants.RESOURCE_MANAGER_CACHE_CLASS); object cacheObject = null; if (!string.IsNullOrEmpty(cacheClassName)) { try { cacheObject = System.Activator.CreateInstance(Type.GetType(cacheClassName.Replace(';', ','))); } catch (System.Exception cnfe) { string msg = "The specified class for ResourceCache (" + cacheClassName + ") does not exist or is not accessible to the current classloader."; log.Error(msg, cnfe); throw cnfe; } if (!(cacheObject is IResourceCache)) { string msg = "The specified resource cache class (" + cacheClassName + ") must implement " + typeof(IResourceCache).FullName; log.Error(msg); throw new System.SystemException(msg); } } /* * if we didn't Get through that, just use the default. */ if (cacheObject == null) { cacheObject = new ResourceCacheImpl(); } globalCache = (IResourceCache)cacheObject; globalCache.Initialize(rsvc); log.Trace("Default ResourceManager initialization complete."); } }
/// <summary> /// Initialize the ResourceManager. /// </summary> public void Initialize(IRuntimeServices rs) { runtimeServices = rs; runtimeServices.Info(string.Format("Default ResourceManager initializing. ({0})", GetType())); ResourceLoader resourceLoader; AssembleResourceLoaderInitializers(); for (int i = 0; i < sourceInitializerList.Count; i++) { ExtendedProperties configuration = (ExtendedProperties)sourceInitializerList[i]; String loaderClass = configuration.GetString("class"); if (loaderClass == null) { runtimeServices.Error( string.Format( "Unable to find '{0}.resource.loader.class' specification in configuration. This is a critical value. Please adjust configuration.", configuration.GetString(RESOURCE_LOADER_IDENTIFIER))); continue; } resourceLoader = ResourceLoaderFactory.getLoader(runtimeServices, loaderClass); resourceLoader.CommonInit(runtimeServices, configuration); resourceLoader.Init(configuration); resourceLoaders.Add(resourceLoader); } // now see if this is overridden by configuration logWhenFound = runtimeServices.GetBoolean(RuntimeConstants.RESOURCE_MANAGER_LOGWHENFOUND, true); // now, is a global cache specified? String resourceManagerCacheClassName = runtimeServices.GetString(RuntimeConstants.RESOURCE_MANAGER_CACHE_CLASS); Object o = null; if (resourceManagerCacheClassName != null && resourceManagerCacheClassName.Length > 0) { try { Type type = Type.GetType(resourceManagerCacheClassName); o = Activator.CreateInstance(type); } catch (Exception) { String err = string.Format( "The specified class for ResourceCache ({0}) does not exist (or is not accessible to the current classLoader).", resourceManagerCacheClassName); runtimeServices.Error(err); o = null; } if (!(o is ResourceCache)) { String err = string.Format( "The specified class for ResourceCache ({0}) does not implement NVelocity.Runtime.Resource.ResourceCache. Using default ResourceCache implementation.", resourceManagerCacheClassName); runtimeServices.Error(err); o = null; } } // if we didn't get through that, just use the default. if (o == null) { o = new ResourceCacheImpl(); } globalCache = (ResourceCache)o; globalCache.initialize(runtimeServices); runtimeServices.Info("Default ResourceManager initialization complete."); }
public virtual void Test_run() { System.IO.StreamWriter result = null; ExtendedProperties c = null; try { assureResultsDirectoryExists(RESULTS_DIR); c = new ExtendedProperties(TEST_CONFIG); result = new System.IO.StreamWriter(getFileName(RESULTS_DIR, "output", "res")); } catch (System.Exception e) { throw new System.Exception("Cannot setup CommonsExtPropTestCase!", e); } message(result, "Testing order of keys ..."); showIterator(result, c.Keys); message(result, "Testing retrieval of CSV values ..."); showVector(result, c.GetVector("resource.loader")); message(result, "Testing subset(prefix).getKeys() ..."); ExtendedProperties subset = c.Subset("file.resource.loader"); showIterator(result, subset.Keys); message(result, "Testing getVector(prefix) ..."); showVector(result, subset.GetVector("path")); message(result, "Testing getString(key) ..."); result.Write(c.GetString("config.string.value")); result.Write("\n\n"); message(result, "Testing getBoolean(key) ..."); //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Boolean.toString' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"' result.Write(c.GetBoolean("config.boolean.value").ToString()); result.Write("\n\n"); message(result, "Testing getByte(key) ..."); result.Write(c.GetByte("config.byte.value").ToString()); result.Write("\n\n"); message(result, "Testing getShort(key) ..."); result.Write(c.GetShort("config.short.value").ToString()); result.Write("\n\n"); message(result, "Testing getInt(key) ..."); result.Write(c.GetInt("config.int.value").ToString()); result.Write("\n\n"); message(result, "Testing getLong(key) ..."); result.Write(c.GetLong("config.long.value").ToString()); result.Write("\n\n"); message(result, "Testing getFloat(key) ..."); result.Write(c.GetFloat("config.float.value").ToString()); result.Write("\n\n"); message(result, "Testing getDouble(key) ..."); result.Write(c.GetDouble("config.double.value").ToString()); result.Write("\n\n"); message(result, "Testing escaped-comma scalar..."); result.Write(c.GetString("escape.comma1")); result.Write("\n\n"); message(result, "Testing escaped-comma vector..."); showVector(result, c.GetVector("escape.comma2")); result.Write("\n\n"); result.Flush(); result.Close(); if (!isMatch(RESULTS_DIR, COMPARE_DIR, "output", "res", "cmp")) { Assertion.Fail("Output incorrect."); } }
// public virtual ExtendedProperties GetContextProperties() { // return contextProperties; // } // // public virtual bool UseClasspath { // set { // this.useClasspath = value; // } // } /// <summary> /// Execute the input script with Velocity /// @throws BuildException /// BuildExceptions are thrown when required attributes are missing. /// Exceptions thrown by Velocity are rethrown as BuildExceptions. /// </summary> protected override void ExecuteTask() { // Make sure the template path is set. if (templatePath == null && useClasspath == false) { throw new BuildException("The template path needs to be defined if you are not using " + "the classpath for locating templates!"); } // Make sure the control template is set. if (controlTemplate == null) { throw new BuildException("The control template needs to be defined!"); } // Make sure the output directory is set. if (outputDirectory == null) { throw new BuildException("The output directory needs to be defined!"); } // Make sure there is an output file. if (outputFile == null) { throw new BuildException("The output file needs to be defined!"); } VelocityEngine ve = new VelocityEngine(); try { // Setup the Velocity Runtime. if (templatePath != null) { //log("Using templatePath: " + templatePath, project.MSG_VERBOSE); Log.WriteLine(LogPrefix + "Using templatePath: " + templatePath); ve.SetProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, templatePath); } if (useClasspath) { Log.WriteLine(LogPrefix + "Using classpath"); ve.AddProperty(RuntimeConstants_Fields.RESOURCE_LOADER, "classpath"); ve.SetProperty("classpath." + RuntimeConstants_Fields.RESOURCE_LOADER + ".class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); ve.SetProperty("classpath." + RuntimeConstants_Fields.RESOURCE_LOADER + ".cache", "false"); ve.SetProperty("classpath." + RuntimeConstants_Fields.RESOURCE_LOADER + ".modificationCheckInterval", "2"); } ve.Init(); // Create the text generator. Generator generator = Generator.Instance; generator.LogPrefix = LogPrefix; generator.VelocityEngine = ve; generator.OutputPath = outputDirectory; generator.InputEncoding = inputEncoding; generator.OutputEncoding = outputEncoding; if (templatePath != null) { generator.TemplatePath = templatePath; } // Make sure the output directory exists, if it doesn't // then create it. System.IO.FileInfo file = new System.IO.FileInfo(outputDirectory); bool tmpBool; if (System.IO.File.Exists(file.FullName)) { tmpBool = true; } else { tmpBool = System.IO.Directory.Exists(file.FullName); } if (!tmpBool) { System.IO.Directory.CreateDirectory(file.FullName); } System.String path = outputDirectory + System.IO.Path.DirectorySeparatorChar.ToString() + outputFile; Log.WriteLine(LogPrefix + "Generating to file " + path); System.IO.StreamWriter writer = generator.getWriter(path, outputEncoding); // The generator and the output path should // be placed in the init context here and // not in the generator class itself. IContext c = initControlContext(); // Everything in the generator class should be // pulled out and placed in here. What the generator // class does can probably be added to the Velocity // class and the generator class can probably // be removed all together. populateInitialContext(c); // Feed all the options into the initial // control context so they are available // in the control/worker templates. if (contextProperties != null) { IEnumerator i = contextProperties.Keys; while (i.MoveNext()) { System.String property = (System.String)i.Current; System.String value_Renamed = contextProperties.GetString(property); // Now lets quickly check to see if what // we have is numeric and try to put it // into the context as an Integer. try { c.Put(property, System.Int32.Parse(value_Renamed)); } catch (System.FormatException nfe) { // Now we will try to place the value into // the context as a boolean value if it // maps to a valid boolean value. System.String booleanString = contextProperties.TestBoolean(value_Renamed); if (booleanString != null) { c.Put(property, booleanString.ToUpper().Equals("TRUE")); } else { // We are going to do something special // for properties that have a "file.contents" // suffix: for these properties will pull // in the contents of the file and make // them available in the context. So for // a line like the following in a properties file: // // license.file.contents = license.txt // // We will pull in the contents of license.txt // and make it available in the context as // $license. This should make texen a little // more flexible. if (property.EndsWith("file.contents")) { // We need to turn the license file from relative to // absolute, and let Ant help :) //value_Renamed = StringUtils.fileContentsToString(project.resolveFile(value_Renamed).CanonicalPath); value_Renamed = StringUtils.fileContentsToString(new FileInfo(value_Renamed).FullName); property = property.Substring(0, (property.IndexOf("file.contents") - 1) - (0)); } c.Put(property, value_Renamed); } } } } writer.Write(generator.parse(controlTemplate, c)); writer.Flush(); writer.Close(); generator.shutdown(); cleanup(); } catch (BuildException e) { throw e; } catch (MethodInvocationException e) { throw new BuildException("Exception thrown by '" + e.ReferenceName + "." + e.MethodName + "'" + ERR_MSG_FRAGMENT, e.WrappedThrowable); } catch (ParseErrorException e) { throw new BuildException("Velocity syntax error" + ERR_MSG_FRAGMENT, e); } catch (ResourceNotFoundException e) { throw new BuildException("Resource not found" + ERR_MSG_FRAGMENT, e); } catch (System.Exception e) { throw new BuildException("Generation failed" + ERR_MSG_FRAGMENT, e); } }
/// <summary> String property accessor method with default to hide the /// configuration implementation. /// /// </summary> /// <param name="String">key property key /// </param> /// <param name="String">defaultValue default value to return if key not /// found in resource manager. /// </param> /// <returns>String value of key or default /// /// </returns> public virtual System.String getString(System.String key, System.String defaultValue) { return(configuration.GetString(key, defaultValue)); }
/// <summary> Initialize the ResourceManager. It is assumed /// that assembleSourceInitializers() has been /// called before this is run. /// </summary> public virtual void initialize(RuntimeServices rs) { rsvc = rs; rsvc.info("Default ResourceManager initializing. (" + this.GetType() + ")"); ResourceLoader resourceLoader; assembleResourceLoaderInitializers(); for (int i = 0; i < sourceInitializerList.Count; i++) { ExtendedProperties configuration = (ExtendedProperties)sourceInitializerList[i]; System.String loaderClass = configuration.GetString("class"); if (loaderClass == null) { rsvc.error("Unable to find '" + configuration.GetString(RESOURCE_LOADER_IDENTIFIER) + ".resource.loader.class' specification in configuation." + " This is a critical value. Please adjust configuration."); continue; } resourceLoader = ResourceLoaderFactory.getLoader(rsvc, loaderClass); resourceLoader.commonInit(rsvc, configuration); resourceLoader.init(configuration); resourceLoaders.Add(resourceLoader); } /* * now see if this is overridden by configuration */ logWhenFound = rsvc.getBoolean(NVelocity.Runtime.RuntimeConstants_Fields.RESOURCE_MANAGER_LOGWHENFOUND, true); /* * now, is a global cache specified? */ System.String claz = rsvc.getString(NVelocity.Runtime.RuntimeConstants_Fields.RESOURCE_MANAGER_CACHE_CLASS); System.Object o = null; if (claz != null && claz.Length > 0) { try { Type type = System.Type.GetType(claz); o = System.Activator.CreateInstance(type); } catch (System.Exception cnfe) { System.String err = "The specified class for ResourceCache (" + claz + ") does not exist (or is not accessible to the current classlaoder)."; rsvc.error(err); o = null; } if (!(o is ResourceCache)) { System.String err = "The specified class for ResourceCache (" + claz + ") does not implement NVelocity.Runtime.Resource.ResourceCache." + " Using default ResourceCache implementation."; rsvc.error(err); o = null; } } /* * if we didn't get through that, just use the default. */ if (o == null) { o = new ResourceCacheImpl(); } globalCache = (ResourceCache)o; globalCache.initialize(rsvc); rsvc.info("Default ResourceManager initialization complete."); }