示例#1
0
        /// <summary> Create a new generator object with default properties.
        /// *
        /// </summary>
        /// <returns>Generator generator used in the control context.
        ///
        /// </returns>

        /// <summary> Set the velocity engine.
        /// </summary>

        /// <summary> Create a new generator object with properties loaded from
        /// a file.  If the file does not exist or any other exception
        /// occurs during the reading operation the default properties
        /// are used.
        /// *
        /// </summary>
        /// <param name="String">properties used to help populate the control context.
        /// </param>
        /// <returns>Generator generator used in the control context.
        ///
        /// </returns>
        public Generator(System.String propFile)
        {
            ResourceLocator rl = new ResourceLocator(propFile);

            if (rl.Exists)
            {
                Stream s = rl.OpenRead();
                props.Load(rl.OpenRead());
                s.Close();
            }
            else
            {
                setDefaultProps();
            }
        }
示例#2
0
        /// <summary>
        /// Load a properties file from the classpath
        /// </summary>
        /// <param name="propertiesFile">the properties file to load.</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 loadFromClassPath(String propertiesFile)
        {
            ExtendedProperties properties = new ExtendedProperties();

            try {
                // This is a hack for now to make sure that properties
                // files referenced in the filesystem work in
                // a JAR file. We have to deprecate the use
                // of $generator.templatePath in templates first
                // and this hack will allow those same templates
                // that use $generator.templatePath to work in
                // JAR files.
                if (propertiesFile.StartsWith("$generator"))
                {
                    propertiesFile = propertiesFile.Substring("$generator.templatePath/".Length);
                }

                ResourceLocator rl          = new ResourceLocator(propertiesFile);
                Stream          inputStream = rl.OpenRead();
                properties.Load(inputStream);
            } catch (System.IO.IOException) {
                // do nothing
            }
            return(properties);
        }
示例#3
0
        /// <summary> Initializes the Velocity Runtime with properties file.
        /// The properties file may be in the file system proper,
        /// or the properties file may be in the classpath.
        /// </summary>
        private void  setDefaultProperties()
        {
            //UPGRADE_ISSUE: Class 'java.lang.ClassLoader' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javalangClassLoader"'
            //UPGRADE_ISSUE: Method 'java.lang.Class.getClassLoader' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javalangClassgetClassLoader"'
            //	    ClassLoader classLoader = this.GetType().getClassLoader();
            //
            //	    try {
            //		//UPGRADE_TODO: Method java.lang.ClassLoader.getResourceAsStream was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"'
            //		System.IO.Stream inputStream = classLoader.getResourceAsStream(NVelocity.Runtime.RuntimeConstants_Fields.DEFAULT_RUNTIME_PROPERTIES);
            //		FileInfo file = new FileInfo(NVelocity.Runtime.RuntimeConstants_Fields.DEFAULT_RUNTIME_PROPERTIES);
            //
            //		configuration.Load(inputStream);
            //
            //		info("Default Properties File: " + new System.IO.FileInfo(NVelocity.Runtime.RuntimeConstants_Fields.DEFAULT_RUNTIME_PROPERTIES).FullName);
            //	    }
            //	    catch (System.IO.IOException ioe) {
            //		System.Console.Error.WriteLine("Cannot get Velocity Runtime default properties!");
            //	    }

            // TODO - there might be a better way

            try {
                ResourceLocator file = new ResourceLocator(RuntimeConstants_Fields.DEFAULT_RUNTIME_PROPERTIES);
                configuration.Load(file.OpenRead());
                info("Default Properties File: " + file.FullName);
            } catch (System.Exception ex) {
                debugOutput.WriteLine("Cannot get NVelocity Runtime default properties!\n" + ex.Message);
                debugOutput.Flush();
            }
        }
