Exemplo n.º 1
0
 public ScriptServicesBuilder(IConsole console, ILog logger, IRuntimeServices runtimeServices = null)
 {
     _initializationServices = new InitializationServices(logger);
     _runtimeServices        = runtimeServices;
     _console = console;
     _logger  = logger;
 }
Exemplo n.º 2
0
 /// <summary> Called when an invalid set method is encountered.
 ///
 /// </summary>
 /// <param name="rsvc">current instance of RuntimeServices
 /// </param>
 /// <param name="context">the context when the reference was found invalid
 /// </param>
 /// <param name="leftreference">left reference being assigned to
 /// </param>
 /// <param name="rightreference">invalid reference on the right
 /// </param>
 /// <param name="Info">contains Info on template, line, col
 /// </param>
 public static void InvalidSetMethod(IRuntimeServices rsvc, IInternalContextAdapter context, string leftreference, string rightreference, Info info)
 {
     /**
      * ignore return value
      */
     InvalidReferenceHandlerCall(new NVelocity.App.Event.InvalidSetMethodExecutor(context, leftreference, rightreference, info), rsvc, context);
 }
Exemplo n.º 3
0
 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");
 }
Exemplo n.º 4
0
        /// <summary> Called when a null is evaluated during a #set. All event handlers are
        /// called in sequence until a false is returned. The default implementation
        /// always returns true.
        ///
        /// </summary>
        /// <param name="lhs">Left hand side of the expression.
        /// </param>
        /// <param name="rhs">Right hand side of the expression.
        /// </param>
        /// <param name="rsvc">current instance of RuntimeServices
        /// </param>
        /// <param name="context">The internal context adapter.
        /// </param>
        /// <returns> true if to be logged, false otherwise
        /// </returns>
        public static bool ShouldLogOnNullSet(IRuntimeServices rsvc, IInternalContextAdapter context, string lhs, string rhs)
        {
            // app level cartridges have already been initialized
            EventCartridge ev1 = rsvc.ApplicationEventCartridge;

            System.Collections.IEnumerator applicationEventHandlerIterator = (ev1 == null) ? null : ev1.NullSetEventHandlers;

            EventCartridge ev2 = context.EventCartridge;

            InitializeEventCartridge(rsvc, ev2);
            System.Collections.IEnumerator contextEventHandlerIterator = (ev2 == null) ? null : ev2.NullSetEventHandlers;

            try
            {
                IEventHandlerMethodExecutor methodExecutor = new ShouldLogOnNullSetExecutor(context, lhs, rhs);

                CallEventHandlers(applicationEventHandlerIterator, contextEventHandlerIterator, methodExecutor);

                return((System.Boolean)methodExecutor.ReturnValue);
            }
            catch (System.SystemException e)
            {
                throw e;
            }
            catch (System.Exception e)
            {
                throw new RuntimeException("Exception in event handler.", e);
            }
        }
Exemplo n.º 5
0
        /// <summary> Called when an include-type directive is encountered (#include or
        /// #parse). All the registered event handlers are called unless null is
        /// returned. The default implementation always processes the included
        /// resource.
        ///
        /// </summary>
        /// <param name="includeResourcePath">the path as given in the include directive.
        /// </param>
        /// <param name="currentResourcePath">the path of the currently rendering template that includes the
        /// include directive.
        /// </param>
        /// <param name="directiveName">name of the directive used to include the resource. (With the
        /// standard directives this is either "parse" or "include").
        /// </param>
        /// <param name="rsvc">current instance of RuntimeServices
        /// </param>
        /// <param name="context">The internal context adapter.
        ///
        /// </param>
        /// <returns> a new resource path for the directive, or null to block the
        /// include from occurring.
        /// </returns>
        public static string IncludeEvent(IRuntimeServices rsvc, IInternalContextAdapter context, string includeResourcePath, string currentResourcePath, string directiveName)
        {
            // app level cartridges have already been initialized
            EventCartridge ev1 = rsvc.ApplicationEventCartridge;

            System.Collections.IEnumerator applicationEventHandlerIterator = (ev1 == null) ? null : ev1.IncludeEventHandlers;

            EventCartridge ev2 = context.EventCartridge;

            InitializeEventCartridge(rsvc, ev2);
            System.Collections.IEnumerator contextEventHandlerIterator = (ev2 == null) ? null : ev2.IncludeEventHandlers;

            try
            {
                IEventHandlerMethodExecutor methodExecutor = new NVelocity.App.Event.IncludeEventExecutor(context, includeResourcePath, currentResourcePath, directiveName);

                CallEventHandlers(applicationEventHandlerIterator, contextEventHandlerIterator, methodExecutor);

                return((string)methodExecutor.ReturnValue);
            }
            catch (System.SystemException e)
            {
                throw e;
            }
            catch (System.Exception e)
            {
                throw new RuntimeException("Exception in event handler.", e);
            }
        }
