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 Project: sunbird-lms-service   Author: project-sunbird   File: OTPService.java    License: 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 Project: sakai   Author: sakaiproject   File: SLF4JLogChute.java    License: 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 #3
Source Project: sakai   Author: sakaiproject   File: SLF4JLogChute.java    License: 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 #4
Source Project: pippo   Author: pippo-java   File: VelocityTemplateEngine.java    License: 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 #5
Source Project: velocity-engine   Author: apache   File: SimpleNode.java    License: 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 #6
Source Project: velocity-engine   Author: apache   File: ResourceLoaderFactory.java    License: 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 #7
Source Project: velocity-engine   Author: apache   File: ResourceCacheImpl.java    License: 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 #8
Source Project: velocity-engine   Author: apache   File: BlockMacro.java    License: 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 Project: velocity-engine   Author: apache   File: VelocimacroProxy.java    License: 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 #10
Source Project: velocity-engine   Author: apache   File: Macro.java    License: 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 #11
Source Project: velocity-engine   Author: apache   File: Include.java    License: 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 #12
Source Project: AuTe-Framework   Author: BSC-RUS   File: VelocityTransformer.java    License: 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 #13
Source Project: AuTe-Framework   Author: BSC-RUS   File: CustomVelocityResponseTransformer.java    License: Apache License 2.0 5 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 #14
Source Project: iotplatform   Author: osswangxining   File: VelocityUtils.java    License: 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 #15
Source Project: mybaties   Author: shurun19851206   File: VelocitySqlSource.java    License: 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 #16
Source Project: htmlcompressor   Author: serg472   File: JavaScriptCompressorDirective.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void init(RuntimeServices rs, InternalContextAdapter context, Node node) throws TemplateInitException {
	super.init(rs, context, node);
	log = rs.getLog();
	
	//set compressor properties
	enabled = rs.getBoolean("userdirective.compressJs.enabled", true);
	jsCompressor = rs.getString("userdirective.compressHtml.jsCompressor", HtmlCompressor.JS_COMPRESSOR_YUI);
	yuiJsNoMunge = rs.getBoolean("userdirective.compressJs.yuiJsNoMunge", false);
	yuiJsPreserveAllSemiColons = rs.getBoolean("userdirective.compressJs.yuiJsPreserveAllSemiColons", false);
	yuiJsLineBreak = rs.getInt("userdirective.compressJs.yuiJsLineBreak", -1);
	closureOptLevel = rs.getString("userdirective.compressHtml.closureOptLevel", ClosureJavaScriptCompressor.COMPILATION_LEVEL_SIMPLE);
}
 
Example #17
Source Project: htmlcompressor   Author: serg472   File: CssCompressorDirective.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void init(RuntimeServices rs, InternalContextAdapter context, Node node) throws TemplateInitException {
	super.init(rs, context, node);
	log = rs.getLog();
	
	//set compressor properties
	enabled = rs.getBoolean("userdirective.compressCss.enabled", true);
	yuiCssLineBreak = rs.getInt("userdirective.compressCss.yuiCssLineBreak", -1);
}
 
Example #18
Source Project: htmlcompressor   Author: serg472   File: XmlCompressorDirective.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void init(RuntimeServices rs, InternalContextAdapter context, Node node) throws TemplateInitException {
	super.init(rs, context, node);
	log = rs.getLog();
	
	//set compressor properties
	xmlCompressor.setEnabled(rs.getBoolean("userdirective.compressXml.enabled", true));
	xmlCompressor.setRemoveComments(rs.getBoolean("userdirective.compressXml.removeComments", true));
	xmlCompressor.setRemoveIntertagSpaces(rs.getBoolean("userdirective.compressXml.removeIntertagSpaces", true));
}
 
Example #19
Source Project: jsqsh   Author: scgray   File: ExtensionManager.java    License: 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 #20
Source Project: jsqsh   Author: scgray   File: StringExpander.java    License: 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 #21
Source Project: mybatis   Author: tuguangquan   File: VelocitySqlSource.java    License: 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 #22
Source Project: minnal   Author: minnal   File: Slf4jLogChute.java    License: 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 Project: velocity-engine   Author: apache   File: ReportInvalidReferences.java    License: 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 Project: velocity-engine   Author: apache   File: EscapeReference.java    License: 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 Project: velocity-engine   Author: apache   File: IncludeNotFound.java    License: 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 Project: velocity-engine   Author: apache   File: EventHandlerUtil.java    License: 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 Project: velocity-engine   Author: apache   File: JarHolder.java    License: 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 Project: velocity-engine   Author: apache   File: Parse.java    License: 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);
}
 
Example #29
Source Project: velocity-engine   Author: apache   File: Directive.java    License: 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 Project: velocity-engine   Author: apache   File: Block.java    License: 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);
}