示例#4
0
        private void initializeDirectives()
        {
            this.initializeDirectiveManager();
            ExtendedProperties extendedProperties = new ExtendedProperties();

            try
            {
                extendedProperties.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream("NVelocity.Runtime.Defaults.directive.properties"));
            }
            catch (System.Exception ex)
            {
                throw new System.Exception("Error loading directive.properties! Something is very wrong if these properties aren't being located. Either your Velocity distribution is incomplete or your Velocity jar file is corrupted!\n" + ex.Message);
            }
            IEnumerator enumerator = extendedProperties.Values.GetEnumerator();

            while (enumerator.MoveNext())
            {
                string directiveTypeName = (string)enumerator.Current;
                this.directiveManager.Register(directiveTypeName);
            }
            string[] stringArray = this.configuration.GetStringArray("userdirective");
            for (int i = 0; i < stringArray.Length; i++)
            {
                this.directiveManager.Register(stringArray[i]);
            }
        }
        /// <summary>
        /// Starts/configure NVelocity based on the properties.
        /// </summary>
        public void BeginInit()
        {
            vengine = new VelocityEngine();

            var props = new ExtendedProperties();

            var expandedTemplateDir = ExpandTemplateDir(templateDir);

            Log.InfoFormat("Initializing NVelocityTemplateEngine component using template directory: {0}", expandedTemplateDir);

            var propertiesFile = new FileInfo(Path.Combine(expandedTemplateDir, "nvelocity.properties"));

            if (propertiesFile.Exists)
            {
                Log.Info("Found 'nvelocity.properties' on template dir, loading as base configuration");
                using (Stream stream = propertiesFile.OpenRead())
                    props.Load(stream);
            }

            props.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, expandedTemplateDir);
            props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, EnableCache ? "true" : "false");

            vengine.Init(props);
        }
示例#6
0
        /// <summary> This methods initializes all the directives
        /// that are used by the Velocity Runtime. The
        /// directives to be initialized are listed in
        /// the RUNTIME_DEFAULT_DIRECTIVES properties
        /// file.
        ///
        /// @throws Exception
        /// </summary>
        private void initializeDirectives()
        {
            initializeDirectiveManager();

            /*
             * Initialize the runtime directive table.
             * This will be used for creating parsers.
             */
            // runtimeDirectives = new Hashtable();

            ExtendedProperties directiveProperties = new ExtendedProperties();

            /*
             * Grab the properties file with the list of directives
             * that we should initialize.
             */

            try
            {
                directiveProperties.Load(
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(RuntimeConstants.DEFAULT_RUNTIME_DIRECTIVES));
            }
            catch (System.Exception ex)
            {
                throw new System.Exception(
                          string.Format(
                              "Error loading directive.properties! Something is very wrong if these properties aren't being located. Either your Velocity distribution is incomplete or your Velocity jar file is corrupted!\n{0}",
                              ex.Message));
            }

            /*
             * Grab all the values of the properties. These
             * are all class names for example:
             *
             * NVelocity.Runtime.Directive.Foreach
             */
            IEnumerator directiveClasses = directiveProperties.Values.GetEnumerator();

            while (directiveClasses.MoveNext())
            {
                String directiveClass = (String)directiveClasses.Current;
                // loadDirective(directiveClass);
                directiveManager.Register(directiveClass);
            }

            /*
             *  now the user's directives
             */
            String[] userdirective = configuration.GetStringArray("userdirective");
            for (int i = 0; i < userdirective.Length; i++)
            {
                // loadDirective(userdirective[i]);
                directiveManager.Register(userdirective[i]);
            }
        }
示例#7
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);
        }
