org.apache.velocity.context.InternalContextAdapter Java Examples

The following examples show how to use org.apache.velocity.context.InternalContextAdapter. 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: ASTBlock.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.apache.velocity.runtime.parser.node.SimpleNode#render(org.apache.velocity.context.InternalContextAdapter, java.io.Writer)
 */
public boolean render( InternalContextAdapter context, Writer writer)
    throws IOException, MethodInvocationException,
    	ResourceNotFoundException, ParseErrorException
{
    SpaceGobbling spaceGobbling = rsvc.getSpaceGobbling();

    if (spaceGobbling == SpaceGobbling.NONE)
    {
        writer.write(prefix);
    }

    int i, k = jjtGetNumChildren();

    for (i = 0; i < k; i++)
        jjtGetChild(i).render(context, writer);

    if (morePostfix.length() > 0 || spaceGobbling.compareTo(SpaceGobbling.LINES) < 0)
    {
        writer.write(postfix);
    }

    writer.write(morePostfix);

    return true;
}
 
Example #2
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 #3
Source File: ASTAddNode.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
@Override
protected Object handleSpecial(Object left, Object right, InternalContextAdapter context)
{
    // check for strings, but don't coerce
    String lstr = DuckType.asString(left, false);
    String rstr = DuckType.asString(right, false);
    if (lstr != null || rstr != null)
    {
        if (lstr == null)
        {
            lstr = left != null ? left.toString() : jjtGetChild(0).literal();
        }
        else if (rstr == null)
        {
            rstr = right != null ? right.toString() : jjtGetChild(1).literal();
        }
        return lstr.concat(rstr);
    }
    return null;
}
 
Example #4
Source File: ASTReference.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 *   Computes boolean value of this reference
 *   Returns the actual value of reference return type
 *   boolean, and 'true' if value is not null
 *
 *   @param context context to compute value with
 * @return True if evaluation was ok.
 * @throws MethodInvocationException
 */
public boolean evaluate(InternalContextAdapter context)
    throws MethodInvocationException
{
    Object value = execute(this, context); // non-null object as first parameter by convention for 'evaluate'
    if (value == null)
    {
        return false;
    }
    try
    {
        rsvc.getLogContext().pushLogContext(this, uberInfo);
        return DuckType.asBoolean(value, checkEmpty);
    }
    catch(Exception e)
    {
        throw new VelocityException("Reference evaluation threw an exception at "
            + StringUtils.formatFileString(this), e, rsvc.getLogContext().getStackTrace());
    }
    finally
    {
        rsvc.getLogContext().popLogContext();
    }
}
 
Example #5
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 #6
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 #7
Source File: ASTIdentifier.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 *  simple init - don't do anything that is context specific.
 *  just get what we need from the AST, which is static.
 * @param context
 * @param data
 * @return The data object.
 * @throws TemplateInitException
 */
public  Object init(InternalContextAdapter context, Object data)
    throws TemplateInitException
{
    super.init(context, data);

    identifier = rsvc.useStringInterning() ? getFirstToken().image.intern() : getFirstToken().image;

    uberInfo = new Info(getTemplateName(), getLine(), getColumn());

    strictRef = rsvc.getBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false);

    saveTokenImages();
    cleanupParserAndTokens();

    return data;
}
 
Example #8
Source File: Block.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Render the AST of this block into the writer using the context.
 * @param context
 * @param writer
 * @return  success status
 */
public boolean render(InternalContextAdapter context, Writer writer)
{
    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 {} at {}", parent.id(context), StringUtils.formatFileString(parent));
        depth--;
        return false;
    }
    else
    {
        parent.render(context, writer);
        depth--;
        return true;
    }
}
 
Example #9
Source File: ASTObjectArray.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.apache.velocity.runtime.parser.node.SimpleNode#value(org.apache.velocity.context.InternalContextAdapter)
 */
