Java Code Examples for org.apache.velocity.runtime.parser.node.Node#jjtGetChild()

The following examples show how to use org.apache.velocity.runtime.parser.node.Node#jjtGetChild() . 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: 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 2
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 3
Source File: FieldDirective.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 = "";
    Property field = null;
    //reading params
    if (node.jjtGetChild(0) != null) {
        field = (Property) node.jjtGetChild(0).value(context);
    }
    writeField(writer, field, block);
    return true;
}
 
Example 4
Source File: MethodDirective.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 = "";
    Method method = null;
    Boolean isInterface = false;
    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) {
                    method = (Method) node.jjtGetChild(i).value(context);
                } else if (i == 1) {
                    isInterface = (Boolean) node.jjtGetChild(i).value(context);
                } else {
                    break;
                }
            } else {
                //reading block content and rendering it
                StringWriter blockContent = new StringWriter();
                node.jjtGetChild(i).render(context, blockContent);

                block = blockContent.toString();
                break;
            }
        }
    }
    writeMethod(writer, method, block, isInterface);
    return true;
}
 
Example 5
Source File: PluralizeDirective.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(Pluralize.FUNCTION.apply(word));
    return true;
}
 
Example 6
Source File: TrimExtDirective.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
protected Params getParams(final InternalContextAdapter context, final Node node) throws IOException,
        ResourceNotFoundException, ParseErrorException, MethodInvocationException {
    final Params params = new Params();
    final int nodes = node.jjtGetNumChildren();
    for (int i = 0; i < nodes; i++) {
        Node child = node.jjtGetChild(i);
        if (child != null) {
            if (!(child instanceof ASTBlock)) {
                if (i == 0) {
                    params.setPrefix(String.valueOf(child.value(context)));
                } else if (i == 1) {
                    params.setPrefixOverrides(String.valueOf(child.value(context)).toUpperCase(Locale.ENGLISH));
                } else if (i == 2) {
                    params.setSuffix(String.valueOf(child.value(context)));
                } else if (i == 3) {
                    params.setSuffixOverrides(String.valueOf(child.value(context)).toUpperCase(Locale.ENGLISH));
                } else {
                    break;
                }
            } else {
                StringWriter blockContent = new StringWriter();
                child.render(context, blockContent);
                if ("".equals(blockContent.toString().trim())) {
                    return null;
                }
                params.setBody(blockContent.toString().trim());
                break;
            }
        }
    }
    return params;
}
 
Example 7
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 8
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 9
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 10
Source File: RuntimeMacro.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize the Runtime macro. At the init time no implementation so we
 * just save the values to use at the render time.
 *
 * @param rs runtime services
 * @param name macro name
 * @param context InternalContextAdapter
 * @param node node containing the macro call
 */
public void init(RuntimeServices rs, String name, InternalContextAdapter context,
                 Node node)
{
    super.init(rs, context, node);

    macroName = Validate.notNull(name);
    macroName = rsvc.useStringInterning() ? macroName.intern() : macroName;
    this.node = node;

    /**
     * Apply strictRef setting only if this really looks like a macro,
     * so strict mode doesn't balk at things like #E0E0E0 in a template.
     * compare with ")" is a simple #foo() style macro, comparing to
     * "#end" is a block style macro. We use starts with because the token
     * may end with '\n'
     */
    // Tokens can be used here since we are in init() and Tokens have not been dropped yet
    Token t = node.getLastToken();
    if (t.image.startsWith(")") || t.image.startsWith(rsvc.getParserConfiguration().getHashChar() + "end"))
    {
        strictRef = rsvc.getBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false);
    }

    // Validate that none of the arguments are plain words, (VELOCITY-614)
    // they should be string literals, references, inline maps, or inline lists
    for (int n=0; n < node.jjtGetNumChildren(); n++)
    {
        Node child = node.jjtGetChild(n);
        if (child.getType() == ParserTreeConstants.JJTWORD)
        {
            badArgsErrorMsg = "Invalid arg '" + child.getFirstTokenImage()
            + "' in macro #" + macroName + " at " + StringUtils.formatFileString(child);

            if (strictRef)  // If strict, throw now
            {
                /* indicate col/line assuming it starts at 0
                 * this will be corrected one call up  */
                throw new TemplateInitException(badArgsErrorMsg,
                null,
                rsvc.getLogContext().getStackTrace(),
                context.getCurrentTemplateName(), 0, 0);
            }
        }
    }
    // TODO: Improve this
    // this is only needed if the macro does not exist during runtime
    // since tokens are eliminated after this init call, we have to create a cached version of the
    // literal which is in 99.9% cases waste. However, for regular macro calls (non Block macros)
    // this doesn't create very long Strings so it's probably acceptable
    getLiteral();
}
 