示例#8
0
 /// <summary> Initializes the Velocity Runtime with properties file.
 /// The properties file may be in the file system proper,
 /// or the properties file may be in the classpath.
 /// </summary>
 private void setDefaultProperties()
 {
     try
     {
         // TODO: this was modified in v1.4 to use the classloader
         configuration.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream(RuntimeConstants_Fields.DEFAULT_RUNTIME_PROPERTIES));
     }
     catch (System.Exception ex)
     {
         debugOutput.WriteLine("Cannot get NVelocity Runtime default properties!\n" + ex.Message);
         debugOutput.Flush();
     }
 }
        /// <summary>
        /// Starts/configure NVelocity based on the properties.
        /// </summary>
        public void BeginInit()
        {
            vengine = new VelocityEngine();

            ExtendedProperties props = new ExtendedProperties();

            if (!string.IsNullOrEmpty(assemblyName))
            {
                AddResourceAssembly(assemblyName);
            }

            if (assemblies.Count != 0)
            {
                if (log.IsInfoEnabled)
                {
                    log.Info("Initializing NVelocityTemplateEngine component using Assemblies:");
                    foreach (string s in assemblies)
                    {
                        log.InfoFormat(" - {0}", s);
                    }
                }

                props.SetProperty(RuntimeConstants.RESOURCE_LOADER, "assembly");
                props.SetProperty("assembly.resource.loader.class", "NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader;NVelocity");
                props.SetProperty("assembly.resource.loader.cache", EnableCache.ToString().ToLower());
                props.SetProperty("assembly.resource.loader.assembly", assemblies);
            }
            else
            {
                String expandedTemplateDir = ExpandTemplateDir(templateDir);
                log.InfoFormat("Initializing NVelocityTemplateEngine component using template directory: {0}", expandedTemplateDir);

                FileInfo propertiesFile = new FileInfo(Path.Combine(expandedTemplateDir, "nvelocity.properties"));
                if (propertiesFile.Exists)
                {
                    log.Info("Found 'nvelocity.properties' on template dir, loading as base configuration");
                    using (Stream stream = propertiesFile.OpenRead())
                    {
                        props.Load(stream);
                    }
                }

                props.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
                props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, expandedTemplateDir);
                props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, EnableCache.ToString().ToLower());
            }

            vengine.Init(props);
        }
示例#10
0
        /// <summary>
        /// Creates a new instance.
        /// </summary>
        public TemplateTestCase()
        {
            try {
                Velocity.SetProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, NVelocity.Test.TemplateTestBase_Fields.FILE_RESOURCE_LOADER_PATH);

                Velocity.SetProperty(RuntimeConstants_Fields.RUNTIME_LOG_ERROR_STACKTRACE, "true");
                Velocity.SetProperty(RuntimeConstants_Fields.RUNTIME_LOG_WARN_STACKTRACE, "true");
                Velocity.SetProperty(RuntimeConstants_Fields.RUNTIME_LOG_INFO_STACKTRACE, "true");

                Velocity.Init();

                testProperties = new ExtendedProperties();
                testProperties.Load(new FileStream(TemplateTestBase_Fields.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read));
            } catch (System.Exception e) {
                throw new System.Exception("Cannot setup TemplateTestSuite!");
            }
        }
示例#11
0
文件: DvslTask.cs 项目: minskowl/MY
        protected void xExecuteTask()
        {
            int fileCount = fileset.FileNames.Count;

            Log.WriteLine(LogPrefix + "processing {0} files", fileCount);

            foreach (string filename in fileset.FileNames)
            {
                FileInfo file = new FileInfo(filename);
                if (file.Exists)
                {
                    String outfile = filename.Substring(0, filename.Length - file.Extension.Length) + ".html";
                    dvsl = new NVelocity.Dvsl.Dvsl();

                    if (stylesheet == null)
                    {
                        System.Console.Out.WriteLine("usage :need to specify a stylesheet. ");
                        System.Console.Out.WriteLine("Dvsl.exe -STYLE stylesheeet [-IN infile] [-OUT outfile] [-TOOL toolboxname]");
                        return;
                    }
                    else
                    {
                        dvsl.SetStylesheet(stylesheet.FullName);
                    }

                    if (toolboxFile != null)
                    {
                        ExtendedProperties p   = new ExtendedProperties();
                        Stream             fis = new FileStream(toolboxFile.FullName, FileMode.Open, FileAccess.Read);
                        p.Load(fis);
                        fis.Close();
                        dvsl.Toolbox = p;
                    }

                    TextReader reader = new StreamReader(filename);
                    TextWriter writer = new StreamWriter(outfile);

                    long time = dvsl.Transform(reader, writer);
                    writer.Flush();
                    reader.Close();
                    writer.Close();
                }
            }
        }
        protected void SetUp()
        {
            velocityEngine = new VelocityEngine();

            ExtendedProperties extendedProperties = new ExtendedProperties();

            extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
                                           TemplateTest.FILE_RESOURCE_LOADER_PATH);

            extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true");
            extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true");
            extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true");
            extendedProperties.SetProperty("userdirective",
                                           "NVelocity.Runtime.Directive.Component;NVelocity,NVelocity.Runtime.Directive.BlockComponent;NVelocity");

            velocityEngine.Init(extendedProperties);

            testProperties = new ExtendedProperties();
            testProperties.Load(new FileStream(TemplateTest.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read));
        }
        protected void SetUp()
        {
            velocityEngine = new VelocityEngine();

            ExtendedProperties extendedProperties = new ExtendedProperties();

            extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
                                           TemplateTest.FILE_RESOURCE_LOADER_PATH);

            extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true");
            extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true");
            extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true");
            extendedProperties.SetProperty("userdirective",
                                           "NVelocity.Runtime.Directive.Component;NVelocity,NVelocity.Runtime.Directive.BlockComponent;NVelocity");

            velocityEngine.Init(extendedProperties);

            testProperties = new ExtendedProperties();
            testProperties.Load(new FileStream(TemplateTest.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read));
        }
