示例#1
0
        public EventCartridge AttachEventCartridge(EventCartridge ec)
        {
            EventCartridge result = this.eventCartridge;

            this.eventCartridge = ec;
            return(result);
        }
示例#2
0
        /// <summary>   puts the value of the RHS into the context under the key of the LHS
        /// </summary>
        public override bool Render(IInternalContextAdapter context, TextWriter writer)
        {
            /*
             *  get the RHS node, and it's value
             */

            Object value = right.Value(context);

            /*
             * it's an error if we don't have a value of some sort
             */

            if (value == null)
            {
                /*
                 *  first, are we supposed to say anything anyway?
                 */
                if (blather)
                {
                    EventCartridge eventCartridge = context.EventCartridge;

                    bool doIt = true;

                    /*
                     *  if we have an EventCartridge...
                     */
                    if (eventCartridge != null)
                    {
                        doIt = eventCartridge.ShouldLogOnNullSet(left.Literal, right.Literal);
                    }

                    if (doIt)
                    {
                        runtimeServices.Error(
                            string.Format("RHS of #set statement is null. Context will not be modified. {0} [line {1}, column {2}]",
                                          context.CurrentTemplateName, Line, Column));
                    }
                }

                return(false);
            }

            /*
             *  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.ChildrenCount == 0)
            {
                context.Put(leftReference, value);
            }
            else
            {
                left.SetValue(context, value);
            }

            return(true);
        }
示例#3
0
        public virtual EventCartridge AttachEventCartridge(EventCartridge ec)
        {
            EventCartridge temp = eventCartridge;

            eventCartridge = ec;

            return(temp);
        }
        public EventCartridge AttachEventCartridge(EventCartridge eventCartridge)
        {
            EventCartridge temp = this.eventCartridge;

            this.eventCartridge = eventCartridge;

            return(temp);
        }
示例#5
0
        /* ---- InternalWrapperContext --- */

        /// <summary>  returns the user data context that
        /// we are wrapping
        /// </summary>

        /// <summary>  Returns the base context that we are
        /// wrapping. Here, its this, but for other thing
        /// like VM related context contortions, it can
        /// be something else
        /// </summary>

        /* -----  InternalEventContext ---- */

        public EventCartridge AttachEventCartridge(EventCartridge ec)
        {
            if (iec != null)
            {
                return(iec.AttachEventCartridge(ec));
            }

            return(null);
        }
示例#6
0
        /* ---- InternalWrapperContext --- */

        /// <summary>  returns the user data context that
        /// we are wrapping
        /// </summary>
        /// <summary>  Returns the base context that we are
        /// wrapping. Here, its this, but for other thing
        /// like VM related context contortions, it can
        /// be something else
        /// </summary>
        /* -----  InternalEventContext ---- */
        public EventCartridge AttachEventCartridge(EventCartridge eventCartridge)
        {
            if (internalEventContext != null)
            {
                return(internalEventContext.AttachEventCartridge(eventCartridge));
            }

            return(null);
        }
示例#7
0
        /// <summary>   puts the value of the RHS into the context under the key of the LHS
        /// </summary>
        public override bool render(InternalContextAdapter context, System.IO.TextWriter writer)
        {
            /*
             *  get the RHS node, and it's value
             */

            System.Object value_Renamed = right.value_Renamed(context);

            /*
             * it's an error if we don't have a value of some sort
             */

            if (value_Renamed == null)
            {
                /*
                 *  first, are we supposed to say anything anyway?
                 */
                if (blather)
                {
                    EventCartridge ec = context.EventCartridge;

                    bool doit = true;

                    /*
                     *  if we have an EventCartridge...
                     */
                    if (ec != null)
                    {
                        doit = ec.shouldLogOnNullSet(left.literal(), right.literal());
                    }

                    if (doit)
                    {
                        rsvc.error("RHS of #set statement is null. Context will not be modified. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]");
                    }
                }

                return(false);
            }

            /*
             *  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.jjtGetNumChildren() == 0)
            {
                context.Put(leftReference, value_Renamed);
            }
            else
            {
                left.setValue(context, value_Renamed);
            }

            return(true);
        }
示例#8
0
        public EventCartridge AttachEventCartridge(EventCartridge ec)
        {
            EventCartridge result;

            if (this.iec != null)
            {
                result = this.iec.AttachEventCartridge(ec);
            }
            else
            {
                result = null;
            }
            return(result);
        }
示例#9
0
        public override bool Render(IInternalContextAdapter context, TextWriter writer)
        {
            object obj = this.right.Value(context);
            bool   result;

            if (obj == null)
            {
                if (this.blather)
                {
                    EventCartridge eventCartridge = context.EventCartridge;
                    bool           flag           = true;
                    if (eventCartridge != null)
                    {
                        flag = eventCartridge.ShouldLogOnNullSet(this.left.Literal, this.right.Literal);
                    }
                    if (flag)
                    {
                        this.rsvc.Error(string.Concat(new object[]
                        {
                            "RHS of #set statement is null. Context will not be modified. ",
                            context.CurrentTemplateName,
                            " [line ",
                            base.Line,
                            ", column ",
                            base.Column,
                            "]"
                        }));
                    }
                }
                result = false;
            }
            else
            {
                if (this.left.ChildrenCount == 0)
                {
                    context.Put(this.leftReference, obj);
                }
                else
                {
                    this.left.SetValue(context, obj);
                }
                result = true;
            }
            return(result);
        }
示例#10
0
        /// <summary> Execute method against context.
        /// </summary>
        public override System.Object execute(System.Object o, InternalContextAdapter context)
        {
            if (property == null && method == null)
            {
                return(null);
            }

            try {
                if (property != null)
                {
                    return(property.GetValue(o, null));
                }
                else
                {
                    return(method.Invoke(o, new Object[0]));
                }
            } catch (System.Reflection.TargetInvocationException ite) {
                EventCartridge ec = context.EventCartridge;

                /*
                 *  if we have an event cartridge, see if it wants to veto
                 *  also, let non-Exception Throwables go...
                 */

                if (ec != null && ite.GetBaseException() is System.Exception)
                {
                    try {
                        return(ec.methodException(o.GetType(), propertyUsed, (System.Exception)ite.GetBaseException()));
                    } catch (System.Exception e) {
                        throw new MethodInvocationException("Invocation of property '" + propertyUsed + "'" + " in  " + o.GetType() + " threw exception " + ite.GetBaseException().GetType() + " : " + ite.GetBaseException().Message, ite.GetBaseException(), propertyUsed);
                    }
                }
                else
                {
                    /*
                     * no event cartridge to override. Just throw
                     */

                    throw new MethodInvocationException("Invocation of property '" + propertyUsed + "'" + " in  " + o.GetType() + " threw exception " + ite.GetBaseException().GetType() + " : " + ite.GetBaseException().Message, ite.GetBaseException(), propertyUsed);
                }
            } catch (System.ArgumentException iae) {
                return(null);
            }
        }
