org.apache.velocity.runtime.RuntimeServices Java Examples

The following examples show how to use org.apache.velocity.runtime.RuntimeServices. 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: OTPService.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
public static String getSmsBody(String templateFile, Map<String, String> smsTemplate) {
  try {
    String sms = getOTPSMSTemplate(templateFile);
    RuntimeServices rs = RuntimeSingleton.getRuntimeServices();
    SimpleNode sn = rs.parse(sms, "Sms Information");
    Template t = new Template();
    t.setRuntimeServices(rs);
    t.setData(sn);
    t.initDocument();
    VelocityContext context = new VelocityContext();
    context.put(JsonKey.OTP, smsTemplate.get(JsonKey.OTP));
    context.put(
        JsonKey.OTP_EXPIRATION_IN_MINUTES, smsTemplate.get(JsonKey.OTP_EXPIRATION_IN_MINUTES));
    context.put(
        JsonKey.INSTALLATION_NAME,
        ProjectUtil.getConfigValue(JsonKey.SUNBIRD_INSTALLATION_DISPLAY_NAME));

    StringWriter writer = new StringWriter();
    t.merge(context, writer);
    return writer.toString();
  } catch (Exception ex) {
    ProjectLogger.log(
        "OTPService:getSmsBody: Exception occurred with error message = " + ex.getMessage(), ex);
  }
  return "";
}
 
Example #2
Source File: Macro.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * For debugging purposes.  Formats the arguments from
 * <code>argArray</code> and appends them to <code>buf</code>.
 *
 * @param buf A StringBuilder. If null, a new StringBuilder is allocated.
 * @param macroArgs  Array of macro arguments, containing the
 *        #macro() arguments and default values.  the 0th is the name.
 * @return A StringBuilder containing the formatted arguments. If a StringBuilder
 *         has passed in as buf, this method returns it.
 * @since 1.5
 */
public static StringBuilder macroToString(final StringBuilder buf, List<MacroArg> macroArgs, RuntimeServices rsvc)
{
    StringBuilder ret = (buf == null) ? new StringBuilder() : buf;

    ret.append(rsvc.getParserConfiguration().getHashChar()).append(macroArgs.get(0).name).append("( ");
    for (MacroArg marg : macroArgs)
    {
        ret.append(rsvc.getParserConfiguration().getDollarChar()).append(marg.name);
        if (marg.defaultVal != null)
        {
          ret.append("=").append(marg.defaultVal);
        }
        ret.append(' ');
    }
    ret.append(" )");
    return ret;
}
 
Example #3
Source File: VelocityTemplateEngine.java    From pippo with Apache License 2.0 6 votes vote down vote up
@Override
public void renderString(String templateContent, Map<String, Object> model, Writer writer) {
    // create the velocity context
    VelocityContext context = createVelocityContext(model);

    // merge the template
    try {
        RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
        StringReader reader = new StringReader(templateContent);
        SimpleNode node = runtimeServices.parse(reader, "StringTemplate");
        Template template = new Template();
        template.setRuntimeServices(runtimeServices);
        template.setData(node);
        template.initDocument();
        template.merge(context, writer);
    } catch (Exception e) {
        throw new PippoRuntimeException(e);
    }
}
 
Example #4
Source File: SLF4JLogChute.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * @see LogChute#init(RuntimeServices)
 */
public void init(RuntimeServices rs) throws Exception {

    // override from velocity.properties
    String name = (String) rs.getProperty(RUNTIME_LOG_SLF4J_LOGGER);
    if (StringUtils.isBlank(name)) {
        // lets try Sakai convention
        ServletContext context = (ServletContext) rs.getApplicationAttribute("javax.servlet.ServletContext");
        if (context != null) {
            name = DEFAULT_LOGGER + "." + context.getServletContextName();
            name = name.replace("-", ".");
        } else {
            // default to "velocity"
            name = DEFAULT_LOGGER;
        }
    }
    log(INFO_ID, "SLF4JLogChute using logger '" + name + '\'');
}
 
Example #5
Source File: SLF4JLogChute.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * @see LogChute#init(RuntimeServices)
 */
