コード例 #1
0
 object IInternalContextAdapter.Remove(object key)
 {
     if (bag.ContextEntries.ContainsKey(key.ToString()))
     {
         bag.ContextEntries.Remove(key.ToString());
     }
     return(context.Remove(key));
 }
コード例 #2
0
ファイル: Foreach.cs プロジェクト: hatjhie/NVelocity
        /// <summary>
        /// renders the #foreach() block
        /// </summary>
        public override bool Render(IInternalContextAdapter context, TextWriter writer, INode node)
        {
            // do our introspection to see what our collection is
            IEnumerator enumerator = GetIterator(context, node);
            INode       bodyNode   = node.GetChild(3);

            INode[][] sections    = PrepareSections(bodyNode);
            bool      isFancyLoop = (sections != null);

            if (enumerator == null && !isFancyLoop)
            {
                return(true);
            }

            int counter = counterInitialValue;

            // save the element key if there is one,
            // and the loop counter
            Object o   = context.Get(elementKey);
            Object ctr = context.Get(counterName);

            if (enumerator != null && enumerator.MoveNext())
            {
                do
                {
                    object current = enumerator.Current;

                    context.Put(counterName, counter);
                    //context.Put(hasNextName, enumerator.MoveNext() ? Boolean.TrueString : Boolean.FalseString);
                    context.Put(elementKey, current);

                    try
                    {
                        if (isFancyLoop)
                        {
                            if (counter == counterInitialValue)
                            {
                                ProcessSection(ForeachSectionEnum.BeforeAll, sections, context, writer);
                            }
                            else
                            {
                                ProcessSection(ForeachSectionEnum.Between, sections, context, writer);
                            }

                            ProcessSection(ForeachSectionEnum.Before, sections, context, writer);

                            // since 1st item is zero we invert odd/even
                            if ((counter - counterInitialValue) % 2 == 0)
                            {
                                ProcessSection(ForeachSectionEnum.Odd, sections, context, writer);
                            }
                            else
                            {
                                ProcessSection(ForeachSectionEnum.Even, sections, context, writer);
                            }

                            ProcessSection(ForeachSectionEnum.Each, sections, context, writer);

                            ProcessSection(ForeachSectionEnum.After, sections, context, writer);
                        }
                        else
                        {
                            bodyNode.Render(context, writer);
                        }
                    }
                    catch (BreakException ex)
                    {
                        Console.WriteLine(ex.Message);
                        bodyNode.Render(context, writer);
                        break;
                    }
                    counter++;
                } while (enumerator.MoveNext());
            }

            if (isFancyLoop)
            {
                if (counter > counterInitialValue)
                {
                    ProcessSection(ForeachSectionEnum.AfterAll, sections, context, writer);
                }
                else
                {
                    ProcessSection(ForeachSectionEnum.NoData, sections, context, writer);
                }
            }

            // restores the loop counter (if we were nested)
            // if we have one, else just removes
            if (ctr == null)
            {
                context.Remove(counterName);
            }
            else
            {
                context.Put(counterName, ctr);
            }

            // restores element key if exists
            // otherwise just removes
            if (o == null)
            {
                context.Remove(elementKey);
            }
            else
            {
                context.Put(elementKey, o);
            }

            return(true);
        }