public Object value( InternalContextAdapter context)
    throws MethodInvocationException
{
    int size = jjtGetNumChildren();

    // since we know the amount of elements, initialize arraylist with proper size
    List objectArray = new ArrayList(size);

    for (int i = 0; i < size; i++)
    {
        objectArray.add(jjtGetChild(i).value(context));
    }

    return objectArray;
}
 
Example #10
Source File: ASTTextblock.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.apache.velocity.runtime.parser.node.SimpleNode#init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)
 */
public Object init( InternalContextAdapter context, Object data)
throws TemplateInitException
{
    Token t = getFirstToken();

    String text = t.image;

    // t.image is in format: #[[ <string> ]]#
    // we must strip away the hash tags
    text = text.substring(START.length(), text.length() - END.length());

    ctext = text.toCharArray();

    cleanupParserAndTokens();

    return data;
}
 
Example #11
Source File: ASTComment.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 *  We need to make sure we catch any of the dreaded MORE tokens.
 * @param context
 * @param data
 * @return The data object.
 */
public Object init(InternalContextAdapter context, Object data)
{
    Token t = getFirstToken();

    int loc1 = t.image.indexOf(parser.lineComment());
    int loc2 = t.image.indexOf(parser.blockComment());

    if (loc1 == -1 && loc2 == -1)
    {
        carr = ZILCH;
    }
    else
    {
        carr = t.image.substring(0, (loc1 == -1) ? loc2 : loc1).toCharArray();
    }

    cleanupParserAndTokens();

    return data;
}
 
Example #12
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 #13
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 #14
Source File: ASTText.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.apache.velocity.runtime.parser.node.SimpleNode#init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)
 */
public Object init( InternalContextAdapter context, Object data)
throws TemplateInitException
{
    StringBuilder builder = new StringBuilder();
    Token t = getFirstToken();
    for (; t != getLastToken(); t = t.next)
    {
        builder.append(NodeUtils.tokenLiteral(parser, t));
    }
    builder.append(NodeUtils.tokenLiteral(parser, t));
    ctext = builder.toString();

    cleanupParserAndTokens();

    return data;
}
 
Example #15
Source File: ASTOrNode.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 *  the logical or :
 *    <pre>
 *      left || null -&gt; left
 *      null || right -&gt; right
 *      null || null -&gt; false
 *      left || right -&gt;  left || right
 *    </pre>
 * @param context
 * @return The evaluation result.
 * @throws MethodInvocationException
 */
public boolean evaluate( InternalContextAdapter context)
    throws MethodInvocationException
{
    Node left = jjtGetChild(0);
    Node right = jjtGetChild(1);

    /*
     *  if the left is not null and true, then true
     */

    if (left != null && left.evaluate( context ) )
        return true;

    /*
     *  same for right
     */

    return right != null && right.evaluate(context);
}
 
Example #16
Source File: ASTBinaryOperator.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @throws TemplateInitException
 * @see org.apache.velocity.runtime.parser.node.Node#init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)
 */
public Object init( InternalContextAdapter context, Object data) throws TemplateInitException
{
    Object obj = super.init(context, data);
    cleanupParserAndTokens(); // drop reference to Parser and all JavaCC Tokens
    return obj;
}
 
Example #17
Source File: ASTVariable.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @throws TemplateInitException
 * @see org.apache.velocity.runtime.parser.node.Node#init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)
 */
public Object init( InternalContextAdapter context, Object data) throws TemplateInitException
{
	Object obj = super.init(context, data);
	cleanupParserAndTokens(); // drop reference to Parser and all JavaCC Tokens
	return obj;
}
 
Example #18
Source File: ASTText.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.apache.velocity.runtime.parser.node.SimpleNode#render(org.apache.velocity.context.InternalContextAdapter, java.io.Writer)
 */
public boolean render( InternalContextAdapter context, Writer writer)
    throws IOException
{
    writer.write(ctext);
    return true;
}
 
Example #19
Source File: ASTIncludeStatement.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @throws TemplateInitException
 * @see org.apache.velocity.runtime.parser.node.Node#init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)
 */
