org.apache.velocity.runtime.parser.node.Node Java Examples

The following examples show how to use org.apache.velocity.runtime.parser.node.Node. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: For.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node)
  throws IOException
{
  Object c = context.get(counterName);
  context.put(counterName, counterInitialValue);
  try
  {
    return super.render(context, writer, node);
  }
  finally
  {
    if (c != null)
    {
      context.put(counterName, c);
    }
    else
    {
      context.remove(counterName);
    }
  }
}
 
Example #2
Source File: Break.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * This directive throws a StopCommand which signals either
 * the nearest Scope or the specified scope to stop rendering
 * its content.
 * @return never, always throws a StopCommand or Exception
 */
public boolean render(InternalContextAdapter context, Writer writer, Node node)
{
    if (!scoped)
    {
        throw new StopCommand();
    }

    Object argument = node.jjtGetChild(0).value(context);
    if (argument instanceof Scope)
    {
        ((Scope)argument).stop();
        throw new IllegalStateException("Scope.stop() failed to throw a StopCommand");
    }
    else
    {
        throw new VelocityException(node.jjtGetChild(0).literal()+
            " is not a valid " + Scope.class.getName() + " instance at "
            + StringUtils.formatFileString(this),
            null,
            rsvc.getLogContext().getStackTrace());
    }
}
 
Example #3
Source File: HtmlCompressorDirective.java    From htmlcompressor with Apache License 2.0 6 votes vote down vote up
public boolean render(InternalContextAdapter context, Writer writer, Node node) 
  		throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
  	
  	//render content
  	StringWriter content = new StringWriter();
node.jjtGetChild(0).render(context, content);

//compress
try {
	writer.write(htmlCompressor.compress(content.toString()));
} catch (Exception e) {
	writer.write(content.toString());
	String msg = "Failed to compress content: "+content.toString();
          log.error(msg, e);
          throw new RuntimeException(msg, e);
          
}
return true;
  	
  }
 
Example #4
Source File: JspUtilsTest.java    From velocity-tools with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspUtils#executeTag(org.apache.velocity.context.InternalContextAdapter, org.apache.velocity.runtime.parser.node.Node, javax.servlet.jsp.PageContext, javax.servlet.jsp.tagext.Tag)}.
 * @throws JspException If something goes wrong.
 * @throws IOException If something goes wrong.
 * @throws ParseErrorException If something goes wrong.
 * @throws ResourceNotFoundException If something goes wrong.
 * @throws MethodInvocationException If something goes wrong.
 */
@Test
public void testExecuteTag() throws JspException, MethodInvocationException, ResourceNotFoundException, ParseErrorException, IOException
{
    InternalContextAdapter context = createMock(InternalContextAdapter.class);
    Node node = createMock(Node.class);
    PageContext pageContext = createMock(PageContext.class);
    BodyTag tag = createMock(BodyTag.class);
    ASTBlock block = createMock(ASTBlock.class);
    JspWriter writer = createMock(JspWriter.class);

    expect(tag.doStartTag()).andReturn(BodyTag.EVAL_BODY_BUFFERED);
    tag.setBodyContent(isA(VelocityBodyContent.class));
    tag.doInitBody();
    expect(node.jjtGetChild(1)).andReturn(block);
    expect(tag.doAfterBody()).andReturn(BodyTag.SKIP_BODY);
    expect(tag.doEndTag()).andReturn(BodyTag.EVAL_PAGE);
    expect(pageContext.getOut()).andReturn(writer);
    expect(block.render(eq(context), isA(StringWriter.class))).andReturn(true);

    replay(context, node, pageContext, block, tag, writer);
    JspUtils.executeTag(context, node, pageContext, tag);
    verify(context, node, pageContext, block, tag, writer);
}
 
