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

The following examples show how to use org.apache.velocity.runtime.parser.node.Node#jjtGetNumChildren() . 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: 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 3
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 4
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());
}
 
Example 5
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 6
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 7
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 8
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 9
Source File: Stop.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
public void init(RuntimeServices rs, InternalContextAdapter context, Node node)
{
    super.init(rs, context, node);

    hasMessage = (node.jjtGetNumChildren() == 1);
}
 
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());
    }
}