Exemplo n.º 6
0
        public ScriptServices Build()
        {
            var defaultExecutorType = typeof(ScriptExecutor);

            _scriptExecutorType = Overrides.ContainsKey(typeof(IScriptExecutor))
                ? (Type)Overrides[typeof(IScriptExecutor)]
                : defaultExecutorType;

            var defaultReplType = typeof(Repl);

            _replType = Overrides.ContainsKey(typeof(IRepl)) ? (Type)Overrides[typeof(IRepl)] : defaultReplType;

            _scriptEngineType = (Type)Overrides[typeof(IScriptEngine)];

            var initDirectoryCatalog = _scriptName != null || _repl;

            if (_runtimeServices == null)
            {
                _runtimeServices = new RuntimeServices(
                    _logger,
                    Overrides,
                    ConsoleInstance,
                    _scriptEngineType,
                    _scriptExecutorType,
                    _replType,
                    initDirectoryCatalog,
                    InitializationServices,
                    _scriptName);
            }

            return(_runtimeServices.GetScriptServices());
        }
Exemplo n.º 7
0
        /// <summary> Called automatically when event cartridge is initialized.
        ///
        /// </summary>
        /// <param name="rs">instance of RuntimeServices
        /// </param>
        public virtual void SetRuntimeServices(IRuntimeServices rs)
        {
            this.rs = rs;

            /**
             * Get the regular expression pattern.
             */
            matchRegExp = StringUtils.NullTrim(rs.Configuration.GetString(MatchAttribute));
            if ((matchRegExp != null) && (matchRegExp.Length == 0))
            {
                matchRegExp = null;
            }

            /**
             * Test the regular expression for a well formed pattern
             */
            if (matchRegExp != null)
            {
                try
                {
                    System.Text.RegularExpressions.Regex.Match("", matchRegExp);
                }
                catch (ArgumentException E)
                {
                    rs.Log.Error("Invalid regular expression '" + matchRegExp + "'.  No escaping will be performed.", E);
                    matchRegExp = null;
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>  ctor for current impl
        /// *
        /// takes the reference literal we are proxying for, the literal
        /// the VM we are for is called with...
        /// *
        /// </summary>
        /// <param name="rs">
        /// </param>
        /// <param name="contextRef">reference arg in the definition of the VM, used in the VM
        /// </param>
        /// <param name="callerRef"> reference used by the caller as an arg to the VM
        /// </param>
        /// <param name="t"> type of arg : JJTREFERENCE, JJTTRUE, etc
        ///
        /// </param>
        public VMProxyArg(IRuntimeServices rs, String contextRef, String callerRef, int t)
        {
            runtimeServices = rs;

            contextReference = contextRef;
            callerReference  = callerRef;
            type             = t;

            // make our AST if necessary
            setup();

            // if we are multi-node tree, then save the size to
            // avoid fn call overhead
            if (nodeTree != null)
            {
                numTreeChildren = nodeTree.ChildrenCount;
            }

            // if we are a reference, and 'scalar' (i.e. $foo )
            // then get the de-dollared ref so we can
            // hit our context directly, avoiding the AST
            if (type == ParserTreeConstants.REFERENCE)
            {
                if (numTreeChildren == 0)
                {
                    // do this properly and use the Reference node
                    singleLevelRef = ((ASTReference)nodeTree).RootString;
                }
            }
        }
Exemplo n.º 9
0
 public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
 {
     base.Init(rs, context, node);
     this.counterName         = this.rsvc.GetString("directive.foreach.counter.name");
     this.counterInitialValue = this.rsvc.GetInt("directive.foreach.counter.initial.value");
     this.elementKey          = node.GetChild(0).FirstToken.Image.Substring(1);
 }
Exemplo n.º 10
0
        public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
        {
            base.Init(rs, context, node);
            int childrenCount = node.ChildrenCount;

            if (this.NumArgs != childrenCount)
            {
                this.rsvc.Error(string.Concat(new object[]
                {
                    "VM #",
                    this.macroName,
                    ": error : too ",
                    (this.NumArgs > childrenCount) ? "few" : "many",
                    " arguments to macro. Wanted ",
                    this.NumArgs,
                    " got ",
                    childrenCount
                }));
            }
            else
            {
                this.callingArgs = this.getArgArray(node);
                this.setupMacro(this.callingArgs, this.callingArgTypes);
            }
        }
Exemplo n.º 11
0
        /// <summary>  simple Init - Get the key</summary>
        public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
        {
            base.Init(rs, context, node);

            log = rs.Log;

            /*
             * default max depth of two is used because intentional recursion is
             * unlikely and discouraged, so make unintentional ones end fast
             */
            maxDepth = rs.GetInt(NVelocity.Runtime.RuntimeConstants.DEFINE_DIRECTIVE_MAXDEPTH, 2);

            /*
             * first token is the name of the block. We don't even check the format,
             * just assume it looks like this: $block_name. Should we check if it has
             * a '$' or not?
             */
            key = node.GetChild(0).FirstToken.Image.Substring(1);

            /**
             * No checking is done. We just grab the second child node and assume
             * that it's the block!
             */
            block = node.GetChild(1);

            /**
             * keep tabs on the template this came from
             */
            definingTemplate = context.CurrentTemplateName;
        }
Exemplo n.º 12
0
        /// <summary> Initialize and check arguments.</summary>
        /// <param name="rs">
        /// </param>
        /// <param name="context">
        /// </param>
        /// <param name="node">
        /// </param>
        /// <throws>  TemplateInitException </throws>
        public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
        {
            base.Init(rs, context, node);

            /**
             * Check that there is exactly one argument and it is a string or reference.
             */

            int argCount = node.GetNumChildren();

            if (argCount == 0)
            {
                throw new TemplateInitException("#" + Name + "() requires exactly one argument", context.CurrentTemplateName, node.Column, node.Line);
            }
            if (argCount > 1)
            {
                /*
                 * use line/col of second argument
                 */

                throw new TemplateInitException("#" + Name + "() requires exactly one argument", context.CurrentTemplateName, node.GetChild(1).Column, node.GetChild(1).Line);
            }

            INode childNode = node.GetChild(0);

            if (childNode.Type != NVelocity.Runtime.Parser.ParserTreeConstants.JJTSTRINGLITERAL && childNode.Type != NVelocity.Runtime.Parser.ParserTreeConstants.JJTREFERENCE)
            {
                throw new TemplateInitException("#" + Name + "()  argument must be a string literal or reference", context.CurrentTemplateName, childNode.Column, childNode.Line);
            }
        }
Exemplo n.º 13
0
 public VMContext(IInternalContextAdapter inner, IRuntimeServices rsvc)
 {
     this.InitBlock();
     this.localcontextscope = rsvc.GetBoolean("velocimacro.context.localscope", false);
     this.wrappedContext    = inner;
     this.innerContext      = inner.BaseContext;
 }
Exemplo n.º 14
0
 public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
 {
     base.Init(rs, context, node);
     this.outputMsgStart  = this.rsvc.GetString("directive.include.output.errormsg.start");
     this.outputMsgStart += " ";
     this.outputMsgEnd    = this.rsvc.GetString("directive.include.output.errormsg.end");
     this.outputMsgEnd    = " " + this.outputMsgEnd;
 }
        /// <summary>
        /// How this directive is to be initialized.
        /// </summary>
        public virtual void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
        {
            runtimeServices = rs;

            //			int i, k = node.jjtGetNumChildren();
            //			for (i = 0; i < k; i++)
            //				node.jjtGetChild(i).init(context, rs);
        }
        /// <summary>  CTOR, wraps an ICA
        /// </summary>
        public VMContext(IInternalContextAdapter inner, IRuntimeServices runtimeServices)
        {
            InitBlock();
            localContextScope = runtimeServices.GetBoolean(RuntimeConstants.VM_CONTEXT_LOCALSCOPE, false);

            wrappedContext = inner;
            innerContext   = inner.BaseContext;
        }
Exemplo n.º 17
0
		/// <summary>
		/// How this directive is to be initialized.
		/// </summary>
		public virtual void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
		{
			runtimeServices = rs;

//			int i, k = node.jjtGetNumChildren();
//			for (i = 0; i < k; i++)
//				node.jjtGetChild(i).init(context, rs);
		}
Exemplo n.º 18
0
        override public object Execute(Reasoner ts, Unifier un, ITerm[] args)
        {
            CheckArguments(args);

            IRuntimeServices rs = ts.GetUserAgArch().GetRuntimeServices();

            rs.StopMAS();
            return(true);
        }
Exemplo n.º 19
0
        public override object Execute(Reasoner ts, Unifier un, ITerm[] args)
        {
            string           agName   = ((IStringTerm)args[0]).GetString();
            IRuntimeServices services = ts.GetUserAgArch().GetRuntimeServices();

            services.Clone(ts.GetAgent(), ts.GetUserAgArch().GetAgArchClassesChain(), agName);

            return(true);
        }
Exemplo n.º 20
0
 public ScriptServicesBuilder(IConsole console, ILog logger, IRuntimeServices runtimeServices = null, ITypeResolver typeResolver = null, IInitializationServices initializationServices = null)
 {
     InitializationServices = initializationServices ?? new InitializationServices(logger);
     _runtimeServices       = runtimeServices;
     _typeResolver          = typeResolver;
     _typeResolver          = typeResolver ?? new TypeResolver();
     ConsoleInstance        = console;
     _logger = logger;
 }
Exemplo n.º 21
0
        /// <summary> Initialize the handlers.  For global handlers this is called when Velocity
        /// is initialized. For local handlers this is called when the first handler
        /// is executed.  Handlers will not be initialized more than once.
        ///
        /// </summary>
        /// <param name="rs">
        /// </param>
        /// <throws>  Exception </throws>
        /// <since> 1.5
        /// </since>
        public virtual void Initialize(IRuntimeServices rs)
        {
            for (System.Collections.IEnumerator i = referenceHandlers.GetEnumerator(); i.MoveNext();)
            {
                IEventHandler eh = (IEventHandler)i.Current;
                if ((eh is IRuntimeServicesAware) && !initializedHandlers.Contains(eh))
                {
                    ((IRuntimeServicesAware)eh).SetRuntimeServices(rs);
                    initializedHandlers.Add(eh);
                }
            }


            for (System.Collections.IEnumerator i = nullSetHandlers.GetEnumerator(); i.MoveNext();)
            {
                IEventHandler eh = (IEventHandler)i.Current;
                if ((eh is IRuntimeServicesAware) && !initializedHandlers.Contains(eh))
                {
                    ((IRuntimeServicesAware)eh).SetRuntimeServices(rs);
                    initializedHandlers.Add(eh);
                }
            }


            for (System.Collections.IEnumerator i = methodExceptionHandlers.GetEnumerator(); i.MoveNext();)
            {
                IEventHandler eh = (IEventHandler)i.Current;
                if ((eh is IRuntimeServicesAware) && !initializedHandlers.Contains(eh))
                {
                    ((IRuntimeServicesAware)eh).SetRuntimeServices(rs);
                    initializedHandlers.Add(eh);
                }
            }


            for (System.Collections.IEnumerator i = includeHandlers.GetEnumerator(); i.MoveNext();)
            {
                IEventHandler eh = (IEventHandler)i.Current;
                if ((eh is IRuntimeServicesAware) && !initializedHandlers.Contains(eh))
                {
                    ((IRuntimeServicesAware)eh).SetRuntimeServices(rs);
                    initializedHandlers.Add(eh);
                }
            }


            for (System.Collections.IEnumerator i = invalidReferenceHandlers.GetEnumerator(); i.MoveNext();)
            {
                IEventHandler eh = (IEventHandler)i.Current;
                if ((eh is IRuntimeServicesAware) && !initializedHandlers.Contains(eh))
                {
                    ((IRuntimeServicesAware)eh).SetRuntimeServices(rs);
                    initializedHandlers.Add(eh);
                }
            }
        }
Exemplo n.º 22
0
        /// <seealso cref="org.apache.velocity.runtime.directive.Directive.Init(org.apache.velocity.runtime.RuntimeServices, org.apache.velocity.context.InternalContextAdapter, NVelocity.Runtime.Paser.Node.Node)">
        /// </seealso>
        public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
        {
            base.Init(rs, context, node);

            /*
             * again, don't do squat.  We want the AST of the macro
             * block to hang off of this but we don't want to
             * Init it... it's useless...
             */
        }
Exemplo n.º 23
0
 public PvcScriptServicesBuilder(IConsole console, ILog logger, IRuntimeServices runtimeServices = null, ITypeResolver typeResolver = null, IInitializationServices initializationServices = null)
     : base(console: console,
         logger: logger,
         runtimeServices: runtimeServices,
         typeResolver: typeResolver,
         initializationServices: initializationServices ?? BuildInitializationServices(logger))
 {
     this.FileSystem<PvcFileSystem>()
         .PackageContainer<PvcPackageContainer>();
 }
        /// <summary> Adds the global namespace to the hash.</summary>
        internal VelocimacroManager(IRuntimeServices rsvc)
        {
            InitBlock();

            /*
             *  Add the global namespace to the namespace hash. We always have that.
             */

            globalNamespace = AddNamespace(GLOBAL_NAMESPACE);
        }
Exemplo n.º 25
0
        /// <summary> Called before a reference is inserted. All event handlers are called in
        /// sequence. The default implementation inserts the reference as is.
        ///
        /// This is a major hotspot method called by ASTReference render.
        ///
        /// </summary>
        /// <param name="reference">reference from template about to be inserted
        /// </param>
        /// <param name="value">value about to be inserted (after toString() )
        /// </param>
        /// <param name="rsvc">current instance of RuntimeServices
        /// </param>
        /// <param name="context">The internal context adapter.
        /// </param>
        /// <returns> Object on which toString() should be called for output.
        /// </returns>
        public static object ReferenceInsert(IRuntimeServices rsvc, IInternalContextAdapter context, string reference, object value)
        {
            // app level cartridges have already been initialized

            /*
             * Performance modification: EventCartridge.getReferenceInsertionEventHandlers
             * now returns a null if there are no handlers. Thus we can avoid creating the
             * Iterator object.
             */
            EventCartridge ev1 = rsvc.ApplicationEventCartridge;

            System.Collections.IEnumerator applicationEventHandlerIterator = (ev1 == null) ? null : ev1.ReferenceInsertionEventHandlers;

            EventCartridge ev2 = context.EventCartridge;

            InitializeEventCartridge(rsvc, ev2);
            System.Collections.IEnumerator contextEventHandlerIterator = (ev2 == null) ? null : ev2.ReferenceInsertionEventHandlers;

            try
            {
                /*
                 * Performance modification: methodExecutor is created only if one of the
                 * iterators is not null.
                 */

                IEventHandlerMethodExecutor methodExecutor = null;

                if (applicationEventHandlerIterator != null)
                {
                    methodExecutor = new ReferenceInsertExecutor(context, reference, value);
                    LterateOverEventHandlers(applicationEventHandlerIterator, methodExecutor);
                }

                if (contextEventHandlerIterator != null)
                {
                    if (methodExecutor == null)
                    {
                        methodExecutor = new ReferenceInsertExecutor(context, reference, value);
                    }

                    LterateOverEventHandlers(contextEventHandlerIterator, methodExecutor);
                }


                return(methodExecutor != null ? methodExecutor.ReturnValue : value);
            }
            catch (System.SystemException e)
            {
                throw e;
            }
            catch (System.Exception e)
            {
                throw new RuntimeException("Exception in event handler.", e);
            }
        }
        /// <summary>  CTOR : requires a runtime services from now
        /// on
        /// </summary>
        public VelocimacroFactory(IRuntimeServices rs)
        {
            runtimeServices = rs;

            /*
            *  we always access in a synchronized(), so we
            *  can use an unsynchronized hashmap
            */
            libModMap = new Hashtable();
            velocimacroManager = new VelocimacroManager(runtimeServices);
        }
Exemplo n.º 27
0
 public ScriptServicesBuilder(
     IConsole console,
     ILogProvider logProvider,
     IRuntimeServices runtimeServices = null,
     IInitializationServices initializationServices = null)
 {
     InitializationServices = initializationServices ?? new InitializationServices(logProvider);
     _runtimeServices       = runtimeServices;
     ConsoleInstance        = console;
     _logProvider           = logProvider;
 }
		/// <summary> Adds the global namespace to the hash.</summary>
		internal VelocimacroManager(IRuntimeServices rs)
		{
			InitBlock();
			runtimeServices = rs;

			/*
		*  add the global namespace to the namespace hash. We always have that.
		*/

			AddNamespace(GLOBAL_NAMESPACE);
		}
Exemplo n.º 29
0
        /// <summary>  CTOR : requires a runtime services from now
        /// on
        /// </summary>
        public VelocimacroFactory(IRuntimeServices rs)
        {
            runtimeServices = rs;

            /*
             *  we always access in a synchronized(), so we
             *  can use an unsynchronized hashmap
             */
            libModMap          = new Hashtable();
            velocimacroManager = new VelocimacroManager(runtimeServices);
        }
Exemplo n.º 30
0
        /// <summary>
        /// simple init - init the tree and get the elementKey from
        /// the AST
        /// </summary>
        public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
        {
            base.Init(rs, context, node);

            counterName         = runtimeServices.GetString(RuntimeConstants.COUNTER_NAME);
            counterInitialValue = runtimeServices.GetInt(RuntimeConstants.COUNTER_INITIAL_VALUE);

            // this is really the only thing we can do here as everything
            // else is context sensitive
            elementKey = node.GetChild(0).FirstToken.Image.Substring(1);
        }
Exemplo n.º 31
0
 public PvcScriptServicesBuilder(IConsole console, ILog logger, IRuntimeServices runtimeServices = null, ITypeResolver typeResolver = null, IInitializationServices initializationServices = null)
     : base(
         console: console,
         logger: logger,
         runtimeServices: runtimeServices,
         typeResolver: typeResolver,
         initializationServices: initializationServices ?? BuildInitializationServices(logger)
         )
 {
     this.FileSystem <PvcFileSystem>()
     .PackageContainer <PvcPackageContainer>();
 }
Exemplo n.º 32
0
		/// <summary>
		/// simple init - init the tree and get the elementKey from
		/// the AST
		/// </summary>
		public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
		{
			base.Init(rs, context, node);

			// get the msg, and add the space so we don't have to
			// do it each time
			outputMsgStart = rsvc.GetString(RuntimeConstants.ERRORMSG_START);
			outputMsgStart = outputMsgStart + " ";

			outputMsgEnd = rsvc.GetString(RuntimeConstants.ERRORMSG_END);
			outputMsgEnd = " " + outputMsgEnd;
		}
		public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
		{
			base.Init(rs, context, node);

			compNameNode = node.GetChild(0);

			if (compNameNode == null)
			{
				String message = String.Format("You must specify the component name on the #{0} directive", Name);
				throw new ViewComponentException(message);
			}
		}
Exemplo n.º 34
0
        /// <summary>
        /// simple init - init the tree and get the elementKey from
        /// the AST
        /// </summary>
        public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
        {
            base.Init(rs, context, node);

            // get the msg, and add the space so we don't have to
            // do it each time
            outputMsgStart = runtimeServices.GetString(RuntimeConstants.ERRORMSG_START);
            outputMsgStart = string.Format("{0} ", outputMsgStart);

            outputMsgEnd = runtimeServices.GetString(RuntimeConstants.ERRORMSG_END);
            outputMsgEnd = string.Format(" {0}", outputMsgEnd);
        }
        /// <summary>  C'tor for the VelociMacro factory.
        ///
        /// </summary>
        /// <param name="rsvc">Reference to a runtime services object.
        /// </param>
        public VelocimacroFactory(IRuntimeServices rsvc)
        {
            this.rsvc = rsvc;
            this.log  = new LogDisplayWrapper(rsvc.Log, "Velocimacro : ", rsvc.GetBoolean(RuntimeConstants.VM_MESSAGES_ON, true));

            /*
             *  we always access in a synchronized(), so we
             *  can use an unsynchronized hashmap
             */
            libModMap = new Dictionary <string, Twonk>();
            vmManager = new VelocimacroManager(rsvc);
        }
Exemplo n.º 36
0
        /// <summary>  Used by Parser.java to process VMs during the parsing process.
        ///
        /// This method does not render the macro to the output stream,
        /// but rather <i>processes the macro body</i> into the internal
        /// representation used by {#link
        /// org.apache.velocity.runtime.directive.VelocimacroProxy}
        /// objects, and if not currently used, adds it to the macro
        /// Factory.
        /// </summary>
        /// <param name="rs">
        /// </param>
        /// <param name="t">
        /// </param>
        /// <param name="node">
        /// </param>
        /// <param name="sourceTemplate">
        /// </param>
        /// <throws>  IOException </throws>
        /// <throws>  ParseException </throws>
        public static void ProcessAndRegister(IRuntimeServices rs, Token t, INode node, string sourceTemplate)
        {
            /*
             *  There must be at least one arg to  #macro,
             *  the name of the VM.  Note that 0 following
             *  args is ok for naming blocks of HTML
             */

            int numArgs = node.GetNumChildren();

            /*
             *  this number is the # of args + 1.  The + 1
             *  is for the block tree
             */

            if (numArgs < 2)
            {
                /*
                 *  Error - they didn't name the macro or
                 *  define a block
                 */

                rs.Log.Error("#macro error : Velocimacro must have name as 1st " + "argument to #macro(). #args = " + numArgs);

                throw new MacroParseException("First argument to #macro() must be " + " macro name.", sourceTemplate, t);
            }

            /*
             *  lets make sure that the first arg is an ASTWord
             */

            int firstType = node.GetChild(0).Type;

            if (firstType != NVelocity.Runtime.Parser.ParserTreeConstants.JJTWORD)
            {
                throw new MacroParseException("First argument to #macro() must be a" + " token without surrounding \' or \", which specifies" + " the macro name.  Currently it is a " + NVelocity.Runtime.Parser.ParserTreeConstants.jjtNodeName[firstType], sourceTemplate, t);
            }

            // Get the arguments to the use of the VM - element 0 contains the macro name
            string[] argArray = GetArgArray(node, rs);

            /*
             * we already have the macro parsed as AST so there is no point to
             * transform it into a String again
             */
            rs.AddVelocimacro(argArray[0], node.GetChild(numArgs - 1), argArray, sourceTemplate);

            /*
             * Even if the Add attempt failed, we don't Log anything here.
             * Logging must be done at VelocimacroFactory or VelocimacroManager because
             * those classes know the real reason.
             */
        }
Exemplo n.º 37
0
		/// <summary> 
		/// This constructor was added to allow the re-use of parsers.
		/// The normal constructor takes a single argument which
		/// an InputStream. This simply creates a re-usable parser
		/// object, we satisfy the requirement of an InputStream
		/// by using a newline character as an input stream.
		/// </summary>
		public Parser(IRuntimeServices rs) : this(new VelocityCharStream(new StringReader("\n"), 1, 1))
		{
			InitBlock();

			/*
			* now setup a VCS for later use
			*/
			velcharstream = new VelocityCharStream(new StringReader("\n"), 1, 1);

			/*
			*  and save the RuntimeServices
			*/
			rsvc = rs;
		}
Exemplo n.º 38
0
		/// <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)
		{
			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 = configuration.GetBoolean("cache", false);
			modificationCheckInterval = configuration.GetLong("modificationCheckInterval", 0);

			// this is a must!
			className = configuration.GetString("class");
		}
        public void initialize(IRuntimeServices rs)
        {
            runtimeServices = rs;

            int maxSize = runtimeServices.GetInt(RuntimeConstants.RESOURCE_MANAGER_DEFAULTCACHE_SIZE, 89);
            if (maxSize > 0)
            {
                // Create a whole new Map here to avoid hanging on to a
                // handle to the unsynch'd LRUMap for our lifetime.
                LRUMap lruCache = LRUMap.Synchronized(new LRUMap(maxSize));
                lruCache.AddAll(cache);
                cache = lruCache;
            }

            runtimeServices.Info(string.Format("ResourceCache : initialized. ({0})", GetType()));
        }
Exemplo n.º 40
0
		/// <summary>
		/// Used by Parser.java to process VMs within the parsing process
		///
		/// processAndRegister() doesn't actually render the macro to the output
		/// Processes the macro body into the internal representation used by the
		/// VelocimacroProxy objects, and if not currently used, adds it
		/// to the macro Factory
		/// </summary>
		public static void processAndRegister(IRuntimeServices rs, INode node, String sourceTemplate)
		{
			// There must be at least one arg to  #macro,
			// the name of the VM.  Note that 0 following 
			// args is ok for naming blocks of HTML
			int numArgs = node.ChildrenCount;

			// this number is the # of args + 1.  The + 1
			// is for the block tree
			if (numArgs < 2)
			{
				// error - they didn't name the macro or
				// define a block
				rs.Error("#macro error : Velocimacro must have name as 1st argument to #macro()");

				return;
			}

			// get the arguments to the use of the VM
			String[] argArray = getArgArray(node);

			// now, try and eat the code block. Pass the root.
			IList macroArray = getASTAsStringArray(node.GetChild(numArgs - 1));

			// make a big string out of our macro
			StringBuilder temp = new StringBuilder();

			for(int i = 0; i < macroArray.Count; i++)
			{
				temp.Append(macroArray[i]);
			}

			String macroBody = temp.ToString();

			// now, try to add it.  The Factory controls permissions, 
			// so just give it a whack...
			rs.AddVelocimacro(argArray[0], macroBody, argArray, sourceTemplate);

			return;
		}
Exemplo n.º 41
0
		/// <summary>
		/// The major meat of VelocimacroProxy, init() checks the # of arguments, 
		/// patches the macro body, renders the macro into an AST, and then inits 
		/// the AST, so it is ready for quick rendering.  Note that this is only 
		/// AST dependant stuff. Not context.
		/// </summary>
		public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
		{
			base.Init(rs, context, node);

			// how many args did we get?
			int i = node.ChildrenCount;

			// right number of args?
			if (NumArgs != i)
			{
				rsvc.Error("VM #" + macroName + ": error : too " + ((NumArgs > i) ? "few" : "many") + " arguments to macro. Wanted " +
				           NumArgs + " got " + i);

				return;
			}

			// get the argument list to the instance use of the VM
			callingArgs = getArgArray(node);

			// now proxy each arg in the context
			setupMacro(callingArgs, callingArgTypes);
			return;
		}
Exemplo n.º 42
0
		/// <summary>
		/// The major meat of VelocimacroProxy, init() checks the # of arguments, 
		/// patches the macro body, renders the macro into an AST, and then initiates 
		/// the AST, so it is ready for quick rendering.  Note that this is only 
		/// AST dependant stuff. Not context.
		/// </summary>
		public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
		{
			base.Init(rs, context, node);

			// how many args did we get?
			int i = node.ChildrenCount;

			// right number of args?
			if (NumArgs != i)
			{
				runtimeServices.Error(
					string.Format("VM #{0}: error : too {1} arguments to macro. Wanted {2} got {3}", macroName,
					              ((NumArgs > i) ? "few" : "many"), NumArgs, i));

				return;
			}

			// get the argument list to the instance use of the VM
			callingArgs = getArgArray(node);

			// now proxy each arg in the context
			setupMacro(callingArgs, callingArgTypes);
			return;
		}
		/// <summary>
		/// Gets the loader specified in the configuration file.
		/// </summary>
		/// <returns>TemplateLoader</returns>
		public static ResourceLoader getLoader(IRuntimeServices rs, String loaderClassName)
		{
			try
			{
				// since properties are parsed into arrays with commas, 
				// something else needed to be used
				loaderClassName = loaderClassName.Replace(';', ',');
				Type loaderType = Type.GetType(loaderClassName);
				Object o = Activator.CreateInstance(loaderType);
				ResourceLoader loader = (ResourceLoader) o;

				rs.Info(string.Format("Resource Loader Instantiated: {0}", loader.GetType().FullName));

				return loader;
			}
			catch(System.Exception e)
			{
				rs.Error(
					string.Format(
						"Problem instantiating the template loader.\nLook at your properties file and make sure the\nname of the template loader is correct. Here is the\nerror: {0}",
						e));
				throw new System.Exception(string.Format("Problem initializing template loader: {0}\nError is: {1}", loaderClassName, e));
			}
		}
Exemplo n.º 44
0
		/// <summary>  ctor for current impl
		/// *
		/// takes the reference literal we are proxying for, the literal
		/// the VM we are for is called with...
		/// *
		/// </summary>
		/// <param name="rs">
		/// </param>
		/// <param name="contextRef">reference arg in the definition of the VM, used in the VM
		/// </param>
		/// <param name="callerRef"> reference used by the caller as an arg to the VM
		/// </param>
		/// <param name="t"> type of arg : JJTREFERENCE, JJTTRUE, etc
		///
		/// </param>
		public VMProxyArg(IRuntimeServices rs, String contextRef, String callerRef, int t)
		{
			runtimeServices = rs;

			contextReference = contextRef;
			callerReference = callerRef;
			type = t;

			// make our AST if necessary
			setup();

			// if we are multi-node tree, then save the size to 
			// avoid fn call overhead 
			if (nodeTree != null)
			{
				numTreeChildren = nodeTree.ChildrenCount;
			}

			// if we are a reference, and 'scalar' (i.e. $foo )
			// then get the de-dollared ref so we can
			// hit our context directly, avoiding the AST
			if (type == ParserTreeConstants.REFERENCE)
			{
				if (numTreeChildren == 0)
				{
					// do this properly and use the Reference node
					singleLevelRef = ((ASTReference) nodeTree).RootString;
				}
			}
		}
Exemplo n.º 45
0
		/// <summary>  Creates a new logging system or returns an existing one
		/// specified by the application.
		/// </summary>
		public static ILogSystem CreateLogSystem(IRuntimeServices runtimeServices)
		{
			ILogSystem logSystem;
			// if a logSystem was set as a configuration value, use that.
			// This is any class the user specifies.
			Object o = runtimeServices.GetProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM);
			logSystem = o as ILogSystem;
			if (logSystem != null)
			{
				logSystem.Init(runtimeServices);

				return logSystem;
			}

			// otherwise, see if a class was specified.  You
			// can put multiple classes, and we use the first one we find.
			//
			// Note that the default value of this property contains both the
			// AvalonLogSystem and the SimpleLog4JLogSystem for convenience -
			// so we use whichever we find.
			IList classes = new ArrayList();
			Object obj = runtimeServices.GetProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS);

			// we might have a list, or not - so check
			if (obj is IList)
			{
				classes = (IList) obj;
			}
			else if (obj is String)
			{
				classes.Add(obj);
			}

			// now run through the list, trying each.  It's ok to
			// fail with a class not found, as we do this to also
			// search out a default simple file logger
			foreach(String className in classes)
			{
				if (className != null && className.Length > 0)
				{
					runtimeServices.Info(string.Format("Trying to use logger class {0}", className));

					try
					{
						Type type = Type.GetType(className);
						o = Activator.CreateInstance(type);
						logSystem = o as ILogSystem;
						if (logSystem == null)
						{
							runtimeServices.Error(string.Format("The specified logger class {0} isn't a valid LogSystem", className));
						}
						else
						{
							logSystem.Init(runtimeServices);

							runtimeServices.Info(string.Format("Using logger class {0}", className));

							return logSystem;
						}
					}
					catch(ApplicationException applicationException)
					{
						runtimeServices.Debug(
							string.Format("Couldn't find class {0} or necessary supporting classes in classpath. Exception : {1}", className,
							              applicationException));
					}
				}
			}

			// if the above failed, then we are in deep doo-doo, as the
			// above means that either the user specified a logging class
			// that we can't find, there weren't the necessary
			// dependencies in the classpath for it, or there were no
			// dependencies for the default logger.
			// Since we really don't know,
			// then take a wack at the log4net as a last resort.
			try
			{
				logSystem = new NullLogSystem();
				logSystem.Init(runtimeServices);
			}
			catch(ApplicationException applicationException)
			{
				String error =
					string.Format(
						"PANIC : NVelocity cannot find any of the specified or default logging systems in the classpath, or the classpath doesn't contain the necessary classes to support them. Please consult the documentation regarding logging. Exception : {0}",
						applicationException);

				Console.Out.WriteLine(error);
				Console.Error.WriteLine(error);

				throw;
			}

			runtimeServices.Info("Using log4net as logger of final resort.");

			return logSystem;
		}
 public ReplScriptServicesBuilder(ScriptConsole console, Common.Logging.ILog logger, IRuntimeServices runtimeServices = null)
     : base(console, logger, runtimeServices)
 {
     this.Overrides.Add(typeof(IScriptExecutor), typeof(Repl));
 }
		/// <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(System.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.");
		}