示例#11
0
        /// <summary>
        /// invokes the method.  Returns null if a problem, the
        /// actual return if the method returns something, or
        /// an empty string "" if the method returns void
        /// </summary>
        public override Object Execute(Object o, IInternalContextAdapter context)
        {
            IDuck duck = o as IDuck;

            object[] parameters = new object[paramCount];

            if (duck != null)
            {
                EvalParameters(parameters, context);

                return(duck.Invoke(methodName, parameters));
            }

            /*
             *  new strategy (strategy!) for introspection. Since we want
             *  to be thread- as well as context-safe, we *must* do it now,
             *  at execution time.  There can be no in-node caching,
             *  but if we are careful, we can do it in the context.
             */

            MethodInfo   method          = null;
            PropertyInfo property        = null;
            bool         preparedAlready = false;

            object[] methodArguments = new object[paramCount];

            try
            {
                /*
                 *   check the cache
                 */

                IntrospectionCacheData introspectionCacheData = context.ICacheGet(this);
                Type c = o.GetType();

                /*
                 *  like ASTIdentifier, if we have cache information, and the
                 *  Class of Object o is the same as that in the cache, we are
                 *  safe.
                 */

                EvalParameters(parameters, context);

                if (introspectionCacheData != null && introspectionCacheData.ContextData == c)
                {
                    preparedAlready = true;

                    /*
                     * and get the method from the cache
                     */
                    if (introspectionCacheData.Thingy is MethodInfo)
                    {
                        method = (MethodInfo)introspectionCacheData.Thingy;

                        methodArguments = BuildMethodArgs(method, parameters, paramArrayIndex);
                    }
                    if (introspectionCacheData.Thingy is PropertyInfo)
                    {
                        property = (PropertyInfo)introspectionCacheData.Thingy;
                    }
                }
                else
                {
                    /*
                     *  otherwise, do the introspection, and then
                     *  cache it
                     */

                    Object obj = PerformIntrospection(context, c, parameters);

                    if (obj is MethodInfo)
                    {
                        method = (MethodInfo)obj;
                    }
                    if (obj is PropertyInfo)
                    {
                        property = (PropertyInfo)obj;
                    }

                    if (obj != null)
                    {
                        introspectionCacheData             = new IntrospectionCacheData();
                        introspectionCacheData.ContextData = c;
                        introspectionCacheData.Thingy      = obj;
                        context.ICachePut(this, introspectionCacheData);
                    }
                }

                /*
                 *  if we still haven't gotten the method, either we are calling
                 *  a method that doesn't exist (which is fine...)  or I screwed
                 *  it up.
                 */

                if (method == null && property == null)
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                runtimeServices.Error(string.Format("ASTMethod.execute() : exception from introspection : {0}", ex));

                throw new RuntimeException(
                          String.Format(
                              "Error during object introspection. Check inner exception for details. Node literal {0} Line {1} Column {2}",
                              base.Literal, Line, Column), ex);
            }

            try
            {
                /*
                 *  get the returned object.  It may be null, and that is
                 *  valid for something declared with a void return type.
                 *  Since the caller is expecting something to be returned,
                 *  as long as things are peachy, we can return an empty
                 *  String so ASTReference() correctly figures out that
                 *  all is well.
                 */

                Object obj;

                if (method == null)
                {
                    obj = property.GetValue(o, null);
                }
                else
                {
                    if (!preparedAlready)
                    {
                        methodArguments = BuildMethodArgs(method, parameters);
                    }

                    obj = method.Invoke(o, methodArguments);

                    if (obj == null && method.ReturnType == typeof(void))
                    {
                        obj = String.Empty;
                    }
                }

                return(obj);
            }
            catch (TargetInvocationException targetInvocationException)
            {
                /*
                 *  In the event that the invocation of the method
                 *  itself throws an exception, we want to catch that
                 *  wrap it, and throw.  We don't log here as we want to figure
                 *  out which reference threw the exception, so do that
                 *  above
                 */

                EventCartridge eventCartridge = context.EventCartridge;

                /*
                 *  if we have an event cartridge, see if it wants to veto
                 *  also, let non-Exception Throwables go...
                 */

                if (eventCartridge == null)
                {
                    /*
                     * no event cartridge to override. Just throw
                     */

                    throw new MethodInvocationException(
                              string.Format("Invocation of method '{0}' in  {1} threw exception {2} : {3}", methodName, o.GetType(),
                                            targetInvocationException.GetBaseException().GetType(),
                                            targetInvocationException.GetBaseException().Message), targetInvocationException,
                              methodName);
                }
                else
                {
                    try
                    {
                        return(eventCartridge.HandleMethodException(o.GetType(), methodName, targetInvocationException));
                    }
                    catch (Exception e)
                    {
                        throw new MethodInvocationException(
                                  string.Format("Invocation of method '{0}' in  {1} threw exception {2} : {3}", methodName, o.GetType(),
                                                e.GetType(), e.Message), e, methodName);
                    }
                }
            }
            catch (Exception e)
            {
                runtimeServices.Error(
                    string.Format("ASTMethod.execute() : exception invoking method '{0}' in {1} : {2}", methodName, o.GetType(), e));
                throw;
            }
        }
示例#12
0
        /// <summary>
        /// invokes the method on the object passed in
        /// </summary>
        public override Object Execute(Object o, IInternalContextAdapter context)
        {
            bool isString    = o.GetType() == typeof(string);
            bool isDecimal   = o.GetType() == typeof(decimal);
            bool isPrimitive = o.GetType().IsPrimitive;

            if (identifier == "to_quote" && (isString || isPrimitive || isDecimal))
            {
                return(string.Format("\"{0}\"", EscapeDoubleQuote(o.ToString())));
            }
            else if (identifier == "to_squote" && (isString || isPrimitive || isDecimal))
            {
                return(string.Format("'{0}'", EscapeSingleQuote(o.ToString())));
            }

            IDuck duck = o as IDuck;

            if (duck != null)
            {
                return(duck.GetInvoke(identifier));
            }

            IVelPropertyGet velPropertyGet = null;

            try
            {
                Type c = o.GetType();

                // first, see if we have this information cached.
                IntrospectionCacheData introspectionCacheData = context.ICacheGet(this);

                // if we have the cache data and the class of the object we are
                // invoked with is the same as that in the cache, then we must
                // be all-right.  The last 'variable' is the method name, and
                // that is fixed in the template :)

                if (introspectionCacheData != null && introspectionCacheData.ContextData == c)
                {
                    velPropertyGet = (IVelPropertyGet)introspectionCacheData.Thingy;
                }
                else
                {
                    // otherwise, do the introspection, and cache it
                    velPropertyGet = runtimeServices.Uberspect.GetPropertyGet(o, identifier, uberInfo);

                    if (velPropertyGet != null && velPropertyGet.Cacheable)
                    {
                        introspectionCacheData = new IntrospectionCacheData(c, velPropertyGet);
                        context.ICachePut(this, introspectionCacheData);
                    }
                }
            }
            catch (Exception e)
            {
                runtimeServices.Error(string.Format("ASTIdentifier.execute() : identifier = {0} : {1}", identifier, e));
            }

            // we have no executor... punt...
            if (velPropertyGet == null)
            {
                return(null);
            }

            // now try and execute.  If we get a TargetInvocationException,
            // throw that as the app wants to get these. If not, log and punt.
            try
            {
                return(velPropertyGet.Invoke(o));
            }
            catch (TargetInvocationException targetInvocationException)
            {
                EventCartridge ec = context.EventCartridge;

                // if we have an event cartridge, see if it wants to veto
                // also, let non-Exception Throwables go...
                if (ec == null)
                {
                    // no event cartridge to override. Just throw
                    String message = String.Format(
                        "Invocation of method '{0}' in {1}, template {2} Line {3} Column {4} threw an exception",
                        velPropertyGet.MethodName, o != null ? o.GetType().FullName : string.Empty,
                        uberInfo.TemplateName, uberInfo.Line, uberInfo.Column);

                    throw new MethodInvocationException(message, targetInvocationException.InnerException, velPropertyGet.MethodName);
                }
                else
                {
                    try
                    {
                        return(ec.HandleMethodException(o.GetType(), velPropertyGet.MethodName, targetInvocationException.InnerException));
                    }
                    catch (Exception)
                    {
                        String message = String.Format(
                            "Invocation of method '{0}' in {1}, template {2} Line {3} Column {4} threw an exception",
                            velPropertyGet.MethodName, o != null ? o.GetType().FullName : string.Empty,
                            uberInfo.TemplateName, uberInfo.Line, uberInfo.Column);

                        throw new MethodInvocationException(message, targetInvocationException.InnerException, velPropertyGet.MethodName);
                    }
                }
            }
            catch (ArgumentException)
            {
                return(null);
            }
            catch (Exception e)
            {
                runtimeServices.Error(
                    string.Format("ASTIdentifier() : exception invoking method for identifier '{0}' in {1} : {2}", identifier,
                                  o.GetType(), e));
            }

            return(null);
        }
