public override bool Evaluate(IInternalContextAdapter context) { // get the two args Object left = GetChild(0).Value(context); Object right = GetChild(1).Value(context); // if either is null, lets log and bail if (left == null || right == null) { runtimeServices.Error( string.Format( "{0} side ({1}) of '>=' operation has null value. Operation not possible. {2} [line {3}, column {4}]", (left == null ? "Left" : "Right"), GetChild((left == null ? 0 : 1)).Literal, context.CurrentTemplateName, Line, Column)); return false; } try { return ObjectComparer.CompareObjects(left, right) >= 0; } catch(ArgumentException ae) { runtimeServices.Error(ae.Message); return false; } }
public override bool Render(IInternalContextAdapter context, TextWriter writer, INode node) { if (node.ChildrenCount != 2) { throw new MonoRailException("#capturefor directive expects an id attribute and a template block"); } var idNode = (ASTWord) node.GetChild(0); var bodyNode = (ASTBlock) node.GetChild(1); var id = idNode.Literal; var buffer = new StringWriter(); var sb = buffer.GetStringBuilder(); bodyNode.Render(context, buffer); var currentContent = context[id] as string; if( currentContent != null ) { sb.Append(currentContent); } context[id] = sb.ToString(); return true; }
/// <summary> /// Computes the value of the subtraction. /// Currently limited to integers. /// </summary> /// <returns>Integer(value) or null</returns> public override Object Value(IInternalContextAdapter context) { // get the two args Object left = GetChild(0).Value(context); Object right = GetChild(1).Value(context); // if either is null, lets log and bail if (left == null || right == null) { rsvc.Error((left == null ? "Left" : "Right") + " side (" + GetChild((left == null ? 0 : 1)).Literal + ") of subtraction operation has null value." + " Operation not possible. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return null; } Type maxType = MathUtil.ToMaxType(left.GetType(), right.GetType()); if (maxType == null) { return null; } return MathUtil.Sub(maxType, left, right); // if not an Integer, not much we can do either // if (!(left is Int32) || !(right is Int32)) // { // rsvc.Error((!(left is Int32) ? "Left" : "Right") + " side of subtraction operation is not a valid type. " + "Currently only integers (1,2,3...) and Integer type is supported. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); // // return null; // } // // return ((Int32) left) - ((Int32) right); }
/// <summary> /// Computes the sum of the two nodes. /// Currently only integer operations are supported. /// </summary> /// <returns>Integer object with value, or null</returns> public override Object Value(IInternalContextAdapter context) { // get the two addends Object left = GetChild(0).Value(context); Object right = GetChild(1).Value(context); // if either is null, lets log and bail if (left == null || right == null) { runtimeServices.Error( string.Format( "{0} side ({1}) of addition operation has null value. Operation not possible. {2} [line {3}, column {4}]", (left == null ? "Left" : "Right"), GetChild((left == null ? 0 : 1)).Literal, context.CurrentTemplateName, Line, Column)); return null; } Type maxType = MathUtil.ToMaxType(left.GetType(), right.GetType()); if (maxType == null) { return null; } return MathUtil.Add(maxType, left, right); // if not an Integer, not much we can do either // if (!(left is Int32) || !(right is Int32)) // { // runtimeServices.Error((!(left is Int32) ? "Left" : "Right") + " side of addition operation is not a valid type. " + "Currently only integers (1,2,3...) and Integer type is supported. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); // // return null; // } // return ((Int32) left) + ((Int32) right); }
public override bool Render(IInternalContextAdapter context, TextWriter writer) { // Check if the #if(expression) construct evaluates to true: // if so render and leave immediately because there // is nothing left to do! if (GetChild(0).Evaluate(context)) { GetChild(1).Render(context, writer); return true; } int totalNodes = ChildrenCount; // Now check the remaining nodes left in the // if construct. The nodes are either elseif // nodes or else nodes. Each of these node // types knows how to evaluate themselves. If // a node evaluates to true then the node will // render itself and this method will return // as there is nothing left to do. for(int i = 2; i < totalNodes; i++) { if (GetChild(i).Evaluate(context)) { GetChild(i).Render(context, writer); return true; } } // This is reached when an ASTIfStatement // consists of an if/elseif sequence where // none of the nodes evaluate to true. return true; }
/// <summary> /// Computes the result of the division. Currently limited to Integers. /// </summary> /// <returns>Integer(value) or null</returns> public override Object Value(IInternalContextAdapter context) { // get the two args Object left = GetChild(0).Value(context); Object right = GetChild(1).Value(context); // if either is null, lets log and bail if (left == null || right == null) { runtimeServices.Error( string.Format( "{0} side ({1}) of division operation has null value. Operation not possible. {2} [line {3}, column {4}]", (left == null ? "Left" : "Right"), GetChild((left == null ? 0 : 1)).Literal, context.CurrentTemplateName, Line, Column)); return null; } Type maxType = MathUtil.ToMaxType(left.GetType(), right.GetType()); if (maxType == null) { return null; } try { return MathUtil.Div(maxType, left, right); } catch (DivideByZeroException) { runtimeServices.Error("Right side of division operation is zero. Must be non-zero. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); } return null; }
public override bool Evaluate(IInternalContextAdapter context) { if (GetChild(0).Evaluate(context)) return false; else return true; }
public override bool Evaluate(IInternalContextAdapter context) { // get the two args Object left = GetChild(0).Value(context); Object right = GetChild(1).Value(context); // if either is null, lets log and bail if (left == null || right == null) { rsvc.Error((left == null ? "Left" : "Right") + " side (" + GetChild((left == null ? 0 : 1)).Literal + ") of '>' operation has null value." + " Operation not possible. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } try { return ObjectComparer.CompareObjects(left, right) == ObjectComparer.Greater; } catch(ArgumentException ae) { rsvc.Error(ae.Message); return false; } }
/// <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; }
public override Object Init(IInternalContextAdapter context, Object data) { Token t = FirstToken; text = NodeUtils.tokenLiteral(t); return data; }
/// <summary> /// How this directive is to be initialized. /// </summary> public virtual void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node) { runtimeServices = rs; // int i, k = node.jjtGetNumChildren(); // for (i = 0; i < k; i++) // node.jjtGetChild(i).init(context, rs); }
/// <summary> /// simple init - init our subtree and get what we can from /// the AST /// </summary> public override Object Init(IInternalContextAdapter context, Object data) { base.Init(context, data); methodName = FirstToken.Image; paramCount = ChildrenCount - 1; return data; }
/// <summary> /// simple init - don't do anything that is context specific. /// just get what we need from the AST, which is static. /// </summary> public override Object Init(IInternalContextAdapter context, Object data) { base.Init(context, data); identifier = FirstToken.Image; uberInfo = new Info(context.CurrentTemplateName, Line, Column); return data; }
public override bool Render(IInternalContextAdapter context, TextWriter writer) { int i, k = ChildrenCount; for(i = 0; i < k; i++) GetChild(i).Render(context, writer); return true; }
/// <summary> init : we don't have to do much. Init the tree (there /// shouldn't be one) and then see if interpolation is turned on. /// </summary> public override Object Init(IInternalContextAdapter context, Object data) { base.Init(context, data); /* * the stringlit is set at template parse time, so we can * do this here for now. if things change and we can somehow * create stringlits at runtime, this must * move to the runtime execution path * * so, only if interpolation is turned on AND it starts * with a " AND it has a directive or reference, then we * can interpolate. Otherwise, don't bother. */ interpolate = FirstToken.Image.StartsWith("\"") && ((FirstToken.Image.IndexOf('$') != - 1) || (FirstToken.Image.IndexOf('#') != - 1)); /* * get the contents of the string, minus the '/" at each end */ image = FirstToken.Image.Substring(1, (FirstToken.Image.Length - 1) - (1)); /* * tack a space on the end (dreaded <MORE> kludge) */ interpolateimage = image + " "; if (interpolate) { /* * now parse and init the nodeTree */ TextReader br = new StringReader(interpolateimage); /* * it's possible to not have an initialization context - or we don't * want to trust the caller - so have a fallback value if so * * Also, do *not* dump the VM namespace for this template */ nodeTree = rsvc.Parse(br, (context != null) ? context.CurrentTemplateName : "StringLiteral", false); /* * init with context. It won't modify anything */ nodeTree.Init(context, rsvc); } return data; }
public override Object Value(IInternalContextAdapter context) { int size = ChildrenCount; ArrayList objectArray = new ArrayList(size); for(int i = 0; i < size; i++) objectArray.Add(GetChild(i).Value(context)); return objectArray; }
/// <summary> Initialization method - doesn't do much but do the object /// creation. We only need to do it once. /// </summary> public override Object Init(IInternalContextAdapter context, Object data) { /* * init the tree correctly */ base.Init(context, data); valueField = Int32.Parse(FirstToken.Image); return data; }
/// <summary> /// simple init - init the tree and get the elementKey from /// the AST /// </summary> public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node) { base.Init(rs, context, node); // get the msg, and add the space so we don't have to // do it each time outputMsgStart = rsvc.GetString(RuntimeConstants.ERRORMSG_START); outputMsgStart = outputMsgStart + " "; outputMsgEnd = rsvc.GetString(RuntimeConstants.ERRORMSG_END); outputMsgEnd = " " + outputMsgEnd; }
/// <summary> /// iterates through the argument list and renders every /// argument that is appropriate. Any non appropriate /// arguments are logged, but render() continues. /// </summary> public override bool Render(IInternalContextAdapter context, TextWriter writer, INode node) { // did we get an argument? if (!AssertArgument(node)) { return false; } // does it have a value? If you have a null reference, then no. Object value; if (!AssertNodeHasValue(node, context, out value)) { return false; } // get the path String arg = value.ToString(); AssertTemplateStack(context); Resource current = context.CurrentResource; // get the resource, and assume that we use the encoding of the current template // the 'current resource' can be null if we are processing a stream.... String encoding; if (current == null) { encoding = (String) runtimeServices.GetProperty(RuntimeConstants.INPUT_ENCODING); } else { encoding = current.Encoding; } // now use the Runtime resource loader to get the template Template t = null; t = GetTemplate(arg, encoding, context); if (t == null) { return false; } // and render it if (!RenderTemplate(t, arg, writer, context)) { return false; } return true; }
/// <summary> /// does the real work. Creates an Vector of Integers with the /// right value range /// </summary> /// <param name="context">app context used if Left or Right of .. is a ref</param> /// <returns>Object array of Integers</returns> public override Object Value(IInternalContextAdapter context) { // get the two range ends Object left = GetChild(0).Value(context); Object right = GetChild(1).Value(context); // if either is null, lets log and bail if (left == null || right == null) { runtimeServices.Error( string.Format( "{0} side of range operator [n..m] has null value. Operation not possible. {1} [line {2}, column {3}]", (left == null ? "Left" : "Right"), context.CurrentTemplateName, Line, Column)); return null; } // if not an Integer, not much we can do either if (!(left is Int32) || !(right is Int32)) { runtimeServices.Error( string.Format( "{0} side of range operator is not a valid type. Currently only integers (1,2,3...) and Integer type is supported. {1} [line {2}, column {3}]", (!(left is Int32) ? "Left" : "Right"), context.CurrentTemplateName, Line, Column)); return null; } // get the two integer values of the ends of the range int l = ((Int32) left); int r = ((Int32) right); // find out how many there are int num = Math.Abs(l - r); num += 1; // see if your increment is Pos or Neg int delta = (l >= r) ? - 1 : 1; // make the vector and fill it ArrayList foo = new ArrayList(num); int val = l; for(int i = 0; i < num; i++) { foo.Add(val); val += delta; } return foo; }
public override bool Render(IInternalContextAdapter context, TextWriter writer) { // normal processing if (directive != null) { directive.Render(context, writer, this); } else { writer.Write("#"); writer.Write(directiveName); } return true; }
/// <summary> /// the logical or : /// the rule : /// left || null -> left /// null || right -> right /// null || null -> false /// left || right -> left || right /// </summary> public override bool Evaluate(IInternalContextAdapter context) { INode left = GetChild(0); INode right = GetChild(1); // if the left is not null and true, then true if (left != null && left.Evaluate(context)) return true; // same for right if (right != null && right.Evaluate(context)) return true; return false; }
/// <summary> /// Renders the macro using the context /// </summary> public override bool Render(IInternalContextAdapter context, TextWriter writer, INode node) { try { // it's possible the tree hasn't been parsed yet, so get // the VMManager to parse and init it if (nodeTree == null) { runtimeServices.Error(string.Format("VM error : {0}. Null AST", macroName)); } else { if (!init) { nodeTree.Init(context, runtimeServices); init = true; } // wrap the current context and add the VMProxyArg objects VMContext vmContext = new VMContext(context, runtimeServices); for(int i = 1; i < argArray.Length; i++) { // we can do this as VMProxyArgs don't change state. They change // the context. VMProxyArg arg = (VMProxyArg) proxyArgHash[argArray[i]]; vmContext.AddVMProxyArg(arg); } // now render the VM nodeTree.Render(vmContext, writer); } } catch(Exception e) { // if it's a MIE, it came from the render.... throw it... if (e is MethodInvocationException) { throw; } runtimeServices.Error(string.Format("VelocimacroProxy.render() : exception VM = #{0}() : {1}", macroName, e)); } return true; }
public override Object Init(IInternalContextAdapter context, Object data) { base.Init(context, data); if (directive == null && rsvc.IsVelocimacro(directiveName, context.CurrentTemplateName)) { directive = rsvc.GetVelocimacro(directiveName, context.CurrentTemplateName); } if (directive != null) { directive.Init(rsvc, context, this); directive.SetLocation(Line, Column); } return data; }
public override bool Render(IInternalContextAdapter context, TextWriter writer, INode node) { if(node.ChildrenCount == 2) { string lang = node.GetChild(0).Value(context) as string; var codeWriter = new StringWriter(); node.GetChild(1).Render(context, codeWriter); var code = codeWriter.ToString(); if(lang != null && !string.IsNullOrEmpty(code)) { var highlighter = new SyntaxHighlighter(); writer.WriteLine("<div class=\"syntax\"><div class=\"code\">"); writer.Write(highlighter.Highlight(code, lang)); writer.WriteLine("</div></div>"); } } return true; }
public override bool Evaluate(IInternalContextAdapter context) { Object left = GetChild(0).Value(context); Object right = GetChild(1).Value(context); try { return ObjectComparer.CompareObjects(left, right) != 0; } catch { // Ignore, we can't compare decently by value, but we honestly don't give a sh*t } // If we can't actually compare the objects, try the operator as fallback // For operator overloaded types, this will not really be a reference comp, but that's ok. return left != right; }
/// <summary> /// Evaluate the node. /// </summary> public override Object Value(IInternalContextAdapter context) { int size = ChildrenCount; IDictionary objectMap = new Hashtable(); for(int i = 0; i < size; i += 2) { SimpleNode keyNode = (SimpleNode) GetChild(i); SimpleNode valueNode = (SimpleNode) GetChild(i + 1); Object key = (keyNode == null ? null : keyNode.Value(context)); Object value = (valueNode == null ? null : valueNode.Value(context)); objectMap.Add(key, value); } return objectMap; }
/// <summary> /// logical and : /// null && right = false /// left && null = false /// null && null = false /// </summary> public override bool Evaluate(IInternalContextAdapter context) { INode left = GetChild(0); INode right = GetChild(1); // if either is null, lets log and bail if (left == null || right == null) { rsvc.Error((left == null ? "Left" : "Right") + " side of '&&' operation is null." + " Operation not possible. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } // short circuit the test. Don't eval the RHS if the LHS is false if (left.Evaluate(context)) if (right.Evaluate(context)) return true; return false; }
/// <summary> simple init. We can get the RHS and LHS as the the tree structure is static /// </summary> public override Object Init(IInternalContextAdapter context, Object data) { /* * init the tree correctly */ base.Init(context, data); right = RightHandSide; left = LeftHandSide; blather = runtimeServices.GetBoolean(RuntimeConstants.RUNTIME_LOG_REFERENCE_LOG_INVALID, true); /* * grab this now. No need to redo each time */ leftReference = left.FirstToken.Image.Substring(1); return(data); }
/// <summary> /// See if we have exceeded the configured depth. /// If it isn't configured, put a stop at 20 just in case. /// </summary> private bool AssertTemplateStack(IInternalContextAdapter context) { bool result = true; Object[] templateStack = context.TemplateNameStack; if (templateStack.Length >= runtimeServices.GetInt(RuntimeConstants.PARSE_DIRECTIVE_MAXDEPTH, 20)) { StringBuilder path = new StringBuilder(); for (int i = 0; i < templateStack.Length; ++i) { path.AppendFormat(" > {0}", (object[])templateStack[i]); } runtimeServices.Error(string.Format("Max recursion depth reached ({0}) File stack:{1}", templateStack.Length, path)); result = false; } return(result); }
/// <summary> simple init. We can get the RHS and LHS as the the tree structure is static /// </summary> public override Object Init(IInternalContextAdapter context, Object data) { /* * init the tree correctly */ base.Init(context, data); right = RightHandSide; left = LeftHandSide; blather = rsvc.GetBoolean(RuntimeConstants.RUNTIME_LOG_REFERENCE_LOG_INVALID, true); /* * grab this now. No need to redo each time */ leftReference = left.FirstToken.Image.Substring(1); return data; }
/// <summary> /// logical and : /// null && right = false /// left && null = false /// null && null = false /// </summary> public override bool Evaluate(IInternalContextAdapter context) { INode left = GetChild(0); INode right = GetChild(1); // if either is null, lets log and bail if (left == null || right == null) { runtimeServices.Error( string.Format("{0} side of '&&' operation is null. Operation not possible. {1} [line {2}, column {3}]", (left == null ? "Left" : "Right"), context.CurrentTemplateName, Line, Column)); return false; } // short circuit the test. Don't eval the RHS if the LHS is false if (left.Evaluate(context)) if (right.Evaluate(context)) return true; return false; }
/// <seealso cref="NVelocity.Runtime.Paser.Node.SimpleNode.render(org.apache.velocity.context.InternalContextAdapter, java.io.Writer)"> /// </seealso> public override bool Render(IInternalContextAdapter context, System.IO.TextWriter writer) { /* * normal processing */ if (isDirective) { directive.Render(context, writer, this); } else { if (context.AllowRendering) { writer.Write("#"); writer.Write(directiveName); } } return(true); }
/// <summary> /// /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <param name="context"></param> /// <returns></returns> protected internal override object HandleSpecial(object left, object right, IInternalContextAdapter context) { /* * shall we try for strings? */ if (left is string || right is string) { if (left == null) { left = GetChild(0).Literal; } else if (right == null) { right = GetChild(1).Literal; } return(string.Concat(left.ToString(), right.ToString())); } return(null); }
/// <summary> simple Init - Init our subtree and Get what we can from /// the AST /// </summary> /// <param name="context"> /// </param> /// <param name="data"> /// </param> /// <returns> The Init result /// </returns> /// <throws> TemplateInitException </throws> public override object Init(IInternalContextAdapter context, object data) { base.Init(context, data); /* * make an uberinfo - saves new's later on */ uberInfo = new Info(TemplateName, Line, Column); /* * this is about all we can do */ methodName = FirstToken.Image; paramCount = GetNumChildren() - 1; strictRef = rsvc.GetBoolean(NVelocity.Runtime.RuntimeConstants.RUNTIME_REFERENCES_STRICT, false); return(data); }
/// <seealso cref="NVelocity.Runtime.Paser.Node.SimpleNode.render(org.apache.velocity.context.InternalContextAdapter, java.io.Writer)"> /// </seealso> public override bool Render(IInternalContextAdapter context, System.IO.TextWriter writer) { /* * Check if the #if(expression) construct evaluates to true: * if so render and leave immediately because there * is nothing left to do! */ if (GetChild(0).Evaluate(context)) { GetChild(1).Render(context, writer); return(true); } int totalNodes = GetNumChildren(); /* * Now check the remaining nodes left in the * if construct. The nodes are either elseif * nodes or else nodes. Each of these node * types knows how to Evaluate themselves. If * a node evaluates to true then the node will * render itself and this method will return * as there is nothing left to do. */ for (int i = 2; i < totalNodes; i++) { if (GetChild(i).Evaluate(context)) { GetChild(i).Render(context, writer); return(true); } } /* * This is reached when an ASTIfStatement * consists of an if/elseif sequence where * none of the nodes Evaluate to true. */ return(true); }
private object HandleInvocationException(object o, IInternalContextAdapter context, System.Exception t) { /* * 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 */ /* * let non-Exception Throwables go... */ if (t is System.Exception) { try { return(EventHandlerUtil.MethodException(rsvc, context, o.GetType(), methodName, (System.Exception)t)); } /** * If the event handler throws an exception, then wrap it * in a MethodInvocationException. Don't pass through RuntimeExceptions like other * similar catchall code blocks. */ catch (System.Exception e) { throw new MethodInvocationException("Invocation of method '" + methodName + "' in " + o.GetType() + " threw exception " + e.ToString(), e, methodName, TemplateName, this.Line, this.Column); } } else { /* * no event cartridge to override. Just throw */ throw new MethodInvocationException("Invocation of method '" + methodName + "' in " + o.GetType() + " threw exception " + t.ToString(), t, methodName, TemplateName, this.Line, this.Column); } }
/// <summary> /// Processes the first param. /// first param can either be the literal string 'with' which means the user /// is using the syntax #blockcomponent(ComponentName with "param1=value1" "param2=value2") /// or it could be a dictionary string like: /// #blockcomponent(ComponentName "%{ param1='value1', param2='value2' }") /// or it could be reference to a IDictionary like: /// #blockcomponent(ComponentName $dictionaryParam) /// anything different than that will throw an exception /// </summary> /// <param name="node">The node.</param> /// <param name="context">The context.</param> /// <param name="childrenCount">The children count.</param> /// <returns></returns> private IDictionary ProcessFirstParam(INode node, IInternalContextAdapter context, int childrenCount) { var compNameNode = node.GetChild(0); var componentName = compNameNode.FirstToken.Image; var withNode = node.GetChild(1); var withName = withNode.FirstToken.Image; if (!"with".Equals(withName)) { var nodeValue = withNode.Value(context); if (nodeValue == null) { return(null); } var dict = nodeValue as IDictionary; if (dict != null) { if (childrenCount > 2) { var message = String.Format("A #{0} directive with a dictionary " + "string parameter cannot have extra params - component {0}", componentName); throw new ViewComponentException(message); } return(dict); } else { var message = String.Format("A #{0} directive with parameters must use " + "the keyword 'with' - component {0}", componentName); throw new ViewComponentException(message); } } return(null); }
/// <summary></summary> public override bool Render(IInternalContextAdapter context, TextWriter writer, INode node) { string text = node.GetChild(0).Literal; string[] args = text.Substring(1, text.Length - 2).Split(','); string[] keys = args[0].Split('.'); StringCase stringCase = StringCase.Default; if (args.Length == 2) { stringCase = (StringCase)Enum.Parse(typeof(StringCase), args[1]); } if (keys[0] == "Strings") { if (keys.Length == 2) { writer.Write(I18n.Strings[keys[1], stringCase]); } else if (keys.Length == 3) { writer.Write(I18n.Strings[keys[1], keys[2], stringCase]); } } else if (keys[0] == "Translates") { if (keys.Length == 2) { writer.Write(I18n.Translates[keys[1], stringCase]); } else if (keys.Length == 3) { writer.Write(I18n.Translates[keys[1], keys[2], stringCase]); } } return(true); }
private void ProcessDictEntry(HybridDictionary map, StringBuilder keyBuilder, object value, IInternalContextAdapter context) { object key = keyBuilder.ToString().Trim(); if (key.ToString().StartsWith("$")) { object keyVal = EvaluateInPlace(key.ToString(), context); if (keyVal == null) { throw new ArgumentException( string.Format("The dictionary entry {0} evaluated to null, but null is not a valid dictionary key", key)); } key = keyVal; } map[key] = value; keyBuilder.Length = 0; }
/// <summary> renders the value of the string literal /// If the properties allow, and the string literal contains a $ or a # /// the literal is rendered against the context /// Otherwise, the stringlit is returned. /// </summary> public override Object Value(IInternalContextAdapter context) { string result = image; if (IsDictionaryString(result)) { return(InterpolateDictionaryString(result, context)); } else { if (interpolate) { try { TextWriter writer = new StringWriter(); nodeTree.Render(context, writer); /* * and return the result as a String */ String ret = writer.ToString(); /* * remove the space from the end (dreaded <MORE> kludge) */ result = ret.Substring(0, (ret.Length - 1) - (0)); } catch (System.Exception e) { runtimeServices.Error(string.Format("Error in interpolating string literal : {0}", e)); result = image; } } return(result); } }
public override bool Render(IInternalContextAdapter context, TextWriter writer, INode node) { int childrenCount = node.ChildrenCount; for (int i = 0; i < childrenCount; i++) { INode child = node.GetChild(i); if (child.Type == 6 || child.Type == 14) { if (!this.RenderOutput(child, context, writer)) { this.OutputErrorToStream(writer, "error with arg " + i + " please see log."); } } else { this.rsvc.Error("#include() error : invalid argument type : " + child.ToString()); this.OutputErrorToStream(writer, "error with arg " + i + " please see log."); } } return(true); }
/// <seealso cref="org.apache.velocity.runtime.parser.node.SimpleNode.evaluate(org.apache.velocity.context.InternalContextAdapter)"> /// </seealso> public override bool Evaluate(IInternalContextAdapter context) { /* * get the two args */ object left = GetChild(0).Value(context); object right = GetChild(1).Value(context); /* * if either is null, lets log and bail */ if (left == null || right == null) { System.String msg = (left == null ? "Left" : "Right") + " side (" + GetChild((left == null ? 0 : 1)).Literal + ") of '>=' operation has null value at " + Log.FormatFileString(this); if (rsvc.GetBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false)) { throw new VelocityException(msg); } log.Error(msg); return(false); } try { return(ObjectComparer.CompareObjects(left, right) >= 0); } catch (ArgumentException ae) { log.Error(ae.Message); return(false); } }
/// <summary> </summary> public virtual bool Render(IInternalContextAdapter context, System.IO.TextWriter writer) { try { depth++; if (depth > parent.maxDepth) { /* this is only a Debug message, as recursion can * happen in quasi-innocent situations and is relatively * harmless due to how we handle it here. * this is more to help anyone nuts enough to intentionally * use recursive block definitions and having problems * pulling it off properly. */ parent.log.Debug("Max recursion depth reached for " + parent.Id(context)); depth--; return(false); } else { parent.block.Render(context, writer); depth--; return(true); } } catch (System.IO.IOException e) { string msg = "Failed to render " + parent.Id(context) + " to writer"; parent.log.Error(msg, e); throw new RuntimeException(msg, e); } catch (VelocityException ve) { string msg = "Failed to render " + parent.Id(context) + " due to " + ve; parent.log.Error(msg, ve); throw ve; } }
/// <summary> simple Init. We can Get the RHS and LHS as the the tree structure is static</summary> /// <param name="context"> /// </param> /// <param name="data"> /// </param> /// <returns> Init result. /// </returns> public override object Init(IInternalContextAdapter context, object data) { lock (this) { /** This method is synchronized to prevent double initialization or initialization while rendering **/ if (!isInitialized) { /* * Init the tree correctly */ base.Init(context, data); uberInfo = new Info(TemplateName, Line, Column); right = RightHandSide; left = LeftHandSide; logOnNull = rsvc.GetBoolean(NVelocity.Runtime.RuntimeConstants.RUNTIME_LOG_REFERENCE_LOG_INVALID, true); allowNull = rsvc.GetBoolean(NVelocity.Runtime.RuntimeConstants.SET_NULL_ALLOWED, false); strictRef = rsvc.GetBoolean(NVelocity.Runtime.RuntimeConstants.RUNTIME_REFERENCES_STRICT, false); if (strictRef) { allowNull = true; // strictRef implies allowNull } /* * grab this now. No need to redo each time */ leftReference = left.FirstToken.Image.Substring(1); isInitialized = true; } return(data); } }
/// <summary> /// Calculates the value of the logical expression /// /// arg1 == arg2 /// /// All class types are supported. Uses equals() to /// determine equivalence. This should work as we represent /// with the types we already support, and anything else that /// implements equals() to mean more than identical references. /// </summary> /// <param name="context"> internal context used to evaluate the LHS and RHS </param> /// <returns> /// true if equivalent, false if not equivalent, /// false if not compatible arguments, or false /// if either LHS or RHS is null /// </returns> public override bool Evaluate(IInternalContextAdapter context) { Object left = GetChild(0).Value(context); Object right = GetChild(1).Value(context); // for equality, they are allowed to be null references try { if (ObjectComparer.CompareObjects(left, right) == 0) { return(true); } } catch { // Ignore, we can't compare decently by value, but we honestly don't give a sh*t } // They are not equal by value, try a reference comparison // reference equal => definitely equal objects ;) // For operator overloaded types, this will not really be a reference comp, but that's ok. return(left == right); }
private bool AssertTemplateStack(IInternalContextAdapter context) { bool result = true; object[] templateNameStack = context.TemplateNameStack; if (templateNameStack.Length >= this.rsvc.GetInt("directive.parse.max.depth", 20)) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < templateNameStack.Length; i++) { stringBuilder.Append(" > " + templateNameStack[i]); } this.rsvc.Error(string.Concat(new object[] { "Max recursion depth reached (", templateNameStack.Length, ") File stack:", stringBuilder })); result = false; } return(result); }
public override bool Evaluate(IInternalContextAdapter context) { object obj = base.GetChild(0).Value(context); object obj2 = base.GetChild(1).Value(context); bool result; if (obj == null || obj2 == null) { this.rsvc.Error(string.Concat(new object[] { (obj == null) ? "Left" : "Right", " side (", base.GetChild((obj == null) ? 0 : 1).Literal, ") of '>=' operation has null value. Operation not possible. ", context.CurrentTemplateName, " [line ", base.Line, ", column ", base.Column, "]" })); result = false; } else { try { result = (ObjectComparer.CompareObjects(obj, obj2) >= 0); } catch (ArgumentException ex) { this.rsvc.Error(ex.Message); result = false; } } return(result); }
public override object Value(IInternalContextAdapter context) { object obj = base.GetChild(0).Value(context); object obj2 = base.GetChild(1).Value(context); object result; if (obj == null || obj2 == null) { this.rsvc.Error(string.Concat(new object[] { (obj == null) ? "Left" : "Right", " side (", base.GetChild((obj == null) ? 0 : 1).Literal, ") of subtraction operation has null value. Operation not possible. ", context.CurrentTemplateName, " [line ", base.Line, ", column ", base.Column, "]" })); result = null; } else { Type type = MathUtil.ToMaxType(obj.GetType(), obj2.GetType()); if (type == null) { result = null; } else { result = MathUtil.Sub(type, obj, obj2); } } return(result); }
private object Evaluate(SimpleNode inlineNode, IInternalContextAdapter context) { var values = new ArrayList(); for (var i = 0; i < inlineNode.ChildrenCount; i++) { var node = inlineNode.GetChild(i); if (node.Type == ParserTreeConstants.TEXT) { values.Add(((ASTText)node).Text); } else { values.Add(node.Value(context)); } } if (values.Count == 0) { return(null); } else if (values.Count == 1) { return(values[0]); } else { var sb = new StringBuilder(); foreach (var value in values) { sb.Append(value); } return(sb.ToString()); } }
public virtual Object Init(IInternalContextAdapter context, Object data) { /* * hold onto the RuntimeServices */ runtimeServices = (IRuntimeServices)data; int i, k = ChildrenCount; for (i = 0; i < k; i++) { try { GetChild(i).Init(context, data); } catch (ReferenceException re) { runtimeServices.Error(re); } } return(data); }
/// <summary> Called when a method exception is generated during Velocity merge. Only /// the first valid event handler in the sequence is called. The default /// implementation simply rethrows the exception. /// /// </summary> /// <param name="claz">Class that is causing the exception /// </param> /// <param name="method">method called that causes the exception /// </param> /// <param name="e">Exception thrown by the method /// </param> /// <param name="rsvc">current instance of RuntimeServices /// </param> /// <param name="context">The internal context adapter. /// </param> /// <returns> Object to return as method result /// </returns> /// <throws> Exception </throws> /// <summary> to be wrapped and propogated to app /// </summary> public static object MethodException(IRuntimeServices rsvc, IInternalContextAdapter context, System.Type claz, string method, System.Exception e) { // app level cartridges have already been initialized EventCartridge ev1 = rsvc.ApplicationEventCartridge; System.Collections.IEnumerator applicationEventHandlerIterator = (ev1 == null) ? null : ev1.MethodExceptionEventHandlers; EventCartridge ev2 = context.EventCartridge; InitializeEventCartridge(rsvc, ev2); System.Collections.IEnumerator contextEventHandlerIterator = (ev2 == null) ? null : ev2.MethodExceptionEventHandlers; IEventHandlerMethodExecutor methodExecutor = new NVelocity.App.Event.MethodExceptionExecutor(context, claz, method, e); if (((applicationEventHandlerIterator == null) || !applicationEventHandlerIterator.MoveNext()) && ((contextEventHandlerIterator == null) || !contextEventHandlerIterator.MoveNext())) { throw e; } CallEventHandlers(applicationEventHandlerIterator, contextEventHandlerIterator, methodExecutor); return(methodExecutor.ReturnValue); }
/// <summary> /// Computes the product of the two args. /// Returns null if either arg is null /// or if either arg is not an integer /// </summary> public override Object Value(IInternalContextAdapter context) { // get the two args Object left = GetChild(0).Value(context); Object right = GetChild(1).Value(context); // if either is null, lets log and bail if (left == null || right == null) { runtimeServices.Error( string.Format( "{0} side ({1}) of multiplication operation has null value. Operation not possible. {2} [line {3}, column {4}]", (left == null ? "Left" : "Right"), GetChild((left == null ? 0 : 1)).Literal, context.CurrentTemplateName, Line, Column)); return(null); } Type maxType = MathUtil.ToMaxType(left.GetType(), right.GetType()); if (maxType == null) { return(null); } return(MathUtil.Mult(maxType, left, right)); // if not an Integer, not much we can do either // if (!(left is Int32) || !(right is Int32)) // { // runtimeServices.Error((!(left is Int32) ? "Left" : "Right") + " side of multiplication operation is not a valid type. " + "Currently only integers (1,2,3...) and Integer type is supported. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); // // return null; // } // // return ((Int32) left)*((Int32) right); }
/// <summary> /// The major meat of VelocimacroProxy, init() checks the # of arguments, /// patches the macro body, renders the macro into an AST, and then initiates /// the AST, so it is ready for quick rendering. Note that this is only /// AST dependant stuff. Not context. /// </summary> public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node) { base.Init(rs, context, node); // how many args did we get? int i = node.ChildrenCount; // right number of args? if (NumArgs != i) { runtimeServices.Error( string.Format("VM #{0}: error : too {1} arguments to macro. Wanted {2} got {3}", macroName, ((NumArgs > i) ? "few" : "many"), NumArgs, i)); return; } // get the argument list to the instance use of the VM callingArgs = getArgArray(node); // now proxy each arg in the context setupMacro(callingArgs, callingArgTypes); return; }
/// <summary> Velocimacro implementation is not known at the Init time. So look for /// a implementation in the macro libaries and if finds one renders it. The /// parameters rendering is delegated to the VelocimacroProxy object. When /// looking for a macro we first loot at the template with has the /// macro call then we look at the macro lbraries in the order they appear /// in the list. If a macro has many definitions above look up will /// determine the precedence. /// /// </summary> /// <param name="context"> /// </param> /// <param name="writer"> /// </param> /// <param name="node"> /// </param> /// <returns> true if the rendering is successfull /// </returns> /// <throws> IOException </throws> /// <throws> ResourceNotFoundException </throws> /// <throws> ParseErrorException </throws> /// <throws> MethodInvocationException </throws> public override bool Render(IInternalContextAdapter context, System.IO.TextWriter writer, INode node) { VelocimacroProxy vmProxy = null; string renderingTemplate = context.CurrentTemplateName; /** * first look in the source template */ object o = rsvc.GetVelocimacro(macroName, sourceTemplate, renderingTemplate); if (o != null) { // getVelocimacro can only return a VelocimacroProxy so we don't need the // costly instanceof check vmProxy = (VelocimacroProxy)o; } /** * if not found, look in the macro libraries. */ if (vmProxy == null) { System.Collections.IList macroLibraries = context.MacroLibraries; if (macroLibraries != null) { for (int i = macroLibraries.Count - 1; i >= 0; i--) { o = rsvc.GetVelocimacro(macroName, (string)macroLibraries[i], renderingTemplate); // Get the first matching macro if (o != null) { vmProxy = (VelocimacroProxy)o; break; } } } } if (vmProxy != null) { try { // mainly check the number of arguments vmProxy.Init(rsvc, context, node); } catch (TemplateInitException die) { Info info = new Info(sourceTemplate, node.Line, node.Column); throw new ParseErrorException(die.Message + " at " + Log.Log.FormatFileString(info), info); } try { return(vmProxy.Render(context, writer, node)); } catch (System.IO.IOException e) { rsvc.Log.Error("Exception in macro #" + macroName + " at " + Log.Log.FormatFileString(sourceTemplate, Line, Column)); throw e; } catch (System.SystemException e) { /** * We catch, the exception here so that we can record in * the logs the template and line number of the macro call * which generate the exception. This information is * especially important for multiple macro call levels. * this is also true for the following catch blocks. */ rsvc.Log.Error("Exception in macro #" + macroName + " at " + Log.Log.FormatFileString(sourceTemplate, Line, Column)); throw e; } } else if (strictRef) { Info info = new Info(sourceTemplate, node.Line, node.Column); throw new ParseErrorException("Macro '#" + macroName + "' is not defined at " + Log.Log.FormatFileString(info), info); } /** * If we cannot find an implementation write the literal text */ writer.Write(Literal); return(true); }
public virtual Object Execute(Object o, IInternalContextAdapter context) { return(null); }
public virtual Object Value(IInternalContextAdapter context) { return(null); }
public virtual bool Evaluate(IInternalContextAdapter context) { return(false); }
public override Object Value(IInternalContextAdapter context) { return(GetChild(0).Value(context)); }
public override bool Evaluate(IInternalContextAdapter context) { return(GetChild(0).Evaluate(context)); }