Exemplo n.º 48
0
		public void Init(IRuntimeServices rs)
		{
		}
Exemplo n.º 49
0
		/// <summary>
		/// Store the literal rendition of a node using
		/// the Node.literal().
		/// </summary>
		public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
		{
			base.Init(rs, context, node);

			literalText = node.GetChild(0).Literal;
		}
Exemplo n.º 50
0
		public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
		{
			base.Init(rs, context, node);
		}
Exemplo n.º 51
0
		/// <summary>  CTOR, wraps an ICA
		/// </summary>
		public VMContext(IInternalContextAdapter inner, IRuntimeServices runtimeServices)
		{
			InitBlock();
			localContextScope = runtimeServices.GetBoolean(RuntimeConstants.VM_CONTEXT_LOCALSCOPE, false);

			wrappedContext = inner;
			innerContext = inner.BaseContext;
		}
Exemplo n.º 52
0
		public virtual Object Init(IInternalContextAdapter context, Object data)
		{
			/*
	    * hold onto the RuntimeServices
	    */

			runtimeServices = (IRuntimeServices) data;

			int i, k = ChildrenCount;

			for(i = 0; i < k; i++)
			{
				try
				{
					GetChild(i).Init(context, data);
				}
				catch(ReferenceException re)
				{
					runtimeServices.Error(re);
				}
			}

			return data;
		}
Exemplo n.º 53
0
        /// <summary>  
        /// simple init - init the tree and get the elementKey from
        /// the AST
        /// </summary>
        public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node)
        {
            base.Init(rs, context, node);

            counterName = runtimeServices.GetString(RuntimeConstants.COUNTER_NAME);
            counterInitialValue = runtimeServices.GetInt(RuntimeConstants.COUNTER_INITIAL_VALUE);

            // this is really the only thing we can do here as everything
            // else is context sensitive
            elementKey = node.GetChild(0).FirstToken.Image.Substring(1);
        }