Java Code Examples for org.apache.velocity.util.StringUtils#formatFileString()

The following examples show how to use org.apache.velocity.util.StringUtils#formatFileString() . These examples are extracted from open source projects. 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
/**
 * Always false by default, != and == subclasses must override this.
 * @param left
 * @param right
 * @return comparison result
 */
public boolean compareNull(Object left, Object right)
{
    // if either side is null, log and bail
    String msg = (left == null ? "Left" : "Right")
                   + " side ("
                   + jjtGetChild( (left == null? 0 : 1) ).literal()
                   + ") of comparison operation has null value at "
                   + StringUtils.formatFileString(this);
    if (rsvc.getBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false))
    {
        throw new VelocityException(msg, null, rsvc.getLogContext().getStackTrace());
    }
    log.error(msg);
    return false;
}
 
Example 2
Source Project: velocity-engine   File: ASTReference.java    License: 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 3
/**
 * 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 4
Source Project: velocity-engine   File: Break.java    License: 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 5
public boolean compareNonNumber(Object left, Object right)
{
    // by default, log and bail
    String msg = (right instanceof Number ? "Left" : "Right")
                   + " side of comparison operation is not a number at "
                   + StringUtils.formatFileString(this);
    if (rsvc.getBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false))
    {
        throw new VelocityException(msg, null, rsvc.getLogContext().getStackTrace());
    }
    log.error(msg);
    return false;
}
 
Example 6
Source Project: velocity-engine   File: Block.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * renders block directive
 * @param context
 * @param writer
 * @return success status
 */
public boolean render(InternalContextAdapter context, Writer writer)
{
    preRender(context);
    try
    {
        return block.render(context, writer);
    }
    catch (IOException e)
    {
        String msg = "Failed to render " + id(context) + " to writer at " +
            StringUtils.formatFileString(this);
        log.error(msg, e);
        throw new RuntimeException(msg, e);
    }
    catch (StopCommand stop)
    {
        if (!stop.isFor(this))
        {
            throw stop;
        }
        return true;
    }
    finally
    {
        postRender(context);
    }
}
 
Example 7
Source Project: velocity-engine   File: Include.java    License: 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 8
Source Project: velocity-engine   File: Define.java    License: 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 9
/**
 * Create a ParseErrorException with the given ParseException.
 *
 * @param pex the parsing exception
 * @param templName
 * @since 1.5
 */
public ParseErrorException(ParseException pex, String templName)
{
    super(pex.getMessage());

    if (templName != null) templateName = templName;

    // Don't use a second C'tor, TemplateParseException is a subclass of
    // ParseException...
    if (pex instanceof ExtendedParseException)
    {
        ExtendedParseException xpex = (ExtendedParseException) pex;

        columnNumber = xpex.getColumnNumber();
        lineNumber = xpex.getLineNumber();
        templateName = xpex.getTemplateName();
    }
    else
    {
        // We get here if the the Parser has thrown an exception. Unfortunately,
        // the error message created is hard coded by javacc, so here we alter
        // the error message, so that it is in our standard format.
        Matcher match =  lexError.matcher(pex.getMessage());
        if (match.matches())
        {
           lineNumber = Integer.parseInt(match.group(1));
           columnNumber = Integer.parseInt(match.group(2));
           String restOfMsg = match.group(3);
           msg = "Lexical error, " + restOfMsg + " at "
             + StringUtils.formatFileString(templateName, lineNumber, columnNumber);
        }

        //  ugly, ugly, ugly...

        if (pex.currentToken != null && pex.currentToken.next != null)
        {
            columnNumber = pex.currentToken.next.beginColumn;
            lineNumber = pex.currentToken.next.beginLine;
        }
    }
}
 
Example 10
Source Project: velocity-engine   File: RuntimeMacro.java    License: 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 Project: velocity-engine   File: SimpleNode.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Return a string that tells the current location of this node.
 * @param context
 * @return location
 */
protected String getLocation(InternalContextAdapter context)
{
    return StringUtils.formatFileString(this);
}
 
Example 12
Source Project: velocity-engine   File: Info.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Formats a textual representation of this object as <code>SOURCE
 * [line X, column Y]</code>.
 *
 * @return String representing this object.
 * @since 1.5
 */
public String toString()
{
    return StringUtils.formatFileString(getTemplateName(), getLine(), getColumn());
}