示例#13
0
 public EventCartridge AttachEventCartridge(EventCartridge ec)
 {
     return(innerContext.AttachEventCartridge(ec));
 }
        /// <summary>
        /// invokes the method.  Returns null if a problem, the
        /// actual return if the method returns something, or
        /// an empty string "" if the method returns void
        /// </summary>
        public override Object execute(Object o, InternalContextAdapter context)
        {
            /*
             *  new strategy (strategery!) for introspection. Since we want
             *  to be thread- as well as context-safe, we *must* do it now,
             *  at execution time.  There can be no in-node caching,
             *  but if we are careful, we can do it in the context.
             */

            MethodInfo   method          = null;
            PropertyInfo property        = null;
            bool         preparedAlready = false;

            Object[] methodArguments = params_Renamed;

            try
            {
                /*
                 *   check the cache
                 */

                IntrospectionCacheData icd = context.ICacheGet(this);
                Type c = o.GetType();

                /*
                 *  like ASTIdentifier, if we have cache information, and the
                 *  Class of Object o is the same as that in the cache, we are
                 *  safe.
                 */

                if (icd != null && icd.contextData == c)
                {
                    // We blindly assume that if there's an array,
                    // we're dealing with a "params array[] args" and
                    // if so, we create an array with an appropriate size

//					int arrayArg = paramArrayIndex == -1 ? int.MaxValue : paramArrayIndex;

//					for (int j = 0; j < paramCount; j++)
//					{
//						if (params_Renamed[j] != null && params_Renamed[j].GetType().IsArray)
//						{
//							Array array = Array.CreateInstance(
//								params_Renamed[j].GetType().GetElementType(), paramCount - j );
//
//							params_Renamed[j] = array;
//
//							arrayArg = j; break;
//						}
//					}

                    /*
                     * sadly, we do need recalc the values of the args, as this can
                     * change from visit to visit
                     */

                    for (int j = 0; j < paramCount; j++)
                    {
                        params_Renamed[j] = jjtGetChild(j + 1).Value(context);
                    }

                    preparedAlready = true;

                    /*
                     * and get the method from the cache
                     */
                    if (icd.thingy is MethodInfo)
                    {
                        method = (MethodInfo)icd.thingy;

                        methodArguments = BuildMethodArgs(method, paramArrayIndex);
                    }
                    if (icd.thingy is PropertyInfo)
                    {
                        property = (PropertyInfo)icd.thingy;
                    }
                }
                else
                {
                    /*
                     *  otherwise, do the introspection, and then
                     *  cache it
                     */

                    Object obj = doIntrospection(context, c);

                    if (obj is MethodInfo)
                    {
                        method = (MethodInfo)obj;
                    }
                    if (obj is PropertyInfo)
                    {
                        property = (PropertyInfo)obj;
                    }

                    if (obj != null)
                    {
                        icd             = new IntrospectionCacheData();
                        icd.contextData = c;
                        icd.thingy      = obj;
                        context.ICachePut(this, icd);
                    }
                }

                /*
                 *  if we still haven't gotten the method, either we are calling
                 *  a method that doesn't exist (which is fine...)  or I screwed
                 *  it up.
                 */

                if (method == null && property == null)
                {
                    return(null);
                }
            }
            catch (Exception e)
            {
                /*
                 *  can come from the doIntropection() also, from Introspector
                 */

                rsvc.error("ASTMethod.execute() : exception from introspection : " + e);
                throw;
            }

            try
            {
                /*
                 *  get the returned object.  It may be null, and that is
                 *  valid for something declared with a void return type.
                 *  Since the caller is expecting something to be returned,
                 *  as long as things are peachy, we can return an empty
                 *  String so ASTReference() correctly figures out that
                 *  all is well.
                 */

                Object obj = null;

                if (method != null)
                {
                    if (!preparedAlready)
                    {
                        methodArguments = BuildMethodArgs(method);
                    }

                    obj = method.Invoke(o, methodArguments);

                    if (obj == null && method.ReturnType == typeof(void))
                    {
                        obj = String.Empty;
                    }
                }
                else
                {
                    obj = property.GetValue(o, null);
                }

                return(obj);
            }
            catch (TargetInvocationException ite)
            {
                /*
                 *  In the event that the invocation of the method
                 *  itself throws an exception, we want to catch that
                 *  wrap it, and throw.  We don't log here as we want to figure
                 *  out which reference threw the exception, so do that
                 *  above
                 */

                EventCartridge ec = context.EventCartridge;

                /*
                 *  if we have an event cartridge, see if it wants to veto
                 *  also, let non-Exception Throwables go...
                 */

                if (ec != null && ite.GetBaseException() is Exception)
                {
                    try
                    {
                        return(ec.methodException(o.GetType(), methodName, (Exception)ite.GetBaseException()));
                    }
                    catch (Exception e)
                    {
                        throw new MethodInvocationException("Invocation of method '" + methodName + "' in  " + o.GetType() + " threw exception " + e.GetType() + " : " + e.Message, e, methodName);
                    }
                }
                else
                {
                    /*
                     * no event cartridge to override. Just throw
                     */

                    throw new MethodInvocationException("Invocation of method '" + methodName + "' in  " + o.GetType() + " threw exception " + ite.GetBaseException().GetType() + " : " + ite.GetBaseException().Message, ite.GetBaseException(), methodName);
                }
            }
            catch (Exception e)
            {
                rsvc.error("ASTMethod.execute() : exception invoking method '" + methodName + "' in " + o.GetType() + " : " + e);
                throw e;
            }
        }
