Java Code Examples for org.apache.velocity.VelocityContext#put()

The following examples show how to use org.apache.velocity.VelocityContext#put() . 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: InvalidEventHandlerTestCase.java    From velocity-engine with Apache License 2.0 7 votes vote down vote up
/**
 * Test deeper structures
 * @param ve
 * @param vc
 * @throws Exception
 */
private void doTestInvalidReferenceEventHandler4(VelocityEngine ve, VelocityContext vc)
throws Exception
{
    VelocityContext context = new VelocityContext(vc);

    Tree test = new Tree();
    test.setField("10");
    Tree test2 = new Tree();
    test2.setField("12");
    test.setChild(test2);

    context.put("tree",test);
    String s;
    Writer w;

    // show work fine
    s = "$tree.Field $tree.field $tree.child.Field";
    w = new StringWriter();
    ve.evaluate(context, w, "mystring", s);

    s = "$tree.x $tree.field.x $tree.child.y $tree.child.Field.y";
    w = new StringWriter();
    ve.evaluate(context, w, "mystring", s);

}
 
Example 2
Source File: TemplateUtil.java    From WePush with MIT License 6 votes vote down vote up
public static String evaluate(String content, VelocityContext velocityContext) {

        if (content.contains("NICK_NAME")) {
            WxMpService wxMpService = WxMpTemplateMsgSender.getWxMpService();
            String nickName = "";
            try {
                nickName = wxMpService.getUserService().userInfo(velocityContext.get(PushControl.TEMPLATE_VAR_PREFIX + "0").toString()).getNickname();
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
            velocityContext.put("NICK_NAME", nickName);
        }

        velocityContext.put("ENTER", "\n");

        StringWriter writer = new StringWriter();
        velocityEngine.evaluate(velocityContext, writer, "", content);

        return writer.toString();
    }
 
Example 3
Source File: ReportBuilder.java    From custom-bytecode-analyzer with GNU General Public License v3.0 6 votes vote down vote up
private static List<String> generateHtmlChunks(List<ReportItem> reportItemList) {
  List<String> htmlChunks = new ArrayList<>();

  VelocityEngine velocityEngine = new VelocityEngine();
  Properties p = new Properties();
  p.setProperty("resource.loader", "class");
  p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
  velocityEngine.init(p);
  Template template = velocityEngine.getTemplate("template/report_template.html");

  int maxItemsInReport = CliHelper.getMaxItemsInReport();
  List<List<ReportItem>> reportItemsChunks = Lists.partition(reportItemList, maxItemsInReport);

  for (List<ReportItem> reportItemsChunk : reportItemsChunks ) {
    VelocityContext velocityContext = new VelocityContext();
    velocityContext.put("jarPath", CliHelper.getPathToAnalyze());
    velocityContext.put("ruleName", reportItemsChunk.get(0).getRuleName());
    velocityContext.put("reportItems", reportItemsChunk);

    StringWriter stringWriter = new StringWriter();
    template.merge(velocityContext, stringWriter);
    htmlChunks.add(stringWriter.toString());
  }
  return htmlChunks;
}
 
Example 4
Source File: IndexController.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public void sendTestMail() {
    VelocityContext context = new VelocityContext();
    context.put("name", "Dunwu");
    context.put("hint", "欢迎使用Velocity邮件模板:");

    // 直接传入一个对象
    context.put("date", new Date());

    // 传入一个Vector
    Hyperlink item1 = new Hyperlink("百度首页", "https://www.baidu.com");
    Hyperlink item2 = new Hyperlink("网易首页", "http://www.163.com/");
    List<Hyperlink> list = new ArrayList<>();
    list.add(item1);
    list.add(item2);
    context.put("links", list);
    context.put("logo", "https://raw.githubusercontent.com/dunwu/images/master/common/dunwu-logo-200.png");

    MailDTO mailDTO = new MailDTO();
    mailDTO.setTo(new String[] { mailUrl });
    mailDTO.setSubject("TEST MAIL");
    String text = VelocityUtil.getMergeOutput(context, "templates/velocity/default/mail.vm");
    mailDTO.setText(text);
    mailService.sendMimeMessage(mailDTO);
}
 
Example 5
Source File: AlipayMenuController.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
	  * 列表页面
	  * @return
	  */
	@RequestMapping(params = "list",method = {RequestMethod.GET,RequestMethod.POST})
	public void list(@ModelAttribute AlipayMenu query,HttpServletRequest request,HttpServletResponse response,
			@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
			@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
			try {
			 	LOG.info(request, "alipayMenu back list");
			 	VelocityContext velocityContext = new VelocityContext();
			 	velocityContext.put("alipayMenu",query);
//			 	---update---begin---author:chhenchuenpeng----date:20161114---for:给菜单数据重新排序------
			 	//分页数据
		 		//MiniDaoPage<AlipayMenu> list =  alipayMenuDao.getAll(query,pageNo,pageSize);
		 		//velocityContext.put("pageInfos",SystemTools.convertPaginatedList(list));
			 	velocityContext.put("pageInfos",menuService.queryAll());
//			 	---update---end---author:chhenchuenpeng----date:20161114---for:给菜单数据重新排序------
				String viewName = "alipay/account/alipayMenu-list.vm";
				ViewVelocity.view(request,response,viewName,velocityContext);
			} catch (Exception e) {
				e.printStackTrace();
			}
}
 
Example 6
Source File: QywxGroupMsgController.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
 * 跳转到编辑页面
 * @return
 */
@RequestMapping(params="toGroupMsgSend",method ={RequestMethod.GET, RequestMethod.POST})
public void toGroupMsgSend(@ModelAttribute QywxGroup group , HttpServletResponse response, HttpServletRequest request) throws Exception{
		 VelocityContext velocityContext = new VelocityContext();
		 List<QywxAgent> agentList= qywxAgentDao.getAllQywxAgents();
		 velocityContext.put("agentList", agentList);
		 //分组展示
		 List<QywxGroup> list =qywxGroupDao.getAllQywxpid();
		 
		//页面图片显示的路径
		 String yuming=ConfigUtil.getProperty("domain");
		 velocityContext.put("yuming", yuming);
		 velocityContext.put("list", list);
		 String viewName = "qywx/msg/groupMsgSend.vm"; 
		 ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 7
Source File: StringResourceLoaderRepositoryTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
public void setUp() throws Exception
{
    Velocity.reset();
    Velocity.setProperty(Velocity.RESOURCE_LOADERS, "string");
    Velocity.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    Velocity.addProperty("string.resource.loader.modificationCheckInterval", "1");
    Velocity.setProperty(Velocity.RUNTIME_LOG_INSTANCE, new TestLogger());
    Velocity.init();

    StringResourceRepository repo = getRepo(null, null);
    repo.putStringResource("foo", "This is $foo");
    repo.putStringResource("bar", "This is $bar");

    context = new VelocityContext();
    context.put("foo", "wonderful!");
    context.put("bar", "horrible!");
    context.put("woogie", "a woogie");
}
 
Example 8
Source File: JwSystemRoleController.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
  * 列表页面
  * @return
  */
@RequestMapping(value="list",method = {RequestMethod.GET,RequestMethod.POST})
public void list(@ModelAttribute JwSystemRole query,HttpServletResponse response,HttpServletRequest request,
			@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
			@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
	 	PageQuery<JwSystemRole> pageQuery = new PageQuery<JwSystemRole>();
	 	pageQuery.setPageNo(pageNo);
	 	pageQuery.setPageSize(pageSize);
	 	VelocityContext velocityContext = new VelocityContext();
		pageQuery.setQuery(query);
		velocityContext.put("jwSystemRole",query);
		velocityContext.put("pageInfos",SystemTools.convertPaginatedList(jwSystemRoleService.queryPageList(pageQuery)));
		String viewName = "system/back/jwSystemRole-list.vm";
		ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 9
Source File: BuiltInEventHandlerTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Test reporting of invalid syntax
 * @throws Exception
 */
public void testReportNullQuietInvalidReferences() throws Exception
{
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty("event_handler.invalid_references.quiet","true");
    ve.setProperty("event_handler.invalid_references.null","true");
    ReportInvalidReferences reporter = new ReportInvalidReferences();
    ve.init();

    VelocityContext context = new VelocityContext();
    EventCartridge ec = new EventCartridge();
    ec.addEventHandler(reporter);
    ec.attachToContext(context);

    context.put("a1","test");
    context.put("b1","test");
    context.put("n1", null);
    Writer writer = new StringWriter();

    ve.evaluate(context,writer,"test","$a1 $c1 $a1.length() $a1.foobar() $!c1 $n1 $!n1 #if($c1) nop #end");

    List errors = reporter.getInvalidReferences();
    assertEquals(5,errors.size());
    assertEquals("$c1",((InvalidReferenceInfo) errors.get(0)).getInvalidReference());
    assertEquals("$a1.foobar()",((InvalidReferenceInfo) errors.get(1)).getInvalidReference());
    assertEquals("$c1",((InvalidReferenceInfo) errors.get(2)).getInvalidReference());
    assertEquals("$n1",((InvalidReferenceInfo) errors.get(3)).getInvalidReference());
    assertEquals("$n1",((InvalidReferenceInfo) errors.get(4)).getInvalidReference());

    log("Caught invalid references (local configuration).");
}
 
Example 10
Source File: QywxGroupController.java    From jeewx with Apache License 2.0 5 votes vote down vote up
/**
 * 跳转到编辑页面
 * @return
 */
@RequestMapping(params="toEdit",method = RequestMethod.GET)
public void toEdit(@RequestParam(required = true, value = "id" ) String id,HttpServletResponse response,HttpServletRequest request) throws Exception{
		 VelocityContext velocityContext = new VelocityContext();
		 QywxGroup qywxGroup = qywxGroupDao.get(id);
		 velocityContext.put("qywxGroup",qywxGroup);
		 String viewName = "qywx/base/qywxGroup-edit.vm";
		 ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 11
Source File: JwSystemUserController.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 跳转到添加页面
 * @return
 */
@RequestMapping(value = "/toAdd",method ={RequestMethod.GET, RequestMethod.POST})
public void toAddDialog(HttpServletRequest request,HttpServletResponse response,ModelMap model)throws Exception{
	 VelocityContext velocityContext = new VelocityContext();
	 String viewName = "system/back/jwSystemUser-add.vm";
	//查询所有角色
	 List<JwSystemRole> roleList = jwSystemRoleService.queryAllRoleList();
	 velocityContext.put("roleList",roleList);
	 ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 12
Source File: WeixinAutoresponseController.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
  * 详情
  * @return
  */
@RequestMapping(value="toDetail",method = RequestMethod.GET)
public void weixinAutoresponseDetail(@RequestParam(required = true, value = "id" ) String id,HttpServletResponse response,HttpServletRequest request)throws Exception{
		VelocityContext velocityContext = new VelocityContext();
		String viewName = "weixin/back/weixinAutoresponse-detail.vm";
		WeixinAutoresponse weixinAutoresponse = weixinAutoresponseService.queryById(id);
		velocityContext.put("weixinAutoresponse",weixinAutoresponse);
		ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 13
Source File: CustomTitle.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Runs the velocity engine on the script with the provided
 * content for one recipient.
 * 
 * @param titleType one of the valid constants TITLE_* from org.agnitas.util.Title
 * @param gender    the gender of the recipient
 * @param title     his title
 * @param firstname his firstname
 * @param lastname  his lastname
 * @param columns   and all other known database columns for this recipient
 * @param error     optional Buffer to collect error message
 * @return          the output of the velocity script, i.e. the generated title for this recipient
 */
public String makeTitle (int titleType, int gender, String title, String firstname, String lastname, Map <String, String> columns, StringBuffer error) {
	String	rc = null;
	
	logTo = error;
	try {
		VelocityEngine	ve = new VelocityEngine ();
		VelocityContext	vc = new VelocityContext ();
	
		ve.setProperty (VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);
		ve.setProperty (VelocityEngine.VM_LIBRARY, "");
		ve.init ();

		StringWriter	out = new StringWriter ();

		vc.put ("type", titleType);
		vc.put ("gender", gender);
		vc.put ("title", (title == null || titleType == Title.TITLE_FIRST ? "" : title));
		vc.put ("firstname", (firstname == null || titleType == Title.TITLE_DEFAULT ? "" : firstname));
		vc.put ("lastname", (lastname == null || titleType == Title.TITLE_FIRST ? "" : lastname));
		vc.put ("cust", columns);
		ve.evaluate (vc, out, "title", titleText);
		rc = shrink (out.toString ());
	} catch (Exception e) {
		if (error != null) {
			error.append ("CustomTitle: \"" + titleText + "\" leads to " + e.toString () + "\n");
		}
	}
	logTo = null;
	return rc;
}
 
Example 14
Source File: WxActGoldeneggsVerifyController.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 跳转到编辑页面
 * @return
 */
@RequestMapping(value="toEdit",method = RequestMethod.GET)
public void toEdit(@RequestParam(required = true, value = "id" ) String id,HttpServletResponse response,HttpServletRequest request) throws Exception{
		 VelocityContext velocityContext = new VelocityContext();
		 WxActGoldeneggsVerify wxActGoldeneggsVerify = wxActGoldeneggsVerifyService.queryById(id);
		 velocityContext.put("wxActGoldeneggsVerify",wxActGoldeneggsVerify);
		 String actId=request.getParameter("actId");
		 velocityContext.put("ActId",actId);
		 String jwid = wxActGoldeneggsService.queryById(actId).getJwid();
		 velocityContext.put("jwid",jwid);
		 String viewName = "goldeneggs/verify/back/wxActGoldeneggsVerify-edit.vm";
		 ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 15
Source File: SystemController.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 登录前验证并获取分配的微信公众号
 * 
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/preLogin", method = { RequestMethod.GET, RequestMethod.POST })
public void preLogin(String username, String password, HttpServletRequest request, HttpServletResponse response)
		throws Exception {
	VelocityContext velocityContext = new VelocityContext();
	String viewName = "base/back/common/prelogin.vm";
	try {
		// 根据用户名查询系统用户
		LoginUser user = jwSystemUserService.queryUserByUserId(username);
		boolean isAuth = false;
		String passwordEncode = MD5Util.MD5Encode(password, "utf-8");
		// 验证用户信息
		if (user != null) {
			if (passwordEncode != null && passwordEncode.equals(user.getPassword())
					&& Constants.USER_NORMAL_STATE.equals(user.getUserStat())) {
				isAuth = true;
			} else {
				LOG.info("登录验证失败:用户【" + username + "】登录信息验证不通过");
			}
		}
		List<WeixinAccountDto> jwids = new ArrayList<WeixinAccountDto>();
		if (isAuth) {
			// 验证通过,根据userid查询捷微列表
			jwids = jwidService.queryJwWebJwidByUserId(username);
               //update begin Author:zhaofei date:20190822 for:新用户分配默认的公众号,允许登录
			if (jwids.size() <= 0){
				WeixinAccountDto jwid = jwidService.queryJwidNameByJwid(defaultJwid);
				jwids.add(jwid);
			}
               //update end Author:zhaofei date:20190822 for:新用户分配默认的公众号,允许登录
		} else {
			LOG.info("登录验证失败:用户【" + username + "】权限验证不通过");
		}
		velocityContext.put("jwids", jwids);
	} catch (Exception e) {
		e.printStackTrace();
		LOG.info("登录验证失败:用户【" + username + "】" + e.getMessage());
	}
	ViewVelocity.view(request, response, viewName, velocityContext);
}
 
Example 16
Source File: WeixinTmessageSendLogController.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
  * 详情
  * @return
  */
@RequestMapping(value="toDetail",method = RequestMethod.GET)
public void weixinTmessageSendLogDetail(@RequestParam(required = true, value = "id" ) String id,HttpServletResponse response,HttpServletRequest request)throws Exception{
		VelocityContext velocityContext = new VelocityContext();
		String viewName = "tmessage/back/weixinTmessageSendLog-detail.vm";
		WeixinTmessageSendLog weixinTmessageSendLog = weixinTmessageSendLogService.queryById(id);
		velocityContext.put("weixinTmessageSendLog",weixinTmessageSendLog);
		ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 17
Source File: LayoutSourceLink.java    From ngAndroid with Apache License 2.0 5 votes vote down vote up
@Override
public VelocityContext getVelocityContext() {
    VelocityContext vc = new VelocityContext();

    vc.put("layoutName", layoutName);
    vc.put("className", className);
    vc.put("javaName", javaName);
    vc.put("scopes", scopes);
    vc.put("layoutPath", layoutPath);
    vc.put("package", PACKAGE);
    vc.put("packageName", packageName);
    return vc;
}
 
Example 18
Source File: WeixinNewsitemController.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
  * 列表页面
  * @return
  */
@RequestMapping(value="list",method = {RequestMethod.GET,RequestMethod.POST})
public void list(@ModelAttribute WeixinNewsitem query,HttpServletResponse response,HttpServletRequest request,
			@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
			@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
	 	PageQuery<WeixinNewsitem> pageQuery = new PageQuery<WeixinNewsitem>();
	 	pageQuery.setPageNo(pageNo);
	 	pageQuery.setPageSize(pageSize);
	 	VelocityContext velocityContext = new VelocityContext();
		pageQuery.setQuery(query);
		velocityContext.put("weixinNewsitem",query);
		velocityContext.put("pageInfos",SystemTools.convertPaginatedList(weixinNewsitemService.queryPageList(pageQuery)));
		String viewName = "weixin/back/weixinNewsitem-list.vm";
		ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 19
Source File: WeixinReceptMsgController.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
  * 列表页面
  * @return
  */
@RequestMapping(value="list",method = {RequestMethod.GET,RequestMethod.POST})
public void list(@ModelAttribute WeixinReceptMsg query,HttpServletResponse response,HttpServletRequest request,
			@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
			@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
	 	PageQuery<WeixinReceptMsg> pageQuery = new PageQuery<WeixinReceptMsg>();
	 	pageQuery.setPageNo(pageNo);
	 	pageQuery.setPageSize(pageSize);
	 	VelocityContext velocityContext = new VelocityContext();
		pageQuery.setQuery(query);
		velocityContext.put("weixinReceptMsg",query);
		velocityContext.put("pageInfos",SystemTools.convertPaginatedList(weixinReceptMsgService.queryPageList(pageQuery)));
		String viewName = "weixin/back/weixinReceptMsg-list.vm";
		ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 20
Source File: WeixinTexttemplateController.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
  * 列表页面
  * @return
  */
@RequestMapping(value="list",method = {RequestMethod.GET,RequestMethod.POST})
public void list(@ModelAttribute WeixinTexttemplate query,HttpServletResponse response,HttpServletRequest request,
			@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
			@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
	 	PageQuery<WeixinTexttemplate> pageQuery = new PageQuery<WeixinTexttemplate>();
	 	pageQuery.setPageNo(pageNo);
	 	pageQuery.setPageSize(pageSize);
	 	VelocityContext velocityContext = new VelocityContext();
	 	//update-begin--Author:zhangweijian  Date: 20180720 for:添加jwid查询条件
	 	String jwid =  request.getSession().getAttribute("jwid").toString();
	 	query.setJwid(jwid);
	 	//update-begin--Author:zhangweijian  Date: 20180928 for:无权限不能查看公众号数据
	 	//判断是否有权限
		String systemUserid = request.getSession().getAttribute("system_userid").toString();
		//update-begin--Author:zhangweijian  Date: 20181008 for:根据jwid和用户id查询公众号信息
		MyJwWebJwid jw = myJwWebJwidService.queryJwidByJwidAndUserId(jwid,systemUserid);
		//update-end--Author:zhangweijian  Date: 20181008 for:根据jwid和用户id查询公众号信息
		if(jw==null){
	 		query.setJwid("-");
	 	}
	 	//update-end--Author:zhangweijian  Date: 20180928 for:无权限不能查看公众号数据
	 	//update-end--Author:zhangweijian  Date: 20180720 for:添加jwid查询条件
		pageQuery.setQuery(query);
		velocityContext.put("weixinTexttemplate",query);
		velocityContext.put("pageInfos",SystemTools.convertPaginatedList(weixinTexttemplateService.queryPageList(pageQuery)));
		String viewName = "weixin/back/weixinTexttemplate-list.vm";
		ViewVelocity.view(request,response,viewName,velocityContext);
}