コード例 #3
0
ファイル: Foreach.cs プロジェクト: modulexcite/Transformalize
        /// <summary>
        /// renders the #foreach() block
        /// </summary>
        public override bool Render(IInternalContextAdapter context, TextWriter writer, INode node)
        {
            // do our introspection to see what our collection is
            IEnumerator enumerator = GetIterator(context, node);
            INode bodyNode = node.GetChild(3);

            INode[][] sections = PrepareSections(bodyNode);
            bool isFancyLoop = (sections != null);

            if (enumerator == null && !isFancyLoop)
            {
                return true;
            }

            int counter = counterInitialValue;

            // save the element key if there is one,
            // and the loop counter
            Object o = context.Get(elementKey);
            Object ctr = context.Get(counterName);

            if (enumerator != null && enumerator.MoveNext())
            {
                do
                {
                    object current = enumerator.Current;

                    context.Put(counterName, counter);
                    //context.Put(hasNextName, enumerator.MoveNext() ? Boolean.TrueString : Boolean.FalseString);
                    context.Put(elementKey, current);

                    try
                    {
                        if (isFancyLoop)
                        {
                            if (counter == counterInitialValue)
                            {
                                ProcessSection(ForeachSectionEnum.BeforeAll, sections, context, writer);
                            }
                            else
                            {
                                ProcessSection(ForeachSectionEnum.Between, sections, context, writer);
                            }

                            ProcessSection(ForeachSectionEnum.Before, sections, context, writer);

                            // since 1st item is zero we invert odd/even
                            if ((counter - counterInitialValue) % 2 == 0)
                            {
                                ProcessSection(ForeachSectionEnum.Odd, sections, context, writer);
                            }
                            else
                            {
                                ProcessSection(ForeachSectionEnum.Even, sections, context, writer);
                            }

                            ProcessSection(ForeachSectionEnum.Each, sections, context, writer);

                            ProcessSection(ForeachSectionEnum.After, sections, context, writer);
                        }
                        else
                        {
                            bodyNode.Render(context, writer);
                        }
                    }
                    catch (BreakException)
                    {
                        break;
                    }
                    counter++;
                } while (enumerator.MoveNext());
            }

            if (isFancyLoop)
            {
                if (counter > counterInitialValue)
                {
                    ProcessSection(ForeachSectionEnum.AfterAll, sections, context, writer);
                }
                else
                {
                    ProcessSection(ForeachSectionEnum.NoData, sections, context, writer);
                }
            }

            // restores the loop counter (if we were nested)
            // if we have one, else just removes
            if (ctr == null)
            {
                context.Remove(counterName);
            }
            else
            {
                context.Put(counterName, ctr);
            }

            // restores element key if exists
            // otherwise just removes
            if (o == null)
            {
                context.Remove(elementKey);
            }
            else
            {
                context.Put(elementKey, o);
            }

            return true;
        }
コード例 #4
0
		public override bool Render(IInternalContextAdapter context, TextWriter writer, INode node)
		{
			IEngineContext railsContext = EngineContextLocator.Instance.LocateCurrentContext();
			IViewComponentRegistry registry = railsContext.Services.GetService<IViewComponentFactory>().Registry;
			IViewComponentDescriptorProvider viewDescProvider =
				railsContext.Services.GetService<IViewComponentDescriptorProvider>();
			ICacheProvider cacheProvider = railsContext.Services.CacheProvider;

			INode 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);
			}

			string componentName = compNameNode.FirstToken.Image;

			if (componentName == null)
			{
				String message = String.Format("Could not obtain component name from the #{0} directive", Name);
				throw new ViewComponentException(message);
			}

			if (componentName.StartsWith("$"))
			{
				String nodeContent = compNameNode.Literal.Trim('"', '\'');
				SimpleNode inlineNode = runtimeServices.Parse(new StringReader(nodeContent), context.CurrentTemplateName, false);

				inlineNode.Init(context, runtimeServices);
				componentName = (string) Evaluate(inlineNode, context);
			}

			IDictionary componentParams = CreateParameters(context, node);

			Type viewComptype = registry.GetViewComponent(componentName);

			ViewComponentDescriptor descriptor = null;
			CacheKey key = null;

			if (viewComptype != null)
			{
				descriptor = viewDescProvider.Collect(viewComptype);
			}

			bool isOutputtingToCache = false;
			ViewComponentCacheBag bag = null;

			if (descriptor != null && descriptor.IsCacheable)
			{
				key = descriptor.CacheKeyGenerator.Create(componentName, componentParams, railsContext);

				if (key != null)
				{
					ViewComponentCacheBag cachedContent = (ViewComponentCacheBag) cacheProvider.Get(key.ToString());

					if (cachedContent != null)
					{
						// Restore entries

						foreach(KeyValuePair<string, object> pair in cachedContent.ContextEntries)
						{
							context[pair.Key] = pair.Value;
						}

						// Render from cache

						writer.Write(cachedContent.Content);

						return true;
					}

					isOutputtingToCache = true;
					bag = new ViewComponentCacheBag();
				}
			}

			ViewComponent component = viewComponentFactory.Create(componentName);

			if (component == null)
			{
				throw new MonoRailException("ViewComponentFactory returned a null ViewComponent for " + componentName + ". " +
				                            "Please investigate the implementation: " + viewComponentFactory.GetType().FullName);
			}

			try
			{
				ASTDirective directiveNode = (ASTDirective) node;
				IViewRenderer renderer = (IViewRenderer) directiveNode.Directive;

				NVelocityViewContextAdapter contextAdapter = new NVelocityViewContextAdapter(componentName, node, viewEngine, renderer);
				contextAdapter.Context = isOutputtingToCache ? new CacheAwareContext(context, bag) : context;

				INode bodyNode = null;

				if (node.ChildrenCount > 0)
				{
					bodyNode = node.GetChild(node.ChildrenCount - 1);
				}

				TextWriter output = isOutputtingToCache ? bag.CacheWriter : writer;

				contextAdapter.BodyNode = bodyNode;
				contextAdapter.ComponentParams = componentParams;
				contextAdapter.TextWriter = output;

				component.Init(railsContext, contextAdapter);

				ProcessSubSections(component, contextAdapter);

				const string ViewComponentContextKey = "viewcomponent";
				object previousComp = context[ViewComponentContextKey];

				try
				{
					context[ViewComponentContextKey] = component;

					component.Render();

					if (contextAdapter.ViewToRender != null)
					{
						RenderComponentView(context, contextAdapter.ViewToRender, output, contextAdapter);
					}

					if (isOutputtingToCache)
					{
						// Save output

						cacheProvider.Store(key.ToString(), bag);

						// Output to correct writer

						writer.Write(bag.Content);
					}
				}
				finally
				{
					if (previousComp != null)
					{
						context[ViewComponentContextKey] = previousComp;
					}
					else
					{
						context.Remove(ViewComponentContextKey);
					}
				}
			}
			finally
			{
				viewComponentFactory.Release(component);
			}

			return true;
		}