示例#15
0
        public override object Execute(object o, IInternalContextAdapter context)
        {
            MethodInfo   methodInfo   = null;
            PropertyInfo propertyInfo = null;
            bool         flag         = false;

            object[] array = this.parameters;
            object   result;

            try
            {
                IntrospectionCacheData introspectionCacheData = context.ICacheGet(this);
                Type type = o.GetType();
                if (introspectionCacheData != null && introspectionCacheData.ContextData == type)
                {
                    for (int i = 0; i < this.paramCount; i++)
                    {
                        this.parameters[i] = base.GetChild(i + 1).Value(context);
                    }
                    flag = true;
                    if (introspectionCacheData.Thingy is MethodInfo)
                    {
                        methodInfo = (MethodInfo)introspectionCacheData.Thingy;
                        array      = this.BuildMethodArgs(methodInfo, this.paramArrayIndex);
                    }
                    if (introspectionCacheData.Thingy is PropertyInfo)
                    {
                        propertyInfo = (PropertyInfo)introspectionCacheData.Thingy;
                    }
                }
                else
                {
                    object obj = this.doIntrospection(context, type);
                    if (obj is MethodInfo)
                    {
                        methodInfo = (MethodInfo)obj;
                    }
                    if (obj is PropertyInfo)
                    {
                        propertyInfo = (PropertyInfo)obj;
                    }
                    if (obj != null)
                    {
                        context.ICachePut(this, new IntrospectionCacheData
                        {
                            ContextData = type,
                            Thingy      = obj
                        });
                    }
                }
                if (methodInfo == null && propertyInfo == null)
                {
                    result = null;
                    return(result);
                }
            }
            catch (System.Exception ex)
            {
                this.rsvc.Error("ASTMethod.execute() : exception from introspection : " + ex);
                throw new RuntimeException(string.Format("Error during object instrospection. Check inner exception for details. Node literal {0} Line {1} Column {2}", base.Literal, base.Line, base.Column), ex);
            }
            try
            {
                object obj;
                if (methodInfo != null)
                {
                    if (!flag)
                    {
                        array = this.BuildMethodArgs(methodInfo);
                    }
                    obj = methodInfo.Invoke(o, array);
                    if (obj == null && methodInfo.ReturnType == typeof(void))
                    {
                        obj = string.Empty;
                    }
                }
                else
                {
                    obj = propertyInfo.GetValue(o, null);
                }
                result = obj;
            }
            catch (TargetInvocationException ex2)
            {
                EventCartridge eventCartridge = context.EventCartridge;
                if (eventCartridge != null)
                {
                    try
                    {
                        result = eventCartridge.HandleMethodException(o.GetType(), this.methodName, ex2.GetBaseException());
                        return(result);
                    }
                    catch (System.Exception ex3)
                    {
                        throw new MethodInvocationException(string.Concat(new object[]
                        {
                            "Invocation of method '",
                            this.methodName,
                            "' in  ",
                            o.GetType(),
                            " threw exception ",
                            ex3.GetType(),
                            " : ",
                            ex3.Message
                        }), ex3, this.methodName);
                    }
                }
                throw new MethodInvocationException(string.Concat(new object[]
                {
                    "Invocation of method '",
                    this.methodName,
                    "' in  ",
                    o.GetType(),
                    " threw exception ",
                    ex2.GetBaseException().GetType(),
                    " : ",
                    ex2.GetBaseException().Message
                }), ex2.GetBaseException(), this.methodName);
            }
            catch (System.Exception ex3)
            {
                this.rsvc.Error(string.Concat(new object[]
                {
                    "ASTMethod.execute() : exception invoking method '",
                    this.methodName,
                    "' in ",
                    o.GetType(),
                    " : ",
                    ex3
                }));
                throw ex3;
            }
            return(result);
        }
示例#16
0
        /// <summary>
        /// invokes the method on the object passed in
        /// </summary>
        public override Object execute(Object o, InternalContextAdapter context)
        {
            VelPropertyGet vg = null;

            try
            {
                Type c = o.GetType();

                /*
                 *  first, see if we have this information cached.
                 */

                IntrospectionCacheData icd = context.ICacheGet(this);

                /*
                 * if we have the cache data and the class of the object we are
                 * invoked with is the same as that in the cache, then we must
                 * be allright.  The last 'variable' is the method name, and
                 * that is fixed in the template :)
                 */

                if (icd != null && icd.contextData == c)
                {
                    vg = (VelPropertyGet)icd.thingy;
                }
                else
                {
                    /*
                     *  otherwise, do the introspection, and cache it
                     */
                    vg = rsvc.Uberspect.getPropertyGet(o, identifier, uberInfo);

                    if (vg != null && vg.Cacheable)
                    {
                        icd             = new IntrospectionCacheData();
                        icd.contextData = c;
                        icd.thingy      = vg;
                        context.ICachePut(this, icd);
                    }
                }
            }
            catch (Exception e)
            {
                rsvc.error("ASTIdentifier.execute() : identifier = " + identifier + " : " + e);
            }

            /*
             *  we have no executor... punt...
             */
            if (vg == null)
            {
                return(null);
            }

            /*
             *  now try and execute.  If we get a MIE, throw that
             *  as the app wants to get these.  If not, log and punt.
             */
            try
            {
                return(vg.invoke(o));
            }
            catch (TargetInvocationException ite)
            {
                EventCartridge ec = context.EventCartridge;

                /*
                 *  if we have an event cartridge, see if it wants to veto
                 *  also, let non-Exception Throwables go...
                 */
                if (ec != null)
                {
                    try
                    {
                        return(ec.methodException(o.GetType(), vg.MethodName, ite.InnerException));
                    }
                    catch (Exception e)
                    {
                        String message = String.Format(
                            "Invocation of method '{0}' in {1}, template {2} Line {3} Column {4} threw exception {5} {6}",
                            vg.MethodName, o != null ? o.GetType().FullName : "",
                            uberInfo.TemplateName, uberInfo.Line, uberInfo.Column,
                            ite.InnerException.GetType(), ite.InnerException.Message);

                        throw new MethodInvocationException(message, ite.InnerException, vg.MethodName);
                    }
                }
                else
                {
                    /*
                     * no event cartridge to override. Just throw
                     */
                    String message = String.Format(
                        "Invocation of method '{0}' in {1}, template {2} Line {3} Column {4} threw exception {5} {6}",
                        vg.MethodName, o != null ? o.GetType().FullName : "",
                        uberInfo.TemplateName, uberInfo.Line, uberInfo.Column,
                        ite.InnerException.GetType(), ite.InnerException.Message);

                    throw new MethodInvocationException(message, ite.InnerException, vg.MethodName);
                }
            }
            catch (ArgumentException iae)
            {
                return(null);
            }
            catch (Exception e)
            {
                rsvc.error("ASTIdentifier() : exception invoking method "
                           + "for identifier '" + identifier + "' in "
                           + o.GetType() + " : " + e);
            }

            return(null);
        }
示例#17
0
        /// <summary>  gets the value of the reference and outputs it to the
        /// writer.
        /// *
        /// </summary>
        /// <param name="context"> context of data to use in getting value
        /// </param>
        /// <param name="writer">  writer to render to
        ///
        /// </param>
        public override bool render(InternalContextAdapter context, System.IO.TextWriter writer)
        {
            if (referenceType == RUNT)
            {
                writer.Write(rootString);
                return(true);
            }

            System.Object value_Renamed = execute(null, context);

            /*
             *  if this reference is escaped (\$foo) then we want to do one of two things :
             *  1) if this is a reference in the context, then we want to print $foo
             *  2) if not, then \$foo  (its considered shmoo, not VTL)
             */

            if (escaped)
            {
                if (value_Renamed == null)
                {
                    writer.Write(escPrefix);
                    writer.Write("\\");
                    writer.Write(nullString);
                }
                else
                {
                    writer.Write(escPrefix);
                    writer.Write(nullString);
                }

                return(true);
            }

            /*
             *  the normal processing
             *
             *  if we have an event cartridge, get a new value object
             */
            EventCartridge ec = context.EventCartridge;

            if (ec != null)
            {
                value_Renamed = ec.referenceInsert(nullString, value_Renamed);
            }

            /*
             *  if value is null...
             */

            if (value_Renamed == null)
            {
                /*
                 *  write prefix twice, because it's shmoo, so the \ don't escape each other...
                 */

                writer.Write(escPrefix);
                writer.Write(escPrefix);
                writer.Write(morePrefix);
                writer.Write(nullString);

                if (referenceType != QUIET_REFERENCE && rsvc.getBoolean(NVelocity.Runtime.RuntimeConstants_Fields.RUNTIME_LOG_REFERENCE_LOG_INVALID, true))
                {
                    rsvc.warn(new ReferenceException("reference : template = " + context.CurrentTemplateName, this));
                }

                return(true);
            }
            else
            {
                /*
                 *  non-null processing
                 */

                writer.Write(escPrefix);
                writer.Write(morePrefix);
                //UPGRADE_TODO: The equivalent in .NET for method 'java.Object.toString' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"'
                writer.Write(value_Renamed.ToString());

                return(true);
            }
        }