public Object init( InternalContextAdapter context, Object data) throws TemplateInitException
{
	Object obj = super.init(context, data);
	cleanupParserAndTokens(); // drop reference to Parser and all JavaCC Tokens
	return obj;
}
 
Example #20
Source File: ASTReference.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @param context
 * @return The evaluated value of the variable.
 * @throws MethodInvocationException
 */
public Object getRootVariableValue(InternalContextAdapter context)
{
    Object obj = null;
    try
    {
        obj = context.get(rootString);
    }
    catch(RuntimeException e)
    {
        log.error("Exception calling reference ${} at {}",
                  rootString, StringUtils.formatFileString(uberInfo));
        throw e;
    }

    if (obj == null && strictRef && astAlternateValue == null)
    {
      if (!context.containsKey(rootString))
      {
          log.error("Variable ${} has not been set at {}",
                    rootString, StringUtils.formatFileString(uberInfo));
          throw new MethodInvocationException("Variable $" + rootString +
              " has not been set", null, rsvc.getLogContext().getStackTrace(), identifier,
              uberInfo.getTemplateName(), uberInfo.getLine(), uberInfo.getColumn());
      }
    }
    return obj;
}
 
Example #21
Source File: ASTMap.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @throws TemplateInitException
 * @see org.apache.velocity.runtime.parser.node.Node#init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)
 */
public Object init( InternalContextAdapter context, Object data) throws TemplateInitException
{
	Object obj = super.init(context, data);
	cleanupParserAndTokens(); // drop reference to Parser and all JavaCC Tokens
	return obj;
}
 
Example #22
Source File: ASTComment.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.apache.velocity.runtime.parser.node.SimpleNode#render(org.apache.velocity.context.InternalContextAdapter, java.io.Writer)
 */
public boolean render( InternalContextAdapter context, Writer writer)
    throws IOException, MethodInvocationException, ParseErrorException, ResourceNotFoundException
{
    writer.write(carr);
    return true;
}
 
Example #23
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 #24
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 #25
Source File: ASTAndNode.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * logical and :
 * <pre>
 *   null &amp;&amp; right = false
 *   left &amp;&amp; null = false
 *   null &amp;&amp; null = false
 * </pre>
 * @param context
 * @return True if both sides are true.
 * @throws MethodInvocationException
 */
public boolean evaluate( InternalContextAdapter context)
    throws MethodInvocationException
{
    Node left = jjtGetChild(0);
    Node right = jjtGetChild(1);

    /*
     * null == false
     */
    if (left == null || right == null)
    {
        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;
}
 
Example #26
Source File: ASTEscape.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.apache.velocity.runtime.parser.node.SimpleNode#render(org.apache.velocity.context.InternalContextAdapter, java.io.Writer)
 */
public boolean render( InternalContextAdapter context, Writer writer)
    throws IOException
{
    writer.write(ctext);
    return true;
}
 
Example #27
Source File: ASTMathNode.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Object init(InternalContextAdapter context, Object data) throws TemplateInitException
{
    super.init(context, data);
    strictMode = rsvc.getBoolean(RuntimeConstants.STRICT_MATH, false);
    cleanupParserAndTokens();
    return data;
}
 
Example #28
Source File: ASTAssignment.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @throws TemplateInitException
 * @see org.apache.velocity.runtime.parser.node.Node#init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)
 */
public Object init( InternalContextAdapter context, Object data) throws TemplateInitException
{
	Object obj = super.init(context, data);
	cleanupParserAndTokens(); // drop reference to Parser and all JavaCC Tokens
	return obj;
}
 
Example #29
Source File: ASTModNode.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @throws TemplateInitException
 * @see org.apache.velocity.runtime.parser.node.Node#init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)
 */
public Object init( InternalContextAdapter context, Object data) throws TemplateInitException
{
	Object obj = super.init(context, data);
	cleanupParserAndTokens(); // drop reference to Parser and all JavaCC Tokens
	return obj;
}
 
Example #30
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;
}