public void init(RuntimeServices rs) throws Exception {

    // override from velocity.properties
    String name = (String) rs.getProperty(RUNTIME_LOG_SLF4J_LOGGER);
    if (StringUtils.isBlank(name)) {
        // lets try Sakai convention
        ServletContext context = (ServletContext) rs.getApplicationAttribute("javax.servlet.ServletContext");
        if (context != null) {
            name = DEFAULT_LOGGER + "." + context.getServletContextName();
            name = name.replace("-", ".");
        } else {
            // default to "velocity"
            name = DEFAULT_LOGGER;
        }
    }
    log(INFO_ID, "SLF4JLogChute using logger '" + name + '\'');
}
 
Example #6
Source File: Include.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 *  simple init - init the tree and get the elementKey from
 *  the AST
 * @param rs
 * @param context
 * @param node
 * @throws TemplateInitException
 */
public void init(RuntimeServices rs, InternalContextAdapter context,
                 Node node)
    throws TemplateInitException
{
    super.init( rs, context, node );

    /*
     *  get the msg, and add the space so we don't have to
     *  do it each time
     */
    outputMsgStart = rsvc.getString(RuntimeConstants.ERRORMSG_START);
    outputMsgStart = outputMsgStart + " ";

    outputMsgEnd = rsvc.getString(RuntimeConstants.ERRORMSG_END );
    outputMsgEnd = " " + outputMsgEnd;
}
 
Example #7
Source File: VelocimacroProxy.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize members of VelocimacroProxy.  called from MacroEntry
 * @param rs runtime services
 */
public void init(RuntimeServices rs)
{
    rsvc = rs;
    log = rs.getLog("macro");

    strictArguments = rsvc.getBoolean(
        RuntimeConstants.VM_ARGUMENTS_STRICT, false);

    // get the macro call depth limit
    maxCallDepth = rsvc.getInt(RuntimeConstants.VM_MAX_DEPTH);

    // get name of the reference that refers to AST block passed to block macro call
    bodyReference = rsvc.getString(RuntimeConstants.VM_BODY_REFERENCE, "bodyContent");

    enableBCmode = rsvc.getBoolean(RuntimeConstants.VM_ENABLE_BC_MODE, false);
}
 
Example #8
Source File: BlockMacro.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the directive.
 *
 * @param rs
 * @param macroName
 * @param context
 * @param node
 * @throws TemplateInitException
 */
public void init(RuntimeServices rs, String macroName, InternalContextAdapter context, Node node)
    throws TemplateInitException
{
    this.name = macroName;

    super.init(rs, context, node);

    // get name of the reference that refers to AST block passed to block macro call
    key = rsvc.getString(RuntimeConstants.VM_BODY_REFERENCE, "bodyContent");

    // use the macro max depth for bodyContent max depth as well
    maxDepth = rsvc.getInt(RuntimeConstants.VM_MAX_DEPTH);

    macro = new RuntimeMacro();
    macro.setLocation(getLine(), getColumn(), getTemplate());
    macro.init(rsvc, name, context, node);
}
 
Example #9
Source File: SimpleNode.java    From velocity-engine with Apache License 2.0 6 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
{
    /*
     * hold onto the RuntimeServices
     */

    rsvc = (RuntimeServices) data;
    log = rsvc.getLog("rendering");

    int i, k = jjtGetNumChildren();

    for (i = 0; i < k; i++)
    {
        jjtGetChild(i).init( context, data);
    }

    line = first.beginLine;
    column = first.beginColumn;

    return data;
}
 
Example #10
Source File: ResourceLoaderFactory.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the loader specified in the configuration file.
 * @param rs
 * @param loaderClassName
 * @return TemplateLoader
 */
public static ResourceLoader getLoader(RuntimeServices rs, String loaderClassName)
{
    ResourceLoader loader = null;

    try
    {
        loader = (ResourceLoader) ClassUtils.getNewInstance( loaderClassName );

        rs.getLog().debug("ResourceLoader instantiated: {}", loader.getClass().getName());

        return loader;
    }
    // The ugly three strike again: ClassNotFoundException,IllegalAccessException,InstantiationException
    catch(Exception e)
    {
        String msg = "Problem instantiating the template loader: "+loaderClassName+"." + System.lineSeparator() +
            "Look at your properties file and make sure the" + System.lineSeparator() +
            "name of the template loader is correct.";
        rs.getLog().error(msg, e);
        throw new VelocityException(msg, e);
    }
}
 
Example #11
Source File: ResourceCacheImpl.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.apache.velocity.runtime.resource.ResourceCache#initialize(org.apache.velocity.runtime.RuntimeServices)
 */