Example #5
Source File: JspUtilsTest.java    From velocity-tools with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspUtils#executeSimpleTag(org.apache.velocity.context.InternalContextAdapter, org.apache.velocity.runtime.parser.node.Node, javax.servlet.jsp.PageContext, javax.servlet.jsp.tagext.SimpleTag)}.
 * @throws IOException If something goes wrong.
 * @throws JspException If something goes wrong.
 */
@Test
public void testExecuteSimpleTag() throws JspException, IOException
{
    InternalContextAdapter context = createMock(InternalContextAdapter.class);
    Node node = createMock(Node.class);
    PageContext pageContext = createMock(PageContext.class);
    SimpleTag tag = createMock(SimpleTag.class);
    ASTBlock block = createMock(ASTBlock.class);

    tag.setJspBody(isA(VelocityJspFragment.class));
    expect(node.jjtGetChild(1)).andReturn(block);
    tag.doTag();

    replay(context, node, pageContext, block, tag);
    JspUtils.executeSimpleTag(context, node, pageContext, tag);
    verify(context, node, pageContext, block, tag);
}
 
Example #6
Source File: XmlCompressorDirective.java    From htmlcompressor with Apache License 2.0 6 votes vote down vote up
public boolean render(InternalContextAdapter context, Writer writer, Node node) 
  		throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
  	
  	//render content
  	StringWriter content = new StringWriter();
node.jjtGetChild(0).render(context, content);

//compress
try {
	writer.write(xmlCompressor.compress(content.toString()));
} catch (Exception e) {
	writer.write(content.toString());
	String msg = "Failed to compress content: "+content.toString();
          log.error(msg, e);
          throw new RuntimeException(msg, e);
          
}
return true;
  	
  }
 
Example #7
Source File: BlockMacro.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the directive.
 *
 * @param rs
 * @param macroName
 * @param context
 * @param node
 * @throws TemplateInitException
 */
public void init(RuntimeServices rs, String macroName, InternalContextAdapter context, Node node)
    throws TemplateInitException
{
    this.name = macroName;

    super.init(rs, context, node);

    // get name of the reference that refers to AST block passed to block macro call
    key = rsvc.getString(RuntimeConstants.VM_BODY_REFERENCE, "bodyContent");

    // use the macro max depth for bodyContent max depth as well
    maxDepth = rsvc.getInt(RuntimeConstants.VM_MAX_DEPTH);

    macro = new RuntimeMacro();
    macro.setLocation(getLine(), getColumn(), getTemplate());
    macro.init(rsvc, name, context, node);
}
 
Example #8
Source File: VelocimacroManager.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
private MacroEntry(final String vmName, final Node macro,
           List<Macro.MacroArg> macroArgs, final String sourceTemplate,
           RuntimeServices rsvc)
{
    this.vmName = vmName;
    this.macroArgs = macroArgs;
    this.nodeTree = (SimpleNode)macro;
    this.sourceTemplate = sourceTemplate;

    vp = new VelocimacroProxy();
    vp.init(rsvc);
    vp.setName(this.vmName);
    vp.setMacroArgs(this.macroArgs);
    vp.setNodeTree(this.nodeTree);
    vp.setLocation(macro.getLine(), macro.getColumn(), macro.getTemplate());
}
 
Example #9
Source File: VelocimacroProxy.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether the number of arguments given matches the number defined.
 * @param node
 * @param callArgNum
 */
protected void checkArgumentCount(Node node, int callArgNum)
{
    // Check if we have more calling arguments then the macro accepts
    if (callArgNum > macroArgs.size() - 1)
    {
        if (strictArguments)
        {
            throw new VelocityException("Provided " + callArgNum + " arguments but macro #"
                + macroArgs.get(0).name + " accepts at most " + (macroArgs.size()-1)
                + " at " + StringUtils.formatFileString(node), null, rsvc.getLogContext().getStackTrace());
        }
        // Backward compatibility logging, Mainly for MacroForwardDefinedTestCase
        log.debug("VM #{}: too many arguments to macro. Wanted {} got {}",
                  macroArgs.get(0).name, macroArgs.size() - 1, callArgNum);
    }
}
 