Example 11
Source File: Macro.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an array containing the literal text from the macro
 * argument(s) (including the macro's name as the first arg).
 *
 * @param node The parse node from which to grok the argument
 * list.  It's expected to include the block node tree (for the
 * macro body).
 * @param rsvc For debugging purposes only.
 * @return array of arguments
 */
private static List<MacroArg> getArgArray(Node node, RuntimeServices rsvc)
{
    /*
     * Get the number of arguments for the macro, excluding the
     * last child node which is the block tree containing the
     * macro body.
     */
    int numArgs = node.jjtGetNumChildren();
    numArgs--;  // avoid the block tree...

    ArrayList<MacroArg> macroArgs = new ArrayList();

    for (int i = 0; i < numArgs; i++)
    {
        Node curnode = node.jjtGetChild(i);
        MacroArg macroArg = new MacroArg();
        if (curnode.getType() == ParserTreeConstants.JJTDIRECTIVEASSIGN)
        {
            // This is an argument with a default value
        	macroArg.name = curnode.getFirstTokenImage();

            // Inforced by the parser there will be an argument here.
            i++;
            curnode = node.jjtGetChild(i);
            macroArg.defaultVal = curnode;
        }
        else
        {
            // An argument without a default value
           	macroArg.name = curnode.getFirstTokenImage();
        }

        // trim off the leading $ for the args after the macro name.
        // saves everyone else from having to do it
        if (i > 0 && macroArg.name.startsWith(String.valueOf(rsvc.getParserConfiguration().getDollarChar())))
        {
            macroArg.name = macroArg.name.substring(1);
        }

        macroArgs.add(macroArg);
    }

    if (debugMode)
    {
        StringBuilder msg = new StringBuilder("Macro.getArgArray(): nbrArgs=");
        msg.append(numArgs).append(": ");
        macroToString(msg, macroArgs, rsvc);
        rsvc.getLog("macro").debug(msg.toString());
    }

    return macroArgs;
}
 
Example 12
Source File: Evaluate.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize and check arguments.
 * @param rs
 * @param context
 * @param node
 * @throws TemplateInitException
 */
public void init(RuntimeServices rs, InternalContextAdapter context,
                 Node node)
    throws TemplateInitException
{
    super.init( rs, context, node );

    /**
     * Check that there is exactly one argument and it is a string or reference.
     */

    int argCount = node.jjtGetNumChildren();
    if (argCount == 0)
    {
        throw new TemplateInitException(
                "#" + getName() + "() requires exactly one argument",
                null,
                rsvc.getLogContext().getStackTrace(),
                context.getCurrentTemplateName(),
                node.getColumn(),
                node.getLine());
    }
    if (argCount > 1)
    {
        /*
         * use line/col of second argument
         */

        throw new TemplateInitException(
                "#" + getName() + "() requires exactly one argument",
                null,
                rsvc.getLogContext().getStackTrace(),
                context.getCurrentTemplateName(),
                node.jjtGetChild(1).getColumn(),
                node.jjtGetChild(1).getLine());
    }

    Node childNode = node.jjtGetChild(0);
    if ( childNode.getType() !=  ParserTreeConstants.JJTSTRINGLITERAL &&
         childNode.getType() !=  ParserTreeConstants.JJTREFERENCE )
    {
       throw new TemplateInitException(
               "#" + getName() + "()  argument must be a string literal or reference",
               null,
               rsvc.getLogContext().getStackTrace(),
               context.getCurrentTemplateName(),
               childNode.getColumn(),
               childNode.getLine());
    }
}