コード例 #5
0
        /// <summary>  renders the #foreach() block</summary>
        /// <param name="context">
        /// </param>
        /// <param name="writer">
        /// </param>
        /// <param name="node">
        /// </param>
        /// <returns> True if the directive rendered successfully.
        /// </returns>
        /// <throws>  IOException </throws>
        /// <throws>  MethodInvocationException </throws>
        /// <throws>  ResourceNotFoundException </throws>
        /// <throws>  ParseErrorException </throws>
        public override bool Render(IInternalContextAdapter context, TextWriter writer, INode node)
        {
            /*
             *  do our introspection to see what our collection is
             */

            object listObject = node.GetChild(2).Value(context);

            if (listObject == null)
            {
                return(false);
            }

            IEnumerator i = null;

            try
            {
                i = rsvc.Uberspect.GetIterator(listObject, uberInfo);
            }

            /**
             * pass through application level runtime exceptions
             */
            catch (SystemException e)
            {
                throw e;
            }
            catch (Exception ee)
            {
                string msg = "Error getting iterator for #foreach at " + uberInfo;
                rsvc.Log.Error(msg, ee);
                throw new VelocityException(msg, ee);
            }

            if (i == null)
            {
                if (skipInvalidIterator)
                {
                    return(false);
                }
                else
                {
                    INode pnode = node.GetChild(2);

                    System.String msg = "#foreach parameter " + pnode.Literal + " at " + Log.FormatFileString(pnode) + " is of type " + listObject.GetType().FullName + " and is either of wrong type or cannot be iterated.";
                    rsvc.Log.Error(msg);
                    throw new VelocityException(msg);
                }
            }

            int  counter             = counterInitialValue;
            bool maxNbrLoopsExceeded = false;

            /*
             *  save the element key if there is one, and the loop counter
             */
            object o            = context.Get(elementKey);
            object savedCounter = context.Get(counterName);

            /*
             * Instantiate the null holder context if a null value
             * is returned by the foreach iterator.  Only one instance is
             * created - it's reused for every null value.
             */
            NullHolderContext nullHolderContext = null;


            while (!maxNbrLoopsExceeded && i.MoveNext())
            {
                // TODO: JDK 1.5+ -> Integer.valueOf()
                Put(context, counterName, (object)counter);

                object value = i.Current;

                Put(context, elementKey, value);

                try
                {
                    /*
                     * If the value is null, use the special null holder context
                     */
                    if (value == null)
                    {
                        if (nullHolderContext == null)
                        {
                            // lazy instantiation
                            nullHolderContext = new NullHolderContext(elementKey, context);
                        }
                        node.GetChild(3).Render(nullHolderContext, writer);
                    }
                    else
                    {
                        node.GetChild(3).Render(context, writer);
                    }
                }
                catch (Break.BreakException ex)
                {
                    // encountered #break directive inside #foreach loop
                    break;
                }

                counter++;

                // Determine whether we're allowed to continue looping.
                // ASSUMPTION: counterInitialValue is not negative!
                maxNbrLoopsExceeded = (counter - counterInitialValue) >= maxNbrLoops;
            }

            /*
             * restores the loop counter (if we were nested)
             * if we have one, else just removes
             */

            if (savedCounter != null)
            {
                context.Put(counterName, savedCounter);
            }
            else
            {
                context.Remove(counterName);
            }


            /*
             *  restores element key if exists
             *  otherwise just removes
             */

            if (o != null)
            {
                context.Put(elementKey, o);
            }
            else
            {
                context.Remove(elementKey);
            }

            return(true);
        }