示例#14
0
 /// <summary>
 /// Populates the velocity properties from the given resource
 /// </summary>
 /// <param name="extendedProperties">ExtendedProperties instance to populate</param>
 /// <param name="resource">The resource from which to load the properties</param>
 /// <param name="append">A flag indicated weather the properties loaded from the resource should be appended or replaced in the extendedProperties</param>
 private static void FillProperties(ExtendedProperties extendedProperties, IInputStreamSource resource, bool append)
 {
     try {
         if (append)
         {
             extendedProperties.Load(resource.InputStream);
         }
         else
         {
             ExtendedProperties overrides = new ExtendedProperties();
             overrides.Load(resource.InputStream);
             foreach (DictionaryEntry entry in overrides)
             {
                 extendedProperties.SetProperty(Convert.ToString(entry.Key), entry.Value);
             }
         }
     } finally {
         resource.InputStream.Close();
     }
 }
        public override void Init()
        {
            ExtendedProperties props = new ExtendedProperties();

            String externalProperties = Path.Combine(ViewRootDir, "nvelocity.properties");

            if (File.Exists(externalProperties))
            {
                using (FileStream fs = File.OpenRead(externalProperties))
                {
                    props.Load(fs);
                }
            }

            // Set up a custom directive manager
            props.SetProperty("directive.manager", "Castle.MonoRail.Framework.Views.NVelocity.CustomDirectiveManager; Castle.MonoRail.Framework.Views.NVelocity");

            InitializeVelocityProperties(props);

            velocity.Init(props);
        }
示例#16
0
        public void Initialize()
        {
            var props = new ExtendedProperties();

            if (ViewSourceLoader.HasSource("nvelocity.properties"))
            {
                using (var stream = ViewSourceLoader.GetViewSource("nvelocity.properties").OpenViewStream())
                {
                    props.Load(stream);
                }
            }

            // Set up a custom directive manager
            props.SetProperty("directive.manager",
                              "Castle.MonoRail.Framework.Views.NVelocity.CustomDirectiveManager; Castle.MonoRail.Framework.Views.NVelocity");

            InitializeVelocityProperties(props);

            velocity.SetApplicationAttribute(ServiceProvider, provider);

            velocity.Init(props);
        }
示例#17
0
		/// <summary>
		/// Creates a new instance.
		/// </summary>
		public TemplateTestCase()
		{
			try
			{
				velocityEngine = new VelocityEngine();

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

				extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true");
				extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true");
				extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true");

				velocityEngine.Init(extendedProperties);

				testProperties = new ExtendedProperties();
				testProperties.Load(new FileStream(TemplateTest.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read));
			}
			catch(Exception)
			{
				throw new Exception("Cannot setup TemplateTestSuite!");
			}
		}