Example #10
Source File: Split.java    From CodeGen with MIT License 6 votes vote down vote up
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
    String value = (String) node.jjtGetChild(0).value(context);
    String character = (String) node.jjtGetChild(1).value(context);
    int len = value.length();
    StringBuilder sb = new StringBuilder(len);
    sb.append(value.charAt(0));
    for (int i = 1; i < len; i++) {
        char c = value.charAt(i);
        if (Character.isUpperCase(c)) {
            sb.append(character).append(Character.toLowerCase(c));
        } else {
            sb.append(c);
        }
    }
    writer.write(sb.toString());
    return true;
}
 
Example #11
Source File: Include.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 *  simple init - init the tree and get the elementKey from
 *  the AST
 * @param rs
 * @param context
 * @param node
 * @throws TemplateInitException
 */
public void init(RuntimeServices rs, InternalContextAdapter context,
                 Node node)
    throws TemplateInitException
{
    super.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;
}
 
Example #12
Source File: Parse.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Init's the #parse directive.
 * @param rs
 * @param context
 * @param node
 * @throws TemplateInitException
 */
public void init(RuntimeServices rs, InternalContextAdapter context, Node node)
    throws TemplateInitException
{
    super.init(rs, context, node);

    this.maxDepth = rsvc.getInt(RuntimeConstants.PARSE_DIRECTIVE_MAXDEPTH, 10);

    strictRef = rsvc.getBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false);
}
 
Example #13
Source File: ClassDirective.java    From sundrio with Apache License 2.0 5 votes vote down vote up
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException {
    String block = "";
    TypeDef clazz = null;
    for (int i = 0; i < node.jjtGetNumChildren(); i++) {
        if (node.jjtGetChild(i) != null) {
            if (!(node.jjtGetChild(i) instanceof ASTBlock)) {
                //reading and casting inline parameters
                if (i == 0) {
                    clazz = (TypeDef) node.jjtGetChild(i).value(context);
                } else {
                    break;
                }
            } else {
                //reading block content and rendering it
                try {
                    StringWriter blockContent = new StringWriter();
                    node.jjtGetChild(i).render(context, blockContent);

                    block = blockContent.toString();
                } catch (Exception e)  {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
    writeClazz(writer, clazz, block);
    return true;
}
 
Example #14
Source File: JspUtils.java    From velocity-tools with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a {@link Tag}.
 *
 * @param context The directive context.
 * @param node The main node of the directive.
 * @param pageContext The page context.
 * @param tag The tag to execute.
 * @throws JspException If something goes wrong.
 */
public static void executeTag(InternalContextAdapter context, Node node,
        PageContext pageContext, Tag tag) throws JspException
{
    int result = tag.doStartTag();
    if (tag instanceof BodyTag)
    {
        BodyTag bodyTag = (BodyTag) tag;
        BodyContent bodyContent = new VelocityBodyContent(
                pageContext.getOut(), (ASTBlock) node.jjtGetChild(1),
                context);
        switch (result)
        {
        case BodyTag.EVAL_BODY_BUFFERED:
            bodyTag.setBodyContent(bodyContent);
            bodyTag.doInitBody();
        case BodyTag.EVAL_BODY_INCLUDE:
            bodyContent.getString();
        default:
            break;
        }
        while (bodyTag.doAfterBody() == BodyTag.EVAL_BODY_AGAIN) {
            bodyContent.getString();
        }
    }
    tag.doEndTag();
}
 
Example #15
Source File: UpperCase.java    From CodeGen with MIT License 5 votes vote down vote up
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
    String value = (String) node.jjtGetChild(0).value(context);
    String result = value.replaceFirst(value.substring(0, 1), value.substring(0, 1).toUpperCase());
    writer.write(result);
    return true;
}
 
Example #16
Source File: MicroSqlReplace.java    From nh-micro with Apache License 2.0 5 votes vote down vote up
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node)
		throws IOException, ResourceNotFoundException, ParseErrorException,
		MethodInvocationException {
	List placeList=(List) context.get("placeList");
	if(placeList==null){
		return true;
	}
	Object value=node.jjtGetChild(0).value(context);
	placeList.add(value);
	writer.write("?");
	return true;
}
 
Example #17
Source File: Append.java    From CodeGen with MIT License 5 votes vote down vote up
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
    String prefix = (String) node.jjtGetChild(0).value(context);
    String str = (String) node.jjtGetChild(1).value(context);
    String suffix = (String) node.jjtGetChild(2).value(context);
    writer.write(String.valueOf(prefix + str + suffix));
    return true;
}
 
Example #18
Source File: SingularizeDirective.java    From sundrio with Apache License 2.0 5 votes vote down vote up
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException {
    String word = null;
    if (node.jjtGetChild(0) != null) {
        word = String.valueOf(node.jjtGetChild(0).value(context));
    }

    //truncate and write result to writer
    writer.write(Singularize.FUNCTION.apply(word));
    return true;
}
 
Example #19
Source File: Break.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void init(RuntimeServices rs, InternalContextAdapter context, Node node)
{
    super.init(rs, context, node);

    this.scoped = (node.jjtGetNumChildren() == 1);
}
 
Example #20
Source File: Define.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * directive.render() simply makes an instance of the Block inner class
 * and places it into the context as indicated.
 */
public boolean render(InternalContextAdapter context, Writer writer, Node node)
{
    /* put a Block.Reference instance into the context,
     * using the user-defined key, for later inline rendering.
     */
    context.put(key, new Reference(context, this));
    return true;
}
 
Example #21
Source File: XPathDirective.java    From AuTe-Framework with Apache License 2.0 5 votes vote down vote up
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node ) throws IOException {
    String variableName = node.jjtGetChild(0).getFirstToken().image.substring(1);
    String xmlDocument = String.valueOf(node.jjtGetChild(1).value(context));
    String xpathString = String.valueOf(node.jjtGetChild(2).value(context));

    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        String evaluatedValue = xpath.evaluate(xpathString, new InputSource(new StringReader(xmlDocument)));
        context.put(variableName, evaluatedValue);
    } catch (XPathExpressionException e) {
        throw new IOException("cannot evaluate xpath: " + e.getMessage(), e);
    }
    return true;
}
 