コード例 #6
0
        /// <summary>   puts the value of the RHS into the context under the key of the LHS</summary>
        /// <param name="context">
        /// </param>
        /// <param name="writer">
        /// </param>
        /// <returns> True if rendering was sucessful.
        /// </returns>
        /// <throws>  IOException </throws>
        /// <throws>  MethodInvocationException </throws>
        public override bool Render(IInternalContextAdapter context, System.IO.TextWriter writer)
        {
            /*
             *  Get the RHS node, and its value
             */

            object value = right.Value(context);

            /*
             * it's an Error if we don't have a value of some sort AND
             * it is not allowed by configuration
             */

            if (!allowNull)
            {
                if (value == null)
                {
                    /*
                     *  first, are we supposed to say anything anyway?
                     */
                    if (logOnNull)
                    {
                        bool doit = EventHandlerUtil.ShouldLogOnNullSet(rsvc, context, left.Literal, right.Literal);

                        if (doit && rsvc.Log.DebugEnabled)
                        {
                            rsvc.Log.Debug("RHS of #set statement is null. Context will not be modified. " + Log.FormatFileString(this));
                        }
                    }

                    string rightReference = null;
                    if (right is ASTExpression)
                    {
                        rightReference = ((ASTExpression)right).LastToken.Image;
                    }
                    EventHandlerUtil.InvalidSetMethod(rsvc, context, leftReference, rightReference, uberInfo);

                    return(false);
                }
            }

            if (value == null && !strictRef)
            {
                string rightReference = null;
                if (right is ASTExpression)
                {
                    rightReference = ((ASTExpression)right).LastToken.Image;
                }
                EventHandlerUtil.InvalidSetMethod(rsvc, context, leftReference, rightReference, uberInfo);

                /*
                 * if RHS is null, remove simple LHS from context
                 * or call setValue() with a null value for complex LHS
                 */
                if (left.GetNumChildren() == 0)
                {
                    context.Remove(leftReference);
                }
                else
                {
                    left.SetValue(context, (object)null);
                }

                return(false);
            }
            else
            {
                /*
                 *  if the LHS is simple, just punch the value into the context
                 *  otherwise, use the setValue() method do to it.
                 *  Maybe we should always use setValue()
                 */

                if (left.GetNumChildren() == 0)
                {
                    context.Put(leftReference, value);
                }
                else
                {
                    left.SetValue(context, value);
                }
            }

            return(true);
        }
コード例 #7
0
        public override bool Render(IInternalContextAdapter context, TextWriter writer, INode node)
        {
            var railsContext     = EngineContextLocator.Instance.LocateCurrentContext();
            var registry         = railsContext.Services.GetService <IViewComponentFactory>().Registry;
            var viewDescProvider =
                railsContext.Services.GetService <IViewComponentDescriptorProvider>();
            var cacheProvider = railsContext.Services.CacheProvider;

            var compNameNode = node.GetChild(0);

            if (compNameNode == null)
            {
                var message = String.Format("You must specify the component name on the #{0} directive", Name);
                throw new ViewComponentException(message);
            }

            var componentName = compNameNode.FirstToken.Image;

            if (componentName == null)
            {
                var message = String.Format("Could not obtain component name from the #{0} directive", Name);
                throw new ViewComponentException(message);
            }

            if (componentName.StartsWith("$"))
            {
                var nodeContent = compNameNode.Literal.Trim('"', '\'');
                var inlineNode  = runtimeServices.Parse(new StringReader(nodeContent), context.CurrentTemplateName, false);

                inlineNode.Init(context, runtimeServices);
                componentName = (string)Evaluate(inlineNode, context);
            }

            var componentParams = CreateParameters(context, node);

            var viewComptype = registry.GetViewComponent(componentName);

            ViewComponentDescriptor descriptor = null;
            CacheKey key = null;

            if (viewComptype != null)
            {
                descriptor = viewDescProvider.Collect(viewComptype);
            }

            var isOutputtingToCache   = false;
            ViewComponentCacheBag bag = null;

            if (descriptor != null && descriptor.IsCacheable)
            {
                key = descriptor.CacheKeyGenerator.Create(componentName, componentParams, railsContext);

                if (key != null)
                {
                    var cachedContent = (ViewComponentCacheBag)cacheProvider.Get(key.ToString());

                    if (cachedContent != null)
                    {
                        // Restore entries

                        foreach (var pair in cachedContent.ContextEntries)
                        {
                            context[pair.Key] = pair.Value;
                        }

                        // Render from cache

                        writer.Write(cachedContent.Content);

                        return(true);
                    }

                    isOutputtingToCache = true;
                    bag = new ViewComponentCacheBag();
                }
            }

            var component = viewComponentFactory.Create(componentName);

            if (component == null)
            {
                throw new MonoRailException("ViewComponentFactory returned a null ViewComponent for " + componentName + ". " +
                                            "Please investigate the implementation: " + viewComponentFactory.GetType().FullName);
            }

            try
            {
                var directiveNode = (ASTDirective)node;
                var renderer      = (IViewRenderer)directiveNode.Directive;

                var contextAdapter = new NVelocityViewContextAdapter(componentName, node, viewEngine, renderer)
                {
                    Context = isOutputtingToCache ? new CacheAwareContext(context, bag) : context
                };

                INode bodyNode = null;

                if (node.ChildrenCount > 0)
                {
                    bodyNode = node.GetChild(node.ChildrenCount - 1);
                }

                var output = isOutputtingToCache ? bag.CacheWriter : writer;

                contextAdapter.BodyNode        = bodyNode;
                contextAdapter.ComponentParams = componentParams;
                contextAdapter.TextWriter      = output;

                component.Init(railsContext, contextAdapter);

                ProcessSubSections(component, contextAdapter);

                const string ViewComponentContextKey = "viewcomponent";
                var          previousComp            = context[ViewComponentContextKey];

                try
                {
                    context[ViewComponentContextKey] = component;

                    component.Render();

                    if (contextAdapter.ViewToRender != null)
                    {
                        RenderComponentView(context, contextAdapter.ViewToRender, output, contextAdapter);
                    }

                    if (isOutputtingToCache)
                    {
                        // Save output

                        cacheProvider.Store(key.ToString(), bag);

                        // Output to correct writer

                        writer.Write(bag.Content);
                    }
                }
                finally
                {
                    if (previousComp != null)
                    {
                        context[ViewComponentContextKey] = previousComp;
                    }
                    else
                    {
                        context.Remove(ViewComponentContextKey);
                    }
                }
            }
            finally
            {
                viewComponentFactory.Release(component);
            }

            return(true);
        }