示例#18
0
        /// <summary>
        /// Loads the configuration information and returns that
        /// information as a ExtendedProperties, which will be used to
        /// initialize the Velocity runtime.
        /// <br><br>
        /// Currently, this method gets the initialization parameter
        /// VelocityServlet.INIT_PROPS_KEY, which should be a file containing
        /// the configuration information.
        /// <br><br>
        /// To configure your Servlet Spec 2.2 compliant servlet runner to pass
        /// this to you, put the following in your WEB-INF/web.xml file
        /// <br>
        /// <pre>
        ///   &lt;servlet&gt;
        ///     &lt;servlet-name&gt; YourServlet &lt/servlet-name&gt;
        ///     &lt;servlet-class&gt; your.package.YourServlet &lt;/servlet-class&gt;
        ///     &lt;init-param&gt;
        ///        &lt;param-name&gt; properties &lt;/param-name&gt;
        ///        &lt;param-value&gt; velocity.properties &lt;/param-value&gt;
        ///     &lt;/init-param&gt;
        ///   &lt;/servlet&gt;
        ///  </pre>
        ///
        /// Alternately, if you wish to configure an entire context in this
        /// fashion, you may use the following:
        ///  <br>
        ///  <pre>
        ///    &lt;context-param&gt;
        ///       &lt;param-name&gt; properties &lt;/param-name&gt;
        ///       &lt;param-value&gt; velocity.properties &lt;/param-value&gt;
        ///       &lt;description&gt; Path to Velocity configuration &lt;/description&gt;
        ///    &lt;/context-param&gt;
        ///   </pre>
        ///
        /// Derived classes may do the same, or take advantage of this code to do the loading for them via :
        ///  <pre>
        ///     Properties p = super.loadConfiguration( config );
        ///  </pre>
        /// and then add or modify the configuration values from the file.
        /// <br>
        /// </summary>
        /// <returns>ExtendedProperties</returns>
        protected virtual ExtendedProperties LoadConfiguration()
        {
            String propsFile = System.Configuration.ConfigurationSettings.AppSettings[INIT_PROPERTIES_KEY];

            // This will attempt to find the location of the properties
            // file from the relative path to the WAR archive (ie:
            // docroot). Since JServ returns null for getRealPath()
            // because it was never implemented correctly, then we know we
            // will not have an issue with using it this way. I don't know
            // if this will break other servlet engines, but it probably
            // shouldn't since WAR files are the future anyways.
            ExtendedProperties p = new ExtendedProperties();

            if (propsFile != null)
            {
                FileInfo   file = new FileInfo(HttpContext.Current.Request.PhysicalApplicationPath + propsFile);
                FileStream fs   = file.OpenRead();
                p.Load(fs);
                fs.Close();
            }

            return(p);
        }
示例#19
0
        /// <summary>
        /// Creates a new instance.
        /// </summary>
        public TemplateTestCase()
        {
            try
            {
                velocityEngine = new VelocityEngine();

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

                extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true");
                extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true");
                extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true");

                velocityEngine.Init(extendedProperties);

                testProperties = new ExtendedProperties();
                testProperties.Load(new FileStream(TemplateTest.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read));
            }
            catch (Exception)
            {
                throw new Exception("Cannot setup TemplateTestSuite!");
            }
        }