Example #22
Source File: Directive.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * How this directive is to be initialized.
 * @param rs
 * @param context
 * @param node
 * @throws TemplateInitException
 */
public void init( RuntimeServices rs, InternalContextAdapter context,
                  Node node)
    throws TemplateInitException
{
    rsvc = rs;
    log = rsvc.getLog("directive." + getName());

    provideScope = rsvc.isScopeControlEnabled(getScopeName());
}
 
Example #23
Source File: Define.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 *  simple init - get the key
 */
public void init(RuntimeServices rs, InternalContextAdapter context, Node node)
    throws TemplateInitException
{
    super.init(rs, context, node);

    // the first child is the block name (key), the second child is the block AST body
    if ( node.jjtGetNumChildren() != 2 )
    {
        throw new VelocityException("parameter missing: block name at "
             + StringUtils.formatFileString(this),
            null,
            rsvc.getLogContext().getStackTrace());
    }

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

    /*
     * default max depth of two is used because intentional recursion is
     * unlikely and discouraged, so make unintentional ones end fast
     */
    maxDepth = rsvc.getInt(RuntimeConstants.DEFINE_DIRECTIVE_MAXDEPTH, 2);
}
 
Example #24
Source File: Block.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 *  simple init - get the key
 *  @param rs
 *  @param context
 *  @param node
 */
public void init(RuntimeServices rs, InternalContextAdapter context, Node node)
    throws TemplateInitException
{
    super.init(rs, context, node);

    log = rsvc.getLog();

    /**
     * No checking is done. We just grab the last child node and assume
     * that it's the block!
     */
    block = node.jjtGetChild(node.jjtGetNumChildren() - 1);
}
 