コード例 #8
0
        public override bool Render(IInternalContextAdapter context, TextWriter writer, INode node)
        {
            IEnumerator iterator = this.GetIterator(context, node);
            INode       child    = node.GetChild(3);

            INode[][] array = this.PrepareSections(child);
            bool      flag  = array != null;
            bool      result;

            if (iterator == null && !flag)
            {
                result = true;
            }
            else
            {
                int    num  = this.counterInitialValue;
                object obj  = context.Get(this.elementKey);
                object obj2 = context.Get(this.counterName);
                if (iterator != null && iterator.MoveNext())
                {
                    do
                    {
                        object current = iterator.Current;
                        context.Put(this.counterName, num);
                        context.Put(this.elementKey, current);
                        if (!flag)
                        {
                            child.Render(context, writer);
                        }
                        else
                        {
                            if (num == this.counterInitialValue)
                            {
                                this.ProcessSection(ForeachSectionEnum.BeforeAll, array, context, writer);
                            }
                            else
                            {
                                this.ProcessSection(ForeachSectionEnum.Between, array, context, writer);
                            }
                            this.ProcessSection(ForeachSectionEnum.Before, array, context, writer);
                            if ((num - this.counterInitialValue) % 2 == 0)
                            {
                                this.ProcessSection(ForeachSectionEnum.Odd, array, context, writer);
                            }
                            else
                            {
                                this.ProcessSection(ForeachSectionEnum.Even, array, context, writer);
                            }
                            this.ProcessSection(ForeachSectionEnum.Each, array, context, writer);
                            this.ProcessSection(ForeachSectionEnum.After, array, context, writer);
                        }
                        num++;
                    }while (iterator.MoveNext());
                }
                if (flag)
                {
                    if (num > this.counterInitialValue)
                    {
                        this.ProcessSection(ForeachSectionEnum.AfterAll, array, context, writer);
                    }
                    else
                    {
                        this.ProcessSection(ForeachSectionEnum.NoData, array, context, writer);
                    }
                }
                if (obj2 != null)
                {
                    context.Put(this.counterName, obj2);
                }
                else
                {
                    context.Remove(this.counterName);
                }
                if (obj != null)
                {
                    context.Put(this.elementKey, obj);
                }
                else
                {
                    context.Remove(this.elementKey);
                }
                result = true;
            }
            return(result);
        }
コード例 #9
0
 /// <seealso cref="org.apache.velocity.context.Context.remove(java.lang.Object)">
 /// </seealso>
 public virtual object Remove(object key)
 {
     return(innerContext.Remove(key));
 }