示例#20
0
文件: DvslTask.cs 项目: minskowl/MY
        protected override void ExecuteTask()
        {
            if (stylesheet == null)
            {
                throw new BuildException("no stylesheet specified", Location);
            }

            /*
             * make a DVSL and set validation
             */
            dvsl = new NVelocity.Dvsl.Dvsl();
            dvsl.ValidatingParser = validatingParser;

            /*
             * If a logfile attribute was specified, use that for the log file name,
             * TODO: otherwise use a NVelocity to NAnt logging adapter.
             */
            if (logFile != null)
            {
                dvsl.LogFile = logFile;
            }
            else
            {
                //dvsl.setLogSystem(new AntLogSystem(this));
            }

            /*
             * now the stylesheet
             */
            try {
                Log.WriteLine(LogPrefix + "Loading stylesheet " + stylesheet.FullName);
                dvsl.SetStylesheet(stylesheet);
            } catch (System.Exception ex) {
                Log.WriteLine(LogPrefix + "Failed to read stylesheet " + stylesheet.FullName);
                throw new BuildException(ex.ToString());
            }

            /*
             *  now, if we were given a toolbox, set that up too
             */
            toolboxProps = new ExtendedProperties();

            try {
                if (toolboxFile != null)
                {
                    toolboxProps.Load(toolboxFile.OpenRead());
                }

                /*
                 *  Overlay any parameters
                 */
                //		for (Enumeration e = toolAttr.elements(); e.hasMoreElements();) {
                //		    Tool p = (Tool)e.nextElement();
                //		    toolboxProps.setProperty(p.getName(), p.getValue());
                //		}

                dvsl.Toolbox = toolboxProps;
            } catch (System.Exception ee) {
                throw new BuildException("Error loading the toolbox : " + ee);
            }

            /*
             * if we have an in file and out then process them
             */

            if (inFile != null && outFile != null)
            {
                Process(inFile, outFile, stylesheet);
                return;
            }

            /*
             * if we get here, in and out have not been specified, we are
             * in batch processing mode.
             */

            /*
             *   make sure Source directory exists...
             */
            if (destDir == null)
            {
                throw new BuildException("destdir attributes must be set!");
            }

            Log.WriteLine(LogPrefix + "Transforming into " + destDir);

            /*
             *  Process all the files marked for styling
             */
            // get the base directory from the fileset - needed to colapse ../ syntax
            DirectoryInfo di = new DirectoryInfo(fileset.BaseDirectory);

            // get a list of files to work on
            foreach (string filename in fileset.FileNames)
            {
                String   relativeFilename = filename.Substring(di.FullName.Length + 1);
                FileInfo file             = new FileInfo(filename);
                if (file.Exists)
                {
                    Process(di, file, destDir, stylesheet);
                }
            }
        }
        public static void Main(String[] args)
        {
            Dvsl dvsl = new Dvsl();

            TextReader reader   = Console.In;
            String     infile   = null;
            String     style    = null;
            String     outfile  = null;
            TextWriter writer   = Console.Out;
            String     toolfile = null;

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].Equals("-IN"))
                {
                    infile = args[++i];
                }
                else if (args[i].Equals("-OUT"))
                {
                    outfile = args[++i];
                }
                else if (args[i].Equals("-STYLE"))
                {
                    style = args[++i];
                }
                else if (args[i].Equals("-TOOL"))
                {
                    toolfile = args[++i];
                }
            }

            if (style == null)
            {
                Console.Out.WriteLine("usage :need to specify a stylesheet. ");
                Console.Out.WriteLine("Dvsl.exe -STYLE stylesheeet [-IN infile] [-OUT outfile] [-TOOL toolboxname]");
                return;
            }

            if (style != null)
            {
                dvsl.SetStylesheet(style);
            }

            if (toolfile != null)
            {
                ExtendedProperties p   = new ExtendedProperties();
                Stream             fis = new FileStream(toolfile, FileMode.Open, FileAccess.Read);
                p.Load(fis);

                dvsl.Toolbox = p;
            }

            if (infile != null)
            {
                reader = new StreamReader(infile);
            }

            if (outfile != null)
            {
                writer = new StreamWriter(outfile);
            }

            long time = dvsl.Transform(reader, writer);

            writer.Flush();
        }
