org.apache.velocity.util.StringUtils Java Examples

The following examples show how to use org.apache.velocity.util.StringUtils. 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: 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 #2
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 #3
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 #4
Source File: ASTComparisonNode.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
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 #6
Source File: OfflineScripter.java    From osmo with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Create the actual script from the RF scripter.
 *
 * @return The complete test script.
 */
public String createScript() {
  for (User user : state.getUsers()) {
    scripter.addVariable(user.getId(), StringUtils.capitalizeFirstLetter(user.getName()));
  }
  script = scripter.createScript();
  return script;
}
 
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: 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 #9
Source File: VelocimacroProxy.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * check that we aren't already at the max call depth and throws
 * a MacroOverflowException if we are there.
 * @param context
 */
protected void checkDepth(InternalContextAdapter context)
{
    if (maxCallDepth > 0 && maxCallDepth == context.getCurrentMacroCallDepth())
    {
        String[] stack = context.getMacroNameStack();

        StringBuilder out = new StringBuilder(100)
            .append("Max calling depth of ").append(maxCallDepth)
            .append(" was exceeded in macro '").append(macroName)
            .append("' with Call Stack:");
        for (int i = 0; i < stack.length; i++)
        {
            if (i != 0)
            {
                out.append("->");
            }
            out.append(stack[i]);
        }
        out.append(" at ").append(StringUtils.formatFileString(this));
        log.error(out.toString());

        // clean out the macro stack, since we just broke it
        while (context.getCurrentMacroCallDepth() > 0)
        {
            context.popCurrentMacroName();
        }
        throw new MacroOverflowException(out.toString(), null, rsvc.getLogContext().getStackTrace());
    }
}
 
Example #10
Source File: Block.java    From velocity-engine with 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 #11
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 #12
Source File: ASTComparisonNode.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: MethodInvocationException.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @see Exception#getMessage()
 * @since 1.5
 */
public String getMessage()
{
    StringBuilder message = new StringBuilder();
    message.append(super.getMessage());
    message.append(" at ");
    message.append(StringUtils.formatFileString(templateName, lineNumber, columnNumber));
    return message.toString();
}
 
Example #14
Source File: ProjectHelper.java    From android-codegenerator-plugin-intellij with Apache License 2.0 5 votes vote down vote up
public List<String> getSourceRootPathList(Project project, AnActionEvent event) {
    List<String> sourceRoots = Lists.newArrayList();
    String projectPath = StringUtils.normalizePath(project.getBasePath());
    for (VirtualFile virtualFile : getModuleRootManager(event).getSourceRoots(false)) {
        sourceRoots.add(StringUtils.normalizePath(virtualFile.getPath()).replace(projectPath, ""));
    }
    return sourceRoots;
}
 
Example #15
Source File: ObjectMapper.java    From DWSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 定义Apache BeanUtils日期Converter的格式,可注册多个格式,以','分隔
 */
public static void registerDateConverter(String patterns) {
	DateConverter dc = new DateConverter();
	dc.setUseLocaleFormat(true);
	dc.setPatterns(StringUtils.split(patterns, ","));
	ConvertUtils.register(dc, Date.class);
}
 
Example #16
Source File: MacroParseException.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
/**
 * @param sb
 * @since 1.5
 */
protected void appendTemplateInfo(final StringBuilder sb)
{
    sb.append(StringUtils.formatFileString(getTemplateName(), getLineNumber(), getColumnNumber()));
    sb.append(eol);
}
 
Example #17
Source File: TemplateParseException.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
/**
 * @param sb
 */
protected void appendTemplateInfo(final StringBuilder sb)
{
    sb.append(StringUtils.formatFileString(getTemplateName(), getLineNumber(), getColumnNumber()));
    sb.append(eol);
}
 
Example #18
Source File: ParseErrorException.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
/**
 * 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 #19
Source File: PowerManagementConfigurationAction.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Runs this action.
 * @param mapping action mapping
 * @param formIn form submitted values
 * @param request http request object
 * @param response http response object
 * @return an action forward object
 */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm formIn,
    HttpServletRequest request, HttpServletResponse response) {
    RequestContext context = new RequestContext(request);
    DynaActionForm form = (DynaActionForm) formIn;
    StrutsDelegate strutsDelegate = getStrutsDelegate();
    User user = context.getCurrentUser();
    ActionErrors errors = new ActionErrors();
    int successCount = 0;

    if (context.isSubmitted() && context.wasDispatched(
            "ssm.provisioning.powermanagement.configuration.update")) {
        List<SystemOverview> systemOverviews = getResult(context);
        for (SystemOverview systemOverview : systemOverviews) {
            try {
                Server server = SystemManager.lookupByIdAndUser(systemOverview.getId(),
                    user);
                CobblerPowerSettingsUpdateCommand command = PowerManagementAction
                    .getPowerSettingsUpdateCommandSSM(form, user, server);
                if (command.store() == null) {
                    successCount += 1;
                }
            }
            catch (XmlRpcException e) {
                log.error(StringUtils.stackTrace(e));
                log.error(StringUtils.stackTrace(e.getCause()));
            }
        }

        createSuccessMessage(request,
            "ssm.provisioning.powermanagement.configuration.saved", "" + successCount);
    }

    Map<String, String> types = PowerManagementAction.setUpPowerTypes(request,
            strutsDelegate, errors);
    PowerManagementAction.ensureAgentInstalled(request, strutsDelegate, errors);
    if (!types.isEmpty()) {
        types.put(
            LocalizationService.getInstance().getPlainText(
                "ssm.provisioning.powermanagement.configuration.dontchange"), "");
    }

    ListHelper helper = new ListHelper(this, request);
    helper.execute();

    return strutsDelegate.forwardParams(mapping.findForward(RhnHelper.DEFAULT_FORWARD),
        request.getParameterMap());
}
 
Example #20
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 #21
Source File: PathHelper.java    From android-codegenerator-plugin-intellij with Apache License 2.0 4 votes vote down vote up
public String getFolderPath(String sourcePath, String packageName) {
    String normalizePath = StringUtils.normalizePath(sourcePath + "/" + StringUtils.getPackageAsPath(packageName));
    return org.apache.commons.lang3.StringUtils.strip(normalizePath, "/");
}
 
Example #22
Source File: SimpleNode.java    From velocity-engine with 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 #23
Source File: Info.java    From velocity-engine with 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());
}