示例#18
0
        public Test(System.String templateFile, System.String encoding)
        {
            System.IO.StreamWriter writer = null;
            TestProvider provider = new TestProvider();
            ArrayList al = provider.Customers;
            System.Collections.Hashtable h = new System.Collections.Hashtable();

            /*
            *  put this in to test introspection $h.Bar or $h.get("Bar") etc
            */

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

            /*
            *  adding simple vector with strings for testing late introspection stuff
            */

            System.Collections.ArrayList v = new System.Collections.ArrayList();

            System.String str = "mystr";

            v.Add(new System.String("hello".ToCharArray()));
            v.Add(new System.String("hello2".ToCharArray()));
            v.Add(str);

            try {
            /*
            *  this is another way to do properties when initializing Runtime.
            *  make a Properties
            */

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

            /*
            *  now, if you want to, load it from a file (or whatever)
            */

            try {
            System.IO.FileStream fis = new System.IO.FileStream(new System.IO.FileInfo("velocity.properties").FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            if (fis != null) {
            //UPGRADE_ISSUE: Method 'java.util.Properties.load' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javautilPropertiesload_javaioInputStream"'
            p.load(fis);
            }
            } catch (System.Exception ex) {
            /* no worries. no file... */
            }

            /*
            *  iterate out the properties
            */

            System.Collections.Specialized.NameValueCollection temp_namedvaluecollection;
            temp_namedvaluecollection = System.Configuration.ConfigurationSettings.AppSettings;
            //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"'
            for (System.Collections.IEnumerator e = temp_namedvaluecollection.GetEnumerator(); e.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 el = (System.String) e.Current;

            //UPGRADE_WARNING: method 'java.util.Properties.getProperty' was converted to ' ' which may throw an exception. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1101"'
            Velocity.setProperty(el, (System.String) p.GetValue(el, System.Type.GetType("System.String")));
            }

            /*
            *  add some individual properties if you wish
            */

            Velocity.setProperty(Velocity.RUNTIME_LOG_ERROR_STACKTRACE, "true");
            Velocity.setProperty(Velocity.RUNTIME_LOG_WARN_STACKTRACE, "true");
            Velocity.setProperty(Velocity.RUNTIME_LOG_INFO_STACKTRACE, "true");

            /*
            *  use an alternative logger.  Set it up here and pass it in.
            */

            //            SimpleLogSystem sls = new SimpleLogSystem("velocity_simple.log");

            // Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, sls );

            /*
            *  and now call init
            */

            Velocity.init();

            /*
            *  now, do what we want to do.  First, get the Template
            */

            if (templateFile == null) {
            templateFile = "examples/example.vm";
            }

            Template template = null;

            try
            {
            template = RuntimeSingleton.getTemplate(templateFile, encoding)
            ;
            }
            catch (ResourceNotFoundException rnfe) {
            System.Console.Out.WriteLine("Test : RNFE : Cannot find template " + templateFile);
            } catch (ParseErrorException pee) {
            System.Console.Out.WriteLine("Test : Syntax error in template " + templateFile + ":" + pee);
            }

            /*
            * now, make a Context object and populate it.
            */

            VelocityContext context = new VelocityContext();

            context.put("provider", provider);
            context.put("name", "jason");
            context.put("providers", provider.Customers2);
            context.put("list", al);
            context.put("hashtable", h);
            context.put("search", provider.Search);
            context.put("relatedSearches", provider.RelSearches);
            context.put("searchResults", provider.RelSearches);
            context.put("menu", provider.Menu);
            context.put("stringarray", provider.Array);
            context.put("vector", v);
            context.put("mystring", new System.String("".ToCharArray()));
            context.put("hashmap", new HashMap());
            context.put("runtime", new FieldMethodizer("org.apache.velocity.runtime.RuntimeSingleton"));
            context.put("fmprov", new FieldMethodizer(provider));
            context.put("Floog", "floogie woogie");
            context.put("geirstring", str);
            context.put("mylong", 5);

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

            int[] intarr = new int[]{10, 20, 30, 40, 50};

            System.Object[] oarr = new System.Object[]{"a", "b", "c", "d"};

            context.put("collection", v);
            context.put("iterator", v.iterator());
            context.put("map", h);
            context.put("obarr", oarr);
            context.put("intarr", intarr);

            System.String stest = " My name is $name -> $Floog";
            System.IO.StringWriter w = new System.IO.StringWriter();
            //            Velocity.evaluate( context, w, "evaltest",stest );
            //            System.out.println("Eval = " + w );

            w = new System.IO.StringWriter();
            //Velocity.mergeTemplate( "mergethis.vm",  context, w );
            //System.out.println("Merge = " + w );

            w = new System.IO.StringWriter();
            //Velocity.invokeVelocimacro( "floog", "test", new String[2],  context,  w );
            //System.out.println("Invoke = " + w );

            /*
            *  event cartridge stuff
            */

            EventCartridge ec = new EventCartridge();
            ec.addEventHandler(this);
            ec.attachToContext(context);

            /*
            *  make a writer, and merge the template 'against' the context
            */

            VelocityContext vc = new VelocityContext(context);

            if (template != null) {
            //UPGRADE_ISSUE: Constructor 'java.io.BufferedWriter.BufferedWriter' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javaioBufferedWriterBufferedWriter_javaioWriter"'
            writer = new BufferedWriter(new System.IO.StreamWriter(System.Console.Out));
            template.merge(vc, writer);
            writer.Flush();
            writer.Close();
            }

            } catch (MethodInvocationException mie) {
            System.Console.Out.WriteLine("MIE : " + mie);
            } catch (System.Exception e) {
            RuntimeSingleton.error("Test- exception : " + e);
            SupportClass.WriteStackTrace(e, Console.Error);

            }
        }
示例#19
0
        public override object Execute(object o, IInternalContextAdapter context)
        {
            IVelPropertyGet velPropertyGet = null;

            try
            {
                Type type = o.GetType();
                IntrospectionCacheData introspectionCacheData = context.ICacheGet(this);
                if (introspectionCacheData != null && introspectionCacheData.ContextData == type)
                {
                    velPropertyGet = (IVelPropertyGet)introspectionCacheData.Thingy;
                }
                else
                {
                    velPropertyGet = this.rsvc.Uberspect.GetPropertyGet(o, this.identifier, this.uberInfo);
                    if (velPropertyGet != null && velPropertyGet.Cacheable)
                    {
                        introspectionCacheData = new IntrospectionCacheData(type, velPropertyGet);
                        context.ICachePut(this, introspectionCacheData);
                    }
                }
            }
            catch (System.Exception ex)
            {
                this.rsvc.Error(string.Concat(new object[]
                {
                    "ASTIdentifier.execute() : identifier = ",
                    this.identifier,
                    " : ",
                    ex
                }));
            }
            object result;

            if (velPropertyGet == null)
            {
                result = null;
            }
            else
            {
                try
                {
                    result = velPropertyGet.Invoke(o);
                    return(result);
                }
                catch (TargetInvocationException ex2)
                {
                    EventCartridge eventCartridge = context.EventCartridge;
                    string         message;
                    if (eventCartridge != null)
                    {
                        try
                        {
                            result = eventCartridge.HandleMethodException(o.GetType(), velPropertyGet.MethodName, ex2.InnerException);
                            return(result);
                        }
                        catch (System.Exception)
                        {
                            message = string.Format("Invocation of method '{0}' in {1}, template {2} Line {3} Column {4} threw an exception", new object[]
                            {
                                velPropertyGet.MethodName,
                                (o != null) ? o.GetType().FullName : "",
                                this.uberInfo.TemplateName,
                                this.uberInfo.Line,
                                this.uberInfo.Column
                            });
                            throw new MethodInvocationException(message, ex2.InnerException, velPropertyGet.MethodName);
                        }
                    }
                    message = string.Format("Invocation of method '{0}' in {1}, template {2} Line {3} Column {4} threw an exception", new object[]
                    {
                        velPropertyGet.MethodName,
                        (o != null) ? o.GetType().FullName : "",
                        this.uberInfo.TemplateName,
                        this.uberInfo.Line,
                        this.uberInfo.Column
                    });
                    throw new MethodInvocationException(message, ex2.InnerException, velPropertyGet.MethodName);
                }
                catch (ArgumentException)
                {
                    result = null;
                    return(result);
                }
                catch (System.Exception ex)
                {
                    this.rsvc.Error(string.Concat(new object[]
                    {
                        "ASTIdentifier() : exception invoking method for identifier '",
                        this.identifier,
                        "' in ",
                        o.GetType(),
                        " : ",
                        ex
                    }));
                }
                result = null;
            }
            return(result);
        }
示例#20
0
 static EscapeUtils()
 {
     ec = new EventCartridge();
     ec.ReferenceInsertion += ec_ReferenceInsertion;
 }
示例#21
0
        /// <summary>
        /// gets the value of the reference and outputs it to the
        /// writer.
        /// </summary>
        /// <param name="context"> context of data to use in getting value </param>
        /// <param name="writer">  writer to render to </param>
        public override bool Render(IInternalContextAdapter context, TextWriter writer)
        {
            if (referenceType == ReferenceType.Runt)
            {
                writer.Write(rootString);
                return(true);
            }

            Object value = Execute(null, context);

            // if this reference is escaped (\$foo) then we want to do one of two things :
            // 1) if this is a reference in the context, then we want to print $foo
            // 2) if not, then \$foo  (its considered shmoo, not VTL)
            if (escaped)
            {
                StringBuilder b = new StringBuilder();
                b.Append(escPrefix);
                if (value == null)
                {
                    b.Append("\\");
                }
                b.Append(nullString);

                writer.Write(b);

                return(true);
            }

            // the normal processing

            // if we have an event cartridge, get a new value object
            EventCartridge eventCartridge = context.EventCartridge;

            if (eventCartridge != null && referenceStack != null)
            {
                value = eventCartridge.ReferenceInsert(referenceStack, nullString, value);
            }

            // if value is null...
            if (value == null)
            {
                // write prefix twice, because it's shmoo, so the \ don't escape each other...
                StringBuilder b = new StringBuilder();

                b.Append(escPrefix);
                b.Append(escPrefix);
                b.Append(morePrefix);
                b.Append(nullString);

                writer.Write(b);

                if (referenceType != ReferenceType.Quiet &&
                    runtimeServices.GetBoolean(RuntimeConstants.RUNTIME_LOG_REFERENCE_LOG_INVALID, true))
                {
                    runtimeServices.Warn(
                        new ReferenceException(string.Format("reference : template = {0}", context.CurrentTemplateName), this));
                }

                return(true);
            }
            else
            {
                // non-null processing
                StringBuilder b = new StringBuilder();
                b.Append(escPrefix);
                b.Append(morePrefix);
                b.Append(value);

                writer.Write(b);

                return(true);
            }
        }
        /// <summary> Runs the test.
        /// </summary>
        public virtual void runTest()
        {
            /*
            *  lets make a Context and add the event cartridge
            */

            VelocityContext inner = new VelocityContext();

            /*
            *  Now make an event cartridge, register all the
            *  event handlers (at once) and attach it to the
            *  Context
            */

            EventCartridge ec = new EventCartridge();
            ec.addEventHandler(this);
            ec.attachToContext(inner);

            /*
            *  now wrap the event cartridge - we want to make sure that
            *  we can do this w/o harm
            */

            VelocityContext context = new VelocityContext(inner);

            context.put("name", "Velocity");

            try {
            /*
            *  First, the reference insertion handler
            */

            System.String s = "$name";

            System.IO.StringWriter w = new System.IO.StringWriter();
            Velocity.evaluate(context, w, "mystring", s);

            if (!w.ToString().Equals(REFERENCE_VALUE)) {
            fail("Reference insertion test 1");
            }

            /*
            *  using the same handler, we can deal with
            *  null references as well
            */

            s = "$floobie";

            w = new System.IO.StringWriter();
            Velocity.evaluate(context, w, "mystring", s);

            if (!w.ToString().Equals(NO_REFERENCE_VALUE)) {
            fail("Reference insertion test 2");
            }

            /*
            *  now lets test setting a null value - this test
            *  should result in *no* log output.
            */

            s = "#set($settest = $NotAReference)";
            w = new System.IO.StringWriter();
            logString = null;
            Velocity.evaluate(context, w, "mystring", s);

            if (logString != null) {
            fail("NullSetEventHandler test 1");
            }

            /*
            *  now lets test setting a null value - this test
            *  should result in log output.
            */

            s = "#set($logthis = $NotAReference)";
            w = new System.IO.StringWriter();
            logString = null;
            Velocity.evaluate(context, w, "mystring", s);

            if (logString == null) {
            fail("NullSetEventHandler test 1");
            }

            /*
            *  finally, we test a method exception event - we do this
            *  by putting this class in the context, and calling
            *  a method that does nothing but throw an exception.
            *  we use a little switch to turn the event handling
            *  on and off
            *
            *  Note also how the reference insertion process
            *  happens as well
            */

            exceptionSwitch = true;

            context.put("this", this);

            s = " $this.throwException()";
            w = new System.IO.StringWriter();

            try {
            Velocity.evaluate(context, w, "mystring", s);
            } catch (MethodInvocationException mee) {
            fail("MethodExceptionEvent test 1");
            } catch (System.Exception e) {
            fail("MethodExceptionEvent test 1");
            }

            /*
            *  now, we turn the switch off, and we can see that the
            *  exception will propgate all the way up here, and
            *  wil be caught by the catch() block below
            */

            exceptionSwitch = false;

            s = " $this.throwException()";
            w = new System.IO.StringWriter();

            try {
            Velocity.evaluate(context, w, "mystring", s);
            fail("MethodExceptionEvent test 2");
            } catch (MethodInvocationException mee) {
            /*
            * correct - should land here...
            */
            } catch (System.Exception e) {
            fail("MethodExceptionEvent test 2");
            }
            } catch (ParseErrorException pee) {
            fail("ParseErrorException" + pee);
            } catch (MethodInvocationException mee) {
            fail("MethodInvocationException" + mee);
            } catch (System.Exception e) {
            fail("Exception" + e);
            }
        }
示例#23
0
        public override bool Render(IInternalContextAdapter context, TextWriter writer)
        {
            bool result;

            if (this.referenceType == ReferenceType.Runt)
            {
                char[] array = this.rootString.ToCharArray();
                writer.Write(array, 0, array.Length);
                result = true;
            }
            else
            {
                object obj = this.Execute(null, context);
                if (this.escaped)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.Append(this.escPrefix);
                    if (obj == null)
                    {
                        stringBuilder.Append("\\");
                    }
                    stringBuilder.Append(this.nullString);
                    char[] array = stringBuilder.ToString().ToCharArray();
                    writer.Write(array, 0, array.Length);
                    result = true;
                }
                else
                {
                    EventCartridge eventCartridge = context.EventCartridge;
                    if (eventCartridge != null && this.referenceStack != null)
                    {
                        obj = eventCartridge.ReferenceInsert(this.referenceStack, this.nullString, obj);
                    }
                    if (obj == null)
                    {
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.Append(this.escPrefix);
                        stringBuilder.Append(this.escPrefix);
                        stringBuilder.Append(this.morePrefix);
                        stringBuilder.Append(this.nullString);
                        char[] array = stringBuilder.ToString().ToCharArray();
                        writer.Write(array, 0, array.Length);
                        if (this.referenceType != ReferenceType.Quiet && this.rsvc.GetBoolean("runtime.log.invalid.references", true))
                        {
                            this.rsvc.Warn(new ReferenceException("reference : template = " + context.CurrentTemplateName, this));
                        }
                        result = true;
                    }
                    else
                    {
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.Append(this.escPrefix);
                        stringBuilder.Append(this.morePrefix);
                        stringBuilder.Append(obj);
                        char[] array = stringBuilder.ToString().ToCharArray();
                        writer.Write(array, 0, array.Length);
                        result = true;
                    }
                }
            }
            return(result);
        }