示例#22
0
        /// <summary> This methods initializes all the directives
        /// that are used by the Velocity Runtime. The
        /// directives to be initialized are listed in
        /// the RUNTIME_DEFAULT_DIRECTIVES properties
        /// file.
        ///
        /// @throws Exception
        /// </summary>
        private void  initializeDirectives()
        {
            /*
             * Initialize the runtime directive table.
             * This will be used for creating parsers.
             */
            runtimeDirectives = new System.Collections.Hashtable();

            //UPGRADE_TODO: Format of property file may need to be changed. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1089"'
            ExtendedProperties directiveProperties = new ExtendedProperties();

            /*
             * Grab the properties file with the list of directives
             * that we should initialize.
             */

            //	    ClassLoader classLoader = Runtime.class.getClassLoader();
            //	    //UPGRADE_ISSUE: Class 'java.lang.ClassLoader' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javalangClassLoader"'
            //	    //UPGRADE_ISSUE: Method 'java.lang.Class.getClassLoader' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javalangClassgetClassLoader"'
            //	    ClassLoader classLoader = this.GetType().getClassLoader();
            //
            //	    //UPGRADE_TODO: Method java.lang.ClassLoader.getResourceAsStream was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"'
            //	    System.IO.Stream inputStream = classLoader.getResourceAsStream(NVelocity.Runtime.RuntimeConstants_Fields.DEFAULT_RUNTIME_DIRECTIVES);
            //
            //	    if (inputStream == null)
            //	    throw new System.Exception("Error loading directive.properties! " + "Something is very wrong if these properties " + "aren't being located. Either your Velocity " + "distribution is incomplete or your Velocity " + "jar file is corrupted!");
            //
            //	    //UPGRADE_ISSUE: Method 'java.util.Properties.load' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javautilPropertiesload_javaioInputStream"'
            //	    directiveProperties.load(inputStream);
            //
            try {
                ResourceLocator file = new ResourceLocator(RuntimeConstants_Fields.DEFAULT_RUNTIME_DIRECTIVES);
                directiveProperties.Load(file.OpenRead());
            } catch (System.Exception ex) {
                throw new System.Exception("Error loading directive.properties! " + "Something is very wrong if these properties " + "aren't being located. Either your Velocity " + "distribution is incomplete or your Velocity " + "jar file is corrupted!\n" + ex.Message);
            }


            /*
             * Grab all the values of the properties. These
             * are all class names for example:
             *
             * NVelocity.Runtime.Directive.Foreach
             */
            System.Collections.IEnumerator directiveClasses = directiveProperties.Values.GetEnumerator();

            //UPGRADE_TODO: method 'java.util.Enumeration.hasMoreElements' was converted to ' ' which has a different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1073_javautilEnumerationhasMoreElements"'
            while (directiveClasses.MoveNext())
            {
                //UPGRADE_TODO: method 'java.util.Enumeration.nextElement' was converted to ' ' which has a different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1073_javautilEnumerationnextElement"'
                System.String directiveClass = (System.String)directiveClasses.Current;
                loadDirective(directiveClass, "System");
            }

            /*
             *  now the user's directives
             */
            System.String[] userdirective = configuration.GetStringArray("userdirective");
            for (int i = 0; i < userdirective.Length; i++)
            {
                loadDirective(userdirective[i], "User");
            }
        }
示例#23
0
        /// <summary>
        /// Creates a new instance.
        /// </summary>
        public TemplateTestCase()
        {
            try
            {
                velocityEngine = new VelocityEngine();

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

                extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true");
                extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true");
                extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true");

                velocityEngine.Init(extendedProperties);

                testProperties = new ExtendedProperties();
                testProperties.Load(new FileStream(TemplateTest.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read));
            }
            catch (Exception)
            {
                throw new Exception("Cannot setup TemplateTestSuite!");
            }

            provider = new TestProvider();
            al       = provider.Customers;
            h        = new Hashtable();

            SupportClass.PutElement(h, "Bar", "this is from a hashtable!");
            SupportClass.PutElement(h, "Foo", "this is from a hashtable too!");

            /*
             *  lets set up a vector of objects to test late introspection. See ASTMethod.java
             */

            vec = new ArrayList();

            vec.Add(new String("string1".ToCharArray()));
            vec.Add(new String("string2".ToCharArray()));

            /*
             *  set up 3 chained contexts, and add our data
             *  through the 3 of them.
             */

            context2 = new VelocityContext();
            context1 = new VelocityContext(context2);
            context  = new VelocityContext(context1);

            context.Put("provider", provider);
            context1.Put("name", "jason");
            context2.Put("providers", provider.Customers2);
            context.Put("list", al);
            context1.Put("hashtable", h);
            context2.Put("hashmap", new Hashtable());
            context2.Put("search", provider.Search);
            context.Put("relatedSearches", provider.RelSearches);
            context1.Put("searchResults", provider.RelSearches);
            context2.Put("stringarray", provider.Array);
            context.Put("vector", vec);
            context.Put("mystring", new String(string.Empty.ToCharArray()));
            context.Put("runtime", new FieldMethodizer("NVelocity.Runtime.RuntimeSingleton"));
            context.Put("fmprov", new FieldMethodizer(provider));
            context.Put("Floog", "floogie woogie");
            context.Put("boolobj", new BoolObj());

            /*
             *  we want to make sure we test all types of iterative objects
             *  in #foreach()
             */

            Object[] oarr   = new Object[] { "a", "b", "c", "d" };
            int[]    intarr = new int[] { 10, 20, 30, 40, 50 };

            context.Put("collection", vec);
            context2.Put("iterator", vec.GetEnumerator());
            context1.Put("map", h);
            context.Put("obarr", oarr);
            context.Put("enumerator", vec.GetEnumerator());
            context.Put("intarr", intarr);
        }