Java Code Examples for org.apache.velocity.app.Velocity#evaluate()
The following examples show how to use
org.apache.velocity.app.Velocity#evaluate() .
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: VelocityEval.java From kafka-connect-rest with Apache License 2.0 | 7 votes |
@Override public R apply(R record) { StringWriter sw = new StringWriter(); VelocityContext context = new VelocityContext(globalContext); context.put("r", record); context.put("topic", record.topic()); context.put("partition", record.kafkaPartition()); context.put("key", record.key()); context.put("timestamp", record.timestamp() == null ? 0 : record.timestamp()); context.put("schema", operatingSchema(record)); context.put("value", operatingValue(record)); Velocity.evaluate(context, sw, "", template); return newRecord(record, Schema.STRING_SCHEMA, sw.toString()); }
Example 2
Source File: VelocimacroTestCase.java From velocity-engine with Apache License 2.0 | 6 votes |
/** * Runs the test. */ public void testVelociMacro () throws Exception { VelocityContext context = new VelocityContext(); StringWriter writer = new StringWriter(); Velocity.evaluate(context, writer, "vm_chain1", template1); String out = writer.toString(); if( !result1.equals( out ) ) { fail("output incorrect."); } }
Example 3
Source File: VelocityUsage.java From Android_Code_Arbiter with GNU Lesser General Public License v3.0 | 6 votes |
public void usage1(String inputFile) throws FileNotFoundException { Velocity.init(); VelocityContext context = new VelocityContext(); context.put("author", "Elliot A."); context.put("address", "217 E Broadway"); context.put("phone", "555-1337"); FileInputStream file = new FileInputStream(inputFile); //Evaluate StringWriter swOut = new StringWriter(); Velocity.evaluate(context, swOut, "test", file); String result = swOut.getBuffer().toString(); System.out.println(result); }
Example 4
Source File: BpmTypeTaskFormAction.java From entando-components with GNU Lesser General Public License v3.0 | 6 votes |
public String render(DataObject dataobject, String contentModel, String langCode, RequestContext reqCtx) { String renderedEntity; try { Context velocityContext = new VelocityContext(); DataObjectWrapper contentWrapper = (DataObjectWrapper) this.getEntityWrapper(dataobject); contentWrapper.setRenderingLang(langCode); velocityContext.put("data", contentWrapper); I18nManagerWrapper i18nWrapper = new I18nManagerWrapper(langCode, this.getI18nManager()); velocityContext.put("i18n", i18nWrapper); SystemInfoWrapper systemInfoWrapper = new SystemInfoWrapper(reqCtx); velocityContext.put("info", systemInfoWrapper); StringWriter stringWriter = new StringWriter(); boolean isEvaluated = Velocity.evaluate(velocityContext, stringWriter, "render", contentModel); if (!isEvaluated) { throw new ApsSystemException("Error rendering DataObject"); } stringWriter.flush(); renderedEntity = stringWriter.toString(); } catch (Throwable t) { logger.error("Error rendering dataobject", t); renderedEntity = ""; } return renderedEntity; }
Example 5
Source File: RenderTool.java From velocity-tools with Apache License 2.0 | 6 votes |
protected String internalEval(Context ctx, String vtl) throws Exception { if (vtl == null) { return null; } StringWriter sw = new StringWriter(); boolean success; if (engine == null) { success = Velocity.evaluate(ctx, sw, "RenderTool.eval()", vtl); } else { success = engine.evaluate(ctx, sw, "RenderTool.eval()", vtl); } if (success) { return sw.toString(); } /* or would it be preferable to return the original? */ return null; }
Example 6
Source File: QueryPool.java From fastquery with Apache License 2.0 | 6 votes |
/** * 渲染模板,该方法永远不会返回null或空,因为在初始化时就做了检测 * * @param tpl 模板 * @param logTag 日志标识 * @param map 键值 * @return 渲染之后的字符串 */ private static String render(String tpl, String logTag, Map<String, Object> map) { // 不用判断map是否为空,这个方法没有公开,在作用域 VelocityContext context = new VelocityContext(); // 往上下文设置值 map.forEach(context::put); context.put("_method", QueryContext.getMethodInfo()); // 输出流 StringWriter writer = new StringWriter(); // 转换输出 Velocity.evaluate(context, writer, logTag, tpl); return writer.toString(); }
Example 7
Source File: HelpController.java From JDeSurvey with GNU Affero General Public License v3.0 | 6 votes |
@Secured({"ROLE_ADMIN","ROLE_SURVEY_ADMIN"}) @RequestMapping(produces = "text/html") public String getHelpPage(Model uiModel) { try { StringWriter sw = new StringWriter(); VelocityContext velocityContext = new VelocityContext(); Velocity.evaluate(velocityContext, sw, "velocity-log" , surveySettingsService.velocityTemplate_findById(HELP_VELOCITY_TEMPLATE_ID).getDefinition()); uiModel.addAttribute("helpContent", sw.toString().trim()); return "help/index"; } catch (Exception e) { log.error(e.getMessage(),e); throw (new RuntimeException(e)); } }
Example 8
Source File: MethodInvocationExceptionTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
/** * Runs the test : * * uses the Velocity class to eval a string * which accesses a method that throws an * exception. * @throws Exception */ public void testNormalMethodInvocationException () throws Exception { String template = "$woogie.doException() boing!"; VelocityContext vc = new VelocityContext(); vc.put("woogie", this ); StringWriter w = new StringWriter(); try { Velocity.evaluate( vc, w, "test", template ); fail("No exception thrown"); } catch( MethodInvocationException mie ) { log("Caught MIE (good!) :" ); log(" reference = " + mie.getReferenceName() ); log(" method = " + mie.getMethodName() ); Throwable t = mie.getCause(); log(" throwable = " + t ); if( t instanceof Exception) { log(" exception = " + t.getMessage() ); } } }
Example 9
Source File: MethodInvocationExceptionTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
public void testGetterMethodInvocationException () throws Exception { VelocityContext vc = new VelocityContext(); vc.put("woogie", this ); StringWriter w = new StringWriter(); /* * second test - to ensure that methods accessed via get+ construction * also work */ String template = "$woogie.foo boing!"; try { Velocity. evaluate( vc, w, "test", template ); fail("No exception thrown, second test."); } catch( MethodInvocationException mie ) { log("Caught MIE (good!) :" ); log(" reference = " + mie.getReferenceName() ); log(" method = " + mie.getMethodName() ); Throwable t = mie.getCause(); log(" throwable = " + t ); if( t instanceof Exception) { log(" exception = " + t.getMessage() ); } } }
Example 10
Source File: BaseEntityRenderer.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
@Override public String render(IApsEntity entity, String velocityTemplate, String langCode, boolean convertSpecialCharacters) { String renderedEntity = null; List<TextAttributeCharReplaceInfo> conversions = null; try { if (convertSpecialCharacters) { conversions = this.convertSpecialCharacters(entity, langCode); } Context velocityContext = new VelocityContext(); EntityWrapper entityWrapper = this.getEntityWrapper(entity); entityWrapper.setRenderingLang(langCode); velocityContext.put(this.getEntityWrapperContextName(), entityWrapper); I18nManagerWrapper i18nWrapper = new I18nManagerWrapper(langCode, this.getI18nManager()); velocityContext.put("i18n", i18nWrapper); StringWriter stringWriter = new StringWriter(); boolean isEvaluated = Velocity.evaluate(velocityContext, stringWriter, "render", velocityTemplate); if (!isEvaluated) { throw new ApsSystemException("Rendering error"); } stringWriter.flush(); renderedEntity = stringWriter.toString(); } catch (Throwable t) { _logger.error("Rendering error. entity {}", entity.getTypeCode(), t); //ApsSystemUtils.logThrowable(t, this, "render", "Rendering error"); renderedEntity = ""; } finally { if (convertSpecialCharacters && null != conversions) { this.replaceSpecialCharacters(conversions); } } return renderedEntity; }
Example 11
Source File: BaseDataObjectRenderer.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
@Override public String render(DataObject dataobject, long modelId, String langCode, RequestContext reqCtx) { String renderedEntity = null; List<TextAttributeCharReplaceInfo> conversions = null; try { conversions = this.convertSpecialCharacters(dataobject, langCode); String contentModel = this.getModelShape(modelId); Context velocityContext = new VelocityContext(); DataObjectWrapper contentWrapper = (DataObjectWrapper) this.getEntityWrapper(dataobject); contentWrapper.setRenderingLang(langCode); contentWrapper.setReqCtx(reqCtx); velocityContext.put(this.getEntityWrapperContextName(), contentWrapper); I18nManagerWrapper i18nWrapper = new I18nManagerWrapper(langCode, this.getI18nManager()); velocityContext.put("i18n", i18nWrapper); SystemInfoWrapper systemInfoWrapper = new SystemInfoWrapper(reqCtx); velocityContext.put("info", systemInfoWrapper); StringWriter stringWriter = new StringWriter(); boolean isEvaluated = Velocity.evaluate(velocityContext, stringWriter, "render", contentModel); if (!isEvaluated) { throw new ApsSystemException("Error rendering DataObject"); } stringWriter.flush(); renderedEntity = stringWriter.toString(); } catch (Throwable t) { _logger.error("Error rendering dataobject", t); renderedEntity = ""; } finally { if (null != conversions) { this.replaceSpecialCharacters(conversions); } } return renderedEntity; }
Example 12
Source File: IntrospectionCacheDataTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
public void testCache() throws ParseErrorException, MethodInvocationException, ResourceNotFoundException, IOException { CacheHitCountingVelocityContext context = new CacheHitCountingVelocityContext(); context.put("this", this); StringWriter w = new StringWriter(); Velocity.evaluate(context, w, "test", "$this.exec('a')$this.exec('b')"); assertEquals("[a][b]", w.toString()); assertTrue(context.cacheHit > 0); }
Example 13
Source File: VelocityHelper.java From spacewalk with GNU General Public License v2.0 | 5 votes |
/** * render the template according to what we've added to addMatch * @param template the template * @return the rendered template * @throws Exception e */ public String renderTemplate(String template) throws Exception { StringWriter writer = new StringWriter(); StringReader reader = new StringReader(template); Velocity.evaluate(context, writer, "a", reader); return writer.toString(); }
Example 14
Source File: StringUtil.java From heisenberg with Apache License 2.0 | 5 votes |
public static void main(String[] args) { // System.out.println(substring(crc32("123123123123123"), -3, -1)); String s = "<person>121212:/aaa/bbb"; VelocityContext context = new VelocityContext(); Writer writer = new StringWriter(); // //Pattern.compile("^[0-9a-fA-F]+$") Velocity.evaluate(context, writer, StringUtil.EMPTY, "$!Pattern.compile(\"^[0-9a-fA-F]+$\")"); System.out.println(writer.toString()); System.out.println(substring(s, s.indexOf(">") + 1, s.indexOf(":"))); // $!stringUtil.substring($PARENT_PATH, $!stringUtil.indexOf($PARENT_PATH,">") + 1, // $!stringUtil.indexOf($PARENT_PATH,":")) // $!stringUtil.substring }
Example 15
Source File: VelocityUsage.java From Android_Code_Arbiter with GNU Lesser General Public License v3.0 | 5 votes |
public void allSignatures(InputStream inputStream, Reader fileReader, String template) throws FileNotFoundException { VelocityContext context = new VelocityContext(); StringWriter swOut = new StringWriter(); Velocity.evaluate(context, swOut, "test", inputStream); Velocity.evaluate(context, swOut, "test", fileReader); Velocity.evaluate(context, swOut, "test", template); }
Example 16
Source File: MethodInvocationExceptionTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
public void testSetterMethodInvocationException () throws Exception { VelocityContext vc = new VelocityContext(); vc.put("woogie", this ); StringWriter w = new StringWriter(); String template = "#set($woogie.foo = 'lala') boing!"; try { Velocity. evaluate( vc, w, "test", template ); fail("No exception thrown, set test."); } catch( MethodInvocationException mie ) { log("Caught MIE (good!) :" ); log(" reference = " + mie.getReferenceName() ); log(" method = " + mie.getMethodName() ); Throwable t = mie.getCause(); log(" throwable = " + t ); if( t instanceof Exception) { log(" exception = " + t.getMessage() ); } } }
Example 17
Source File: MethodInvocationExceptionTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
/** * test that no exception is thrown when in parameter to macro. * This is the way we expect the system to work, but it would be better * to throw an exception. * @throws Exception */ public void testMacroInvocationException () throws Exception { VelocityContext vc = new VelocityContext(); vc.put("woogie", this ); StringWriter w = new StringWriter(); String template = "#macro (macro1 $param) $param #end #macro1($woogie.getFoo())"; try { Velocity. evaluate( vc, w, "test", template ); fail("No exception thrown, macro invocation test."); } catch( MethodInvocationException mie ) { log("Caught MIE (good!) :" ); log(" reference = " + mie.getReferenceName() ); log(" method = " + mie.getMethodName() ); Throwable t = mie.getCause(); log(" throwable = " + t ); if( t instanceof Exception) { log(" exception = " + t.getMessage() ); } } catch( Exception e) { fail("Wrong exception thrown, test of exception within macro parameter"); } }
Example 18
Source File: LoginController.java From JDeSurvey with GNU Affero General Public License v3.0 | 4 votes |
@RequestMapping(method = RequestMethod.POST, value = "/", params = "flogin", produces = "text/html") public String forgotLoginPost(@RequestParam(value = "email", required = true) String email, @RequestParam(value = "_proceed", required = false) String proceed, Model uiModel,HttpServletRequest httpServletRequest) { try { log.info("post"); if(proceed != null){ //Proceed User user = userService.user_findByEmail(email); if (user !=null) { StringWriter sw = new StringWriter(); Map model = new HashMap(); model.put(messageSource.getMessage(LOGIN_PARAMETER_NAME, null, LocaleContextHolder.getLocale()).replace("${", "").replace("}", ""), user.getLogin()); VelocityContext velocityContext = new VelocityContext(model); Velocity.evaluate(velocityContext, sw, "velocity-log" , surveySettingsService.velocityTemplate_findById(FORGOT_LOGIN_VELOCITY_EMAIL_TEMPLATE_ID).getDefinition()); mailService.sendEmail(email, messageSource.getMessage(FORGOT_LOGIN_EMAIL_TITLE, null, LocaleContextHolder.getLocale()), sw.toString().trim()); uiModel.addAttribute("status", "S"); return "public/flogin"; } else { log.info("no match"); uiModel.addAttribute("status", "I"); return "public/flogin"; } } else{ //Cancel button return "public/login"; } } catch (Exception e) { log.error(e.getMessage(),e); throw (new RuntimeException(e)); } }
Example 19
Source File: LoginController.java From JDeSurvey with GNU Affero General Public License v3.0 | 4 votes |
@SuppressWarnings("unchecked") @RequestMapping(method = RequestMethod.POST, value = "/", params = "fpass", produces = "text/html") public String forgotPasswordPost(@RequestParam(value = "login", required = true) String login, @RequestParam(value = "dob", required = true) String dob, @RequestParam(value = "_proceed", required = false) String proceed, Model uiModel,HttpServletRequest httpServletRequest) { try { if(proceed != null){ String resetPasswordLink; String dateFormat = messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale()); //Validate date and login entries (sanitize) if (login == null || login.isEmpty() || login.length() > 100 || dob == null || dob.isEmpty() || !GenericValidator.isDate(dob,dateFormat, true)) { uiModel.addAttribute("status", "I"); return "public/fpass"; } //Check if provided DOB and login match if (!userService.user_validateDateofBirthAndLogin(login,DateValidator.getInstance().validate(dob))) { uiModel.addAttribute("status", "I"); return "public/fpass"; } User user = userService.user_findByLogin(login); if (httpServletRequest.getRequestURI().contains("external")) { //resetPasswordLink =messageSource.getMessage(EXTERNAL_SITE_BASE_URL, null, LocaleContextHolder.getLocale()); resetPasswordLink = externalBaseUrl; } else { //resetPasswordLink =messageSource.getMessage(INTERNAL_SITE_BASE_URL, null, LocaleContextHolder.getLocale()); resetPasswordLink = internalBaseUrl; } if (resetPasswordLink.endsWith("/")) {resetPasswordLink = resetPasswordLink +"public/rpass?key=";} else {resetPasswordLink = resetPasswordLink +"/public/rpass?key=";} StringWriter sw = new StringWriter(); Map model = new HashMap(); model.put(messageSource.getMessage(RESET_PASSWORD_LINK_PARAMETER_NAME, null, LocaleContextHolder.getLocale()).replace("${", "").replace("}", ""), "<a href='"+ resetPasswordLink + userService.user_prepareForgotPasswordMessage(user.getId())+ "'>" + messageSource.getMessage(RESET_PASSWORD_LINK_LABEL, null, LocaleContextHolder.getLocale()) +"</a>"); VelocityContext velocityContext = new VelocityContext(model); Velocity.evaluate(velocityContext, sw, "velocity-log" , surveySettingsService.velocityTemplate_findById(FORGOT_PASSWORD_VELOCITY_EMAIL_TEMPLATE_ID).getDefinition()); mailService.sendEmail(user.getEmail(), messageSource.getMessage(FORGOT_PASSWORD_EMAIL_TITLE, null, LocaleContextHolder.getLocale()), sw.toString()); uiModel.addAttribute("status", "S"); return "public/fpass"; } else { //cancel button return "public/login"; } } catch (Exception e) { log.error(e.getMessage(),e); throw (new RuntimeException(e)); } }
Example 20
Source File: RenderSQLTemplate.java From shark with Apache License 2.0 | 3 votes |
/** * 执行sql.xml内容渲染 * * @param sql * 模板内容 * * @param model * 结果集 * * @exception RenderException * * @return String 渲染后的sql语句 */ public static String render(String template, Map<String, ?> model) { String sql = null; try { VelocityContext velocityContext = new VelocityContext(model); StringWriter result = new StringWriter(); Velocity.evaluate(velocityContext, result, "", template); sql = result.toString().replaceAll("\n", "").replaceAll("\t", ""); } catch (Exception e) { throw new RenderException("render fail"); } return sql; }