Example #25
Source File: For.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
@Override
protected void renderBlock(InternalContextAdapter context, Writer writer, Node node)
  throws IOException
{
  Object count = context.get(counterName);
  if (count instanceof Number)
  {
    context.put(counterName, ((Number)count).intValue() + 1);
  }
  super.renderBlock(context, writer, node);
}
 
Example #26
Source File: For.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public void init(RuntimeServices rs, InternalContextAdapter context, Node node)
    throws TemplateInitException
{
  super.init(rs, context, node);
  // If we have more then 3 argument then the user has specified an
  // index value, i.e.; #foreach($a in $b index $c)
  if (node.jjtGetNumChildren() > 4)
  {
      // The index variable name is at position 4
      counterName = ((ASTReference) node.jjtGetChild(4)).getRootString();
      // The count value always starts at 0 when using an index.
      counterInitialValue = 0;
  }
}
 
Example #27
Source File: Stop.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node)
{
    if (!hasMessage)
    {
        throw STOP_ALL;
    }

    Object argument = node.jjtGetChild(0).value(context);

    // stop all and use specified message
    throw new StopCommand(String.valueOf(argument));
}
 
Example #28
Source File: Include.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 *  iterates through the argument list and renders every
 *  argument that is appropriate.  Any non appropriate
 *  arguments are logged, but render() continues.
 * @param context
 * @param writer
 * @param node
 * @return True if the directive rendered successfully.
 * @throws IOException
 * @throws MethodInvocationException
 * @throws ResourceNotFoundException
 */
public boolean render(InternalContextAdapter context,
                       Writer writer, Node node)
    throws IOException, MethodInvocationException,
           ResourceNotFoundException
{
    /*
     *  get our arguments and check them
     */

    int argCount = node.jjtGetNumChildren();

    for( int i = 0; i < argCount; i++)
    {
        /*
         *  we only handle StringLiterals and References right now
         */

        Node n = node.jjtGetChild(i);

        if ( n.getType() ==  ParserTreeConstants.JJTSTRINGLITERAL ||
             n.getType() ==  ParserTreeConstants.JJTREFERENCE )
        {
            if (!renderOutput( n, context, writer ))
                outputErrorToStream( writer, "error with arg " + i
                    + " please see log.");
        }
        else
        {
            String msg = "invalid #include() argument '"
              + n.toString() + "' at " + StringUtils.formatFileString(this);
            log.error(msg);
            outputErrorToStream( writer, "error with arg " + i
                + " please see log.");
            throw new VelocityException(msg, null, rsvc.getLogContext().getStackTrace());
        }
    }

    return true;
}
 
Example #29
Source File: Macro.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 *   render() doesn't do anything in the final output rendering.
 *   There is no output from a #macro() directive.
 * @param context
 * @param writer
 * @param node
 * @return True if the directive rendered successfully.
 * @throws IOException
 */
public boolean render(InternalContextAdapter context,
                       Writer writer, Node node)
    throws IOException
{
    /*
     *  do nothing: We never render.  The VelocimacroProxy object does that
     */

    return true;
}
 
Example #30
Source File: Macro.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.apache.velocity.runtime.directive.Directive#init(org.apache.velocity.runtime.RuntimeServices, org.apache.velocity.context.InternalContextAdapter, org.apache.velocity.runtime.parser.node.Node)
 */
public void init(RuntimeServices rs, InternalContextAdapter context,
                 Node node)
   throws TemplateInitException
{
    super.init(rs, context, node);


    // Add this macro to the VelocimacroManager now that it has been initialized.
    List<MacroArg> macroArgs = getArgArray(node, rsvc);
    int numArgs = node.jjtGetNumChildren();
    rsvc.addVelocimacro(macroArgs.get(0).name, node.jjtGetChild(numArgs - 1),
        macroArgs, node.getTemplate());
}