示例#24
0
        /// <summary> Runs the test.
        /// </summary>
        public virtual void  runTest()
        {
            /*
             *  lets make a Context and add the event cartridge
             */

            VelocityContext inner = new VelocityContext();

            /*
             *  Now make an event cartridge, register all the
             *  event handlers (at once) and attach it to the
             *  Context
             */

            EventCartridge ec = new EventCartridge();

            ec.addEventHandler(this);
            ec.attachToContext(inner);

            /*
             *  now wrap the event cartridge - we want to make sure that
             *  we can do this w/o harm
             */

            VelocityContext context = new VelocityContext(inner);

            context.put("name", "Velocity");

            try {
                /*
                 *  First, the reference insertion handler
                 */

                System.String s = "$name";

                System.IO.StringWriter w = new System.IO.StringWriter();
                Velocity.evaluate(context, w, "mystring", s);

                if (!w.ToString().Equals(REFERENCE_VALUE))
                {
                    fail("Reference insertion test 1");
                }

                /*
                 *  using the same handler, we can deal with
                 *  null references as well
                 */

                s = "$floobie";

                w = new System.IO.StringWriter();
                Velocity.evaluate(context, w, "mystring", s);

                if (!w.ToString().Equals(NO_REFERENCE_VALUE))
                {
                    fail("Reference insertion test 2");
                }

                /*
                 *  now lets test setting a null value - this test
                 *  should result in *no* log output.
                 */

                s         = "#set($settest = $NotAReference)";
                w         = new System.IO.StringWriter();
                logString = null;
                Velocity.evaluate(context, w, "mystring", s);

                if (logString != null)
                {
                    fail("NullSetEventHandler test 1");
                }

                /*
                 *  now lets test setting a null value - this test
                 *  should result in log output.
                 */

                s         = "#set($logthis = $NotAReference)";
                w         = new System.IO.StringWriter();
                logString = null;
                Velocity.evaluate(context, w, "mystring", s);

                if (logString == null)
                {
                    fail("NullSetEventHandler test 1");
                }

                /*
                 *  finally, we test a method exception event - we do this
                 *  by putting this class in the context, and calling
                 *  a method that does nothing but throw an exception.
                 *  we use a little switch to turn the event handling
                 *  on and off
                 *
                 *  Note also how the reference insertion process
                 *  happens as well
                 */

                exceptionSwitch = true;

                context.put("this", this);

                s = " $this.throwException()";
                w = new System.IO.StringWriter();

                try {
                    Velocity.evaluate(context, w, "mystring", s);
                } catch (MethodInvocationException mee) {
                    fail("MethodExceptionEvent test 1");
                } catch (System.Exception e) {
                    fail("MethodExceptionEvent test 1");
                }

                /*
                 *  now, we turn the switch off, and we can see that the
                 *  exception will propgate all the way up here, and
                 *  wil be caught by the catch() block below
                 */

                exceptionSwitch = false;

                s = " $this.throwException()";
                w = new System.IO.StringWriter();

                try {
                    Velocity.evaluate(context, w, "mystring", s);
                    fail("MethodExceptionEvent test 2");
                } catch (MethodInvocationException mee) {
                    /*
                     * correct - should land here...
                     */
                } catch (System.Exception e) {
                    fail("MethodExceptionEvent test 2");
                }
            } catch (ParseErrorException pee) {
                fail("ParseErrorException" + pee);
            } catch (MethodInvocationException mee) {
                fail("MethodInvocationException" + mee);
            } catch (System.Exception e) {
                fail("Exception" + e);
            }
        }
示例#25
0
        /// <summary>
        /// invokes the method.  Returns null if a problem, the
        /// actual return if the method returns something, or
        /// an empty string "" if the method returns void
        /// </summary>
        public override System.Object execute(System.Object o, InternalContextAdapter context)
        {
            /*
             *  new strategy (strategery!) for introspection. Since we want
             *  to be thread- as well as context-safe, we *must* do it now,
             *  at execution time.  There can be no in-node caching,
             *  but if we are careful, we can do it in the context.
             */

            MethodInfo   method   = null;
            PropertyInfo property = null;

            try {
                /*
                 *   check the cache
                 */

                IntrospectionCacheData icd = context.ICacheGet(this);
                System.Type            c   = o.GetType();

                /*
                 *  like ASTIdentifier, if we have cache information, and the
                 *  Class of Object o is the same as that in the cache, we are
                 *  safe.
                 */

                if (icd != null && icd.contextData == c)
                {
                    /*
                     * sadly, we do need recalc the values of the args, as this can
                     * change from visit to visit
                     */

                    for (int j = 0; j < paramCount; j++)
                    {
                        params_Renamed[j] = jjtGetChild(j + 1).value_Renamed(context);
                    }

                    /*
                     * and get the method from the cache
                     */
                    if (icd.thingy is MethodInfo)
                    {
                        method = (MethodInfo)icd.thingy;
                    }
                    if (icd.thingy is PropertyInfo)
                    {
                        property = (PropertyInfo)icd.thingy;
                    }
                }
                else
                {
                    /*
                     *  otherwise, do the introspection, and then
                     *  cache it
                     */

                    Object obj = doIntrospection(context, c);
                    if (obj is MethodInfo)
                    {
                        method = (MethodInfo)obj;
                    }
                    if (obj is PropertyInfo)
                    {
                        property = (PropertyInfo)obj;
                    }

                    if (obj != null)
                    {
                        icd             = new IntrospectionCacheData();
                        icd.contextData = c;
                        icd.thingy      = obj;
                        context.ICachePut(this, icd);
                    }
                }

                /*
                 *  if we still haven't gotten the method, either we are calling
                 *  a method that doesn't exist (which is fine...)  or I screwed
                 *  it up.
                 */

                if (method == null && property == null)
                {
                    return(null);
                }
            } catch (MethodInvocationException mie) {
                /*
                 *  this can come from the doIntrospection(), as the arg values
                 *  are evaluated to find the right method signature.  We just
                 *  want to propogate it here, not do anything fancy
                 */

                throw mie;
            } catch (System.Exception e) {
                /*
                 *  can come from the doIntropection() also, from Introspector
                 */

                rsvc.error("ASTMethod.execute() : exception from introspection : " + e);
                return(null);
            }

            try {
                /*
                 *  get the returned object.  It may be null, and that is
                 *  valid for something declared with a void return type.
                 *  Since the caller is expecting something to be returned,
                 *  as long as things are peachy, we can return an empty
                 *  String so ASTReference() correctly figures out that
                 *  all is well.
                 */

                Object obj = null;
                if (method != null)
                {
                    obj = method.Invoke(o, (System.Object[])params_Renamed);
                    if (obj == null && method.ReturnType == System.Type.GetType("System.Void"))
                    {
                        obj = String.Empty;
                    }
                }
                else
                {
                    obj = property.GetValue(o, null);
                }

                return(obj);
            } catch (System.Reflection.TargetInvocationException ite) {
                /*
                 *  In the event that the invocation of the method
                 *  itself throws an exception, we want to catch that
                 *  wrap it, and throw.  We don't log here as we want to figure
                 *  out which reference threw the exception, so do that
                 *  above
                 */

                EventCartridge ec = context.EventCartridge;

                /*
                 *  if we have an event cartridge, see if it wants to veto
                 *  also, let non-Exception Throwables go...
                 */

                if (ec != null && ite.GetBaseException() is System.Exception)
                {
                    try {
                        return(ec.methodException(o.GetType(), methodName, (System.Exception)ite.GetBaseException()));
                    } catch (System.Exception e) {
                        throw new MethodInvocationException("Invocation of method '" + methodName + "' in  " + o.GetType() + " threw exception " + e.GetType() + " : " + e.Message, e, methodName);
                    }
                }
                else
                {
                    /*
                     * no event cartridge to override. Just throw
                     */

                    throw new MethodInvocationException("Invocation of method '" + methodName + "' in  " + o.GetType() + " threw exception " + ite.GetBaseException().GetType() + " : " + ite.GetBaseException().Message, ite.GetBaseException(), methodName);
                }
            } catch (System.Exception e) {
                rsvc.error("ASTMethod.execute() : exception invoking method '" + methodName + "' in " + o.GetType() + " : " + e);
                return(null);
            }
        }
示例#26
0
        public Test(System.String templateFile, System.String encoding)
        {
            System.IO.StreamWriter writer   = null;
            TestProvider           provider = new TestProvider();
            ArrayList al = provider.Customers;

            System.Collections.Hashtable h = new System.Collections.Hashtable();

            /*
             *  put this in to test introspection $h.Bar or $h.get("Bar") etc
             */

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

            /*
             *  adding simple vector with strings for testing late introspection stuff
             */

            System.Collections.ArrayList v = new System.Collections.ArrayList();

            System.String str = "mystr";

            v.Add(new System.String("hello".ToCharArray()));
            v.Add(new System.String("hello2".ToCharArray()));
            v.Add(str);

            try {
                /*
                 *  this is another way to do properties when initializing Runtime.
                 *  make a Properties
                 */

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

                /*
                 *  now, if you want to, load it from a file (or whatever)
                 */

                try {
                    System.IO.FileStream fis = new System.IO.FileStream(new System.IO.FileInfo("velocity.properties").FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                    if (fis != null)
                    {
                        //UPGRADE_ISSUE: Method 'java.util.Properties.load' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javautilPropertiesload_javaioInputStream"'
                        p.load(fis);
                    }
                } catch (System.Exception ex) {
                    /* no worries. no file... */
                }

                /*
                 *  iterate out the properties
                 */

                System.Collections.Specialized.NameValueCollection temp_namedvaluecollection;
                temp_namedvaluecollection = System.Configuration.ConfigurationSettings.AppSettings;
                //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"'
                for (System.Collections.IEnumerator e = temp_namedvaluecollection.GetEnumerator(); e.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 el = (System.String)e.Current;

                    //UPGRADE_WARNING: method 'java.util.Properties.getProperty' was converted to ' ' which may throw an exception. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1101"'
                    Velocity.setProperty(el, (System.String)p.GetValue(el, System.Type.GetType("System.String")));
                }

                /*
                 *  add some individual properties if you wish
                 */


                Velocity.setProperty(Velocity.RUNTIME_LOG_ERROR_STACKTRACE, "true");
                Velocity.setProperty(Velocity.RUNTIME_LOG_WARN_STACKTRACE, "true");
                Velocity.setProperty(Velocity.RUNTIME_LOG_INFO_STACKTRACE, "true");

                /*
                 *  use an alternative logger.  Set it up here and pass it in.
                 */

                //            SimpleLogSystem sls = new SimpleLogSystem("velocity_simple.log");

                // Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, sls );

                /*
                 *  and now call init
                 */

                Velocity.init();

                /*
                 *  now, do what we want to do.  First, get the Template
                 */

                if (templateFile == null)
                {
                    templateFile = "examples/example.vm";
                }


                Template template = null;

                try
                {
                    template = RuntimeSingleton.getTemplate(templateFile, encoding)
                    ;
                }
                catch (ResourceNotFoundException rnfe) {
                    System.Console.Out.WriteLine("Test : RNFE : Cannot find template " + templateFile);
                } catch (ParseErrorException pee) {
                    System.Console.Out.WriteLine("Test : Syntax error in template " + templateFile + ":" + pee);
                }

                /*
                 * now, make a Context object and populate it.
                 */

                VelocityContext context = new VelocityContext();

                context.put("provider", provider);
                context.put("name", "jason");
                context.put("providers", provider.Customers2);
                context.put("list", al);
                context.put("hashtable", h);
                context.put("search", provider.Search);
                context.put("relatedSearches", provider.RelSearches);
                context.put("searchResults", provider.RelSearches);
                context.put("menu", provider.Menu);
                context.put("stringarray", provider.Array);
                context.put("vector", v);
                context.put("mystring", new System.String("".ToCharArray()));
                context.put("hashmap", new HashMap());
                context.put("runtime", new FieldMethodizer("org.apache.velocity.runtime.RuntimeSingleton"));
                context.put("fmprov", new FieldMethodizer(provider));
                context.put("Floog", "floogie woogie");
                context.put("geirstring", str);
                context.put("mylong", 5);

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

                int[] intarr = new int[] { 10, 20, 30, 40, 50 };

                System.Object[] oarr = new System.Object[] { "a", "b", "c", "d" };

                context.put("collection", v);
                context.put("iterator", v.iterator());
                context.put("map", h);
                context.put("obarr", oarr);
                context.put("intarr", intarr);

                System.String          stest = " My name is $name -> $Floog";
                System.IO.StringWriter w     = new System.IO.StringWriter();
                //            Velocity.evaluate( context, w, "evaltest",stest );
                //            System.out.println("Eval = " + w );

                w = new System.IO.StringWriter();
                //Velocity.mergeTemplate( "mergethis.vm",  context, w );
                //System.out.println("Merge = " + w );

                w = new System.IO.StringWriter();
                //Velocity.invokeVelocimacro( "floog", "test", new String[2],  context,  w );
                //System.out.println("Invoke = " + w );


                /*
                 *  event cartridge stuff
                 */

                EventCartridge ec = new EventCartridge();
                ec.addEventHandler(this);
                ec.attachToContext(context);

                /*
                 *  make a writer, and merge the template 'against' the context
                 */

                VelocityContext vc = new VelocityContext(context);

                if (template != null)
                {
                    //UPGRADE_ISSUE: Constructor 'java.io.BufferedWriter.BufferedWriter' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javaioBufferedWriterBufferedWriter_javaioWriter"'
                    writer = new BufferedWriter(new System.IO.StreamWriter(System.Console.Out));
                    template.merge(vc, writer);
                    writer.Flush();
                    writer.Close();
                }
            } catch (MethodInvocationException mie) {
                System.Console.Out.WriteLine("MIE : " + mie);
            } catch (System.Exception e) {
                RuntimeSingleton.error("Test- exception : " + e);
                SupportClass.WriteStackTrace(e, Console.Error);
            }
        }