public void initialize( RuntimeServices rs )
{
    rsvc = rs;

    int maxSize =
        rsvc.getInt(RuntimeConstants.RESOURCE_MANAGER_DEFAULTCACHE_SIZE, 89);
    if (maxSize > 0)
    {
        // Create a whole new Map here to avoid hanging on to a
        // handle to the unsynch'd LRUMap for our lifetime.
        Map<Object, Resource> lruCache = Collections.synchronizedMap(new LRUMap<Object, Resource>(maxSize));
        lruCache.putAll(cache);
        cache = lruCache;
    }
    rsvc.getLog().debug("initialized ({}) with {} cache map.", this.getClass(), cache.getClass());
}
 
Example #12
Source File: CustomVelocityResponseTransformer.java    From AuTe-Framework with Apache License 2.0 6 votes vote down vote up
private String getRenderedBodyFromFile(final ResponseDefinition response) throws ParseException {
    RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
    StringReader reader = new StringReader(response.getBody());
    SimpleNode node = runtimeServices.parse(reader, "Template name");
    Template template = new Template();
    template.setEncoding("UTF-8");
    template.setRuntimeServices(runtimeServices);
    template.setData(node);
    template.initDocument();

    StringWriter writer = new StringWriter();
    template.merge(context, writer);
    return String.valueOf(writer.getBuffer());
}
 
Example #13
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 #14
Source File: VelocityTransformer.java    From AuTe-Framework with Apache License 2.0 5 votes vote down vote up
private String render(final String stringTemplate) throws ParseException {
    RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
    runtimeServices.setProperty("userdirective", GroovyDirective.class.getName());
    StringReader reader = new StringReader(stringTemplate);
    SimpleNode node = runtimeServices.parse(reader, "Template name");
    Template template = new Template();
    template.setEncoding("UTF-8");
    template.setRuntimeServices(runtimeServices);
    template.setData(node);
    template.initDocument();

    StringWriter writer = new StringWriter();
    template.merge(velocityContext, writer);
    return String.valueOf(writer.getBuffer());
}
 
Example #15
Source File: ExtensionManager.java    From jsqsh with Apache License 2.0 5 votes vote down vote up
/**
 * This is required by LogChute.
 */
@Override
public void init (RuntimeServices service)
    throws Exception {

    /* Do nothing. */
}
 
Example #16
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 #17
Source File: VelocityUtils.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
public static Template create(String source, String templateName) throws ParseException {
  RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
  StringReader reader = new StringReader(source);
  SimpleNode node = runtimeServices.parse(reader, templateName);
  Template template = new Template();
  template.setRuntimeServices(runtimeServices);
  template.setData(node);
  template.initDocument();
  return template;
}
 
Example #18
Source File: StringExpander.java    From jsqsh with Apache License 2.0 5 votes vote down vote up
/**
 * This is required by LogChute.
 */
@Override
public void init (RuntimeServices service)
    throws Exception {

    /* Do nothing. */
}
 
Example #19
Source File: VelocitySqlSource.java    From mybatis with Apache License 2.0 5 votes vote down vote up
public VelocitySqlSource(Configuration configuration, String scriptText) {
  this.configuration = configuration;
  try {
    RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
    StringReader reader = new StringReader(scriptText);
    SimpleNode node = runtimeServices.parse(reader, "Template name");
    script = new Template();
    script.setRuntimeServices(runtimeServices);
    script.setData(node);
    script.initDocument();
  } catch (Exception ex) {
    throw new BuilderException("Error parsing velocity script", ex);
  }
}
 
Example #20
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 #21
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 #22
Source File: Slf4jLogChute.java    From minnal with Apache License 2.0 5 votes vote down vote up
/********** LogChute methods *************/

    public void init(RuntimeServices rs)
    {
        String name =
            (String)rs.getProperty(LOGCHUTE_SLF4J_NAME);

        if (name == null)
        {
            name = DEFAULT_LOG_NAME;
        }
        log = LoggerFactory.getLogger(name);
        log(LogChute.DEBUG_ID, "Slf4jLogChute name is '" + name + "'");
    }
 
Example #23
Source File: ReportInvalidReferences.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Called automatically when event cartridge is initialized.
 * @param rs RuntimeServices object assigned during initialization
 */
public void setRuntimeServices(RuntimeServices rs)
{
    Boolean b = rs.getConfiguration().getBoolean(OLD_EVENTHANDLER_INVALIDREFERENCE_EXCEPTION, null);
    if (b == null)
    {
        b = rs.getConfiguration().getBoolean(EVENTHANDLER_INVALIDREFERENCE_EXCEPTION, false);
    }
    else
    {
        rs.getLog().warn("configuration key '{}' has been deprecated in favor of '{}'", OLD_EVENTHANDLER_INVALIDREFERENCE_EXCEPTION, EVENTHANDLER_INVALIDREFERENCE_EXCEPTION);
    }
    stopOnFirstInvalidReference = b.booleanValue();
}
 
Example #24
Source File: EscapeReference.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Called automatically when event cartridge is initialized.
 *
 * @param rs instance of RuntimeServices
 */
public void setRuntimeServices(RuntimeServices rs)
{
    this.rs = rs;
    log = rs.getLog("event");

    // Get the regular expression pattern.
    matchRegExp = StringUtils.trim(rs.getString(getMatchAttribute()));
    if (org.apache.commons.lang3.StringUtils.isEmpty(matchRegExp))
    {
        matchRegExp = null;
    }

    // Test the regular expression for a well formed pattern
    if (matchRegExp != null)
    {
        try
        {
            "".matches(matchRegExp);
        }
        catch (PatternSyntaxException E)
        {
            log.error("Invalid regular expression '{}'. No escaping will be performed.",
                      matchRegExp, E);
            matchRegExp = null;
        }
    }

}
 
Example #25
Source File: IncludeNotFound.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.apache.velocity.util.RuntimeServicesAware#setRuntimeServices(org.apache.velocity.runtime.RuntimeServices)
 */
public void setRuntimeServices(RuntimeServices rs)
{
     this.rs = rs;
     log = rs.getLog("event");
     notfound = StringUtils.trim(rs.getString(PROPERTY_NOT_FOUND, DEFAULT_NOT_FOUND));
}
 
Example #26
Source File: EventHandlerUtil.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Called when a method exception is generated during Velocity merge. Only
 * the first valid event handler in the sequence is called. The default
 * implementation simply rethrows the exception.
 *
 * @param claz
 *            Class that is causing the exception
 * @param method
 *            method called that causes the exception
 * @param e
 *            Exception thrown by the method
 * @param rsvc current instance of RuntimeServices
 * @param context The internal context adapter.
 * @param info exception location informations
 * @return Object to return as method result
 * @throws Exception
 *             to be wrapped and propagated to app
 */
public static Object methodException(RuntimeServices rsvc,
        InternalContextAdapter context, Class claz, String method,
        Exception e, Info info) throws Exception
{
    try
    {
        EventCartridge ev = rsvc.getApplicationEventCartridge();
        if (ev.hasMethodExceptionEventHandler())
        {
            return ev.methodException(context, claz, method, e, info);
        }
        EventCartridge contextCartridge = context.getEventCartridge();
        if (contextCartridge != null)
        {
            contextCartridge.setRuntimeServices(rsvc);
            return contextCartridge.methodException(context, claz, method, e, info);
        }
    }
    catch (RuntimeException re)
    {
        throw re;
    }
    catch (Exception ex)
    {
        throw new VelocityException("Exception in event handler.", ex, rsvc.getLogContext().getStackTrace());
    }

    /* default behaviour is to re-throw exception */
    throw e;
}
 
Example #27
Source File: JarHolder.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @param rs
 * @param urlpath
 * @param log
 */
public JarHolder( RuntimeServices rs, String urlpath, Logger log )
{
    this.log = log;

    this.urlpath=urlpath;
    init();

    log.debug("JarHolder: initialized JAR: {}", urlpath);
}
 
Example #28
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 #29
Source File: Directive.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * How this directive is to be initialized.
 * @param rs
 * @param context
 * @param node
 * @throws TemplateInitException
 */
public void init( RuntimeServices rs, InternalContextAdapter context,
                  Node node)
    throws TemplateInitException
{
    rsvc = rs;
    log = rsvc.getLog("directive." + getName());

    provideScope = rsvc.isScopeControlEnabled(getScopeName());
}
 
Example #30
Source File: Parse.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Init's the #parse directive.
 * @param rs
 * @param context
 * @param node
 * @throws TemplateInitException
 */
public void init(RuntimeServices rs, InternalContextAdapter context, Node node)
    throws TemplateInitException
{
    super.init(rs, context, node);

    this.maxDepth = rsvc.getInt(RuntimeConstants.PARSE_DIRECTIVE_MAXDEPTH, 10);

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