Java Code Examples for org.apache.velocity.VelocityContext

The following examples show how to use org.apache.velocity.VelocityContext. These examples are extracted from open source projects. 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: olingo-odata4   Source File: AbstractPOJOGenMojo.java    License: Apache License 2.0 6 votes vote down vote up
protected void parseObj(
    final File base,
    final boolean append,
    final String pkg,
    final String name,
    final String out,
    final Map<String, Object> objs)
    throws MojoExecutionException {

  final VelocityContext ctx = newContext();
  ctx.put("package", pkg);

  if (objs != null) {
    for (Map.Entry<String, Object> obj : objs.entrySet()) {
      if (StringUtils.isNotBlank(obj.getKey()) && obj.getValue() != null) {
        ctx.put(obj.getKey(), obj.getValue());
      }
    }
  }

  final Template template = Velocity.getTemplate(name + ".vm");
  writeFile(out, base, ctx, template, append);
}
 
Example 2
Source Project: takes   Source File: RsVelocity.java    License: MIT License 6 votes vote down vote up
/**
 * Render it.
 * @param folder Template folder
 * @param template Page template
 * @param params Params for velocity
 * @return Page body
 * @throws IOException If fails
 */
private static InputStream render(final String folder,
    final InputStream template,
    final Map<String, Object> params) throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (Writer writer = new WriterTo(baos)) {
        final VelocityEngine engine = new VelocityEngine();
        engine.setProperty(
            "file.resource.loader.path",
            folder
        );
        engine.evaluate(
            new VelocityContext(params),
            writer,
            "",
            new ReaderOf(template)
        );
    }
    return new ByteArrayInputStream(baos.toByteArray());
}
 
Example 3
Source Project: hollow   Source File: DiffObjectPage.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void setUpContext(HttpServletRequest req, HollowUISession session, VelocityContext ctx) {
    String type = req.getParameter("type");
    int fromOrdinal = Integer.parseInt(req.getParameter("fromOrdinal"));
    int toOrdinal = Integer.parseInt(req.getParameter("toOrdinal"));

    int fieldIdx = -1;
    if(req.getParameter("fieldIdx") != null)
        fieldIdx = Integer.parseInt(req.getParameter("fieldIdx"));

    ctx.put("typeName", type);
    ctx.put("fromOrdinal", fromOrdinal);
    ctx.put("toOrdinal", toOrdinal);

    HollowObjectView diffView = diffUI.getHollowObjectViewProvider().getObjectView(req, session);

    HollowDiffHtmlKickstarter htmlKickstarter = new HollowDiffHtmlKickstarter(diffUI.getBaseURLPath());

    ctx.put("initialHtml", htmlKickstarter.initialHtmlRows(diffView));

    ctx.put("breadcrumbs", getBreadcrumbs(type, fieldIdx, fromOrdinal, toOrdinal));
}
 
Example 4
Source Project: difido-reports   Source File: DefaultMailPlugin.java    License: Apache License 2.0 6 votes vote down vote up
private String populateTemplate(String templateName) {
	VelocityEngine ve = new VelocityEngine();
	ve.init();
	Template t = ve.getTemplate(templateName);
	/* create a context and add data */
	VelocityContext context = new VelocityContext();
	String host = System.getProperty("server.address");
	if (null == host) {
		host = "localhost";
	}
	String port = System.getProperty("server.port");
	if (null == port) {
		port = "8080";
	}
	context.put("host", host);
	context.put("port", port);
	context.put("meta", getMetadata());
	final StringWriter writer = new StringWriter();
	t.merge(context, writer);
	return writer.toString();
}
 
Example 5
Source Project: jfinalQ-gencode   Source File: QUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 生成代码 by velocity
 * @param map		变量
 * @param destPath	目的地址
 * @param destFile	目的文件名
 * @param tmpPath	模版地址
 * @param tmpFile	模版文件名
 * @return
 */
public static boolean generateCodeByVelocity(Map<String, Object> map, String destPath, String destFile, String tmpPath, String tmpFile){
	try {
		// 1.初始化
		Properties properties = new Properties();
		properties.put("file.resource.loader.path", tmpPath);  
		properties.put("input.encoding", "UTF-8");
		properties.put("output.encoding", "UTF-8");
		Velocity.init(properties);
		VelocityContext context = new VelocityContext(map);
			
		// 2.生成代码
		FileUtil.mkdir(destPath);
		BufferedWriter sw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(destPath, destFile)), "UTF-8"));
		Velocity.getTemplate(tmpFile).merge(context, sw);
		sw.flush();
		sw.close();
		
		return true;
	} catch (Exception e) {
		e.printStackTrace();
		return false;
	}
}
 
Example 6
Source Project: olat   Source File: MailITCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test for the mail template and the context variable methods
 */
@Test
public void testMailAttachmentsInvalid() {
    String subject = "Subject: Hello $firstname with attachment";
    String body = "Body: \n\n Hey $login, here's a file for you: ";

    // some attachemnts - but no file
    File[] attachments = new File[1];

    MailTemplate template = new MailTemplate(subject, body, null, attachments) {
        @Override
        public void putVariablesInMailContext(VelocityContext context, OLATPrincipal principal) {
            // Put user variables
            context.put("firstname", principal.getAttributes().getFirstName());
            context.put("login", principal.getName());
        }
    };

    // some recipients data
    List<OLATPrincipal> recipients = new ArrayList<OLATPrincipal>();
    recipients.add(id1);

    MailerResult result = new MailerResult();
    result = MailerWithTemplate.getInstance().sendMailAsSeparateMails(recipients, null, null, template, id2);
    assertEquals(MailerResult.ATTACHMENT_INVALID, result.getReturnCode());
}
 
Example 7
public void testLogResult()
    throws Exception
{
    VelocityContext context = new VelocityContext();
    Template template = Velocity.getTemplate("macros.vm");

    // try to get only messages during merge
    logger.startCapture();
    template.merge(context, new StringWriter());
    logger.stopCapture();

    String resultLog = logger.getLog();
    if ( !isMatch(resultLog, COMPARE_DIR, "velocity.log", "cmp"))
    {
        String compare = getFileContents(COMPARE_DIR, "velocity.log", CMP_FILE_EXT);

        String msg = "Log output was incorrect\n"+
            "-----Result-----\n"+ resultLog +
            "----Expected----\n"+ compare +
            "----------------";

        fail(msg);
    }
}
 
Example 8
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 9
Source Project: jeewx   Source File: QywxGroupMsgController.java    License: 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 10
Source Project: olat   Source File: PwChangeController.java    License: Apache License 2.0 6 votes vote down vote up
private MailerResult sendEmail(final UserRequest ureq, Identity identity, TemporaryKey tk) {
    final String ip = ureq.getHttpReq().getRemoteAddr();
    final String today = DateFormat.getDateInstance(DateFormat.LONG, ureq.getLocale()).format(new Date());
    // mailer configuration
    final String serverpath = Settings.getServerContextPathURI();
    final String servername = ureq.getHttpReq().getServerName();
    if (log.isDebugEnabled()) {
        log.debug("this servername is " + servername + " and serverpath is " + serverpath, null);
    }
    final Translator userTrans = PackageUtil.createPackageTranslator(PwChangeController.class, ureq.getLocale());
    String body = userTrans.translate("pwchange.intro", new String[] { identity.getName() })
            + userTrans.translate("pwchange.body", new String[] { serverpath, tk.getRegistrationKey(), I18nManager.getInstance().getLocaleKey(ureq.getLocale()) })
            + SEPARATOR + userTrans.translate("reg.wherefrom", new String[] { serverpath, today, ip });
    String subject = userTrans.translate("pwchange.subject");
    final MailTemplate mailTempl = new MailTemplate(subject, body, MailTemplateHelper.getMailFooter(ureq.getIdentity(), null), null) {
        @Override
        public void putVariablesInMailContext(final VelocityContext context, final OLATPrincipal recipient) {
            // nothing to do
        }
    };

    final MailerResult result = MailerWithTemplate.getInstance().sendMail(identity, null, null, mailTempl, null);
    return result;
}
 
Example 11
Source Project: jeewx   Source File: AlipayNewsitemController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 跳转到编辑页面
 * @return
 */
@RequestMapping(params="goMessage",method = RequestMethod.GET)
public void goMessage(@RequestParam(required = true, value = "templateId" ) String templateId,HttpServletResponse response,HttpServletRequest request) throws Exception{
		 VelocityContext velocityContext = new VelocityContext();
		 List<AlipayNewsitem> headerList = alipayNewsitemDao.getAlipayNewsitemByTemplateId(templateId);
		 if(headerList.size()>0){
			 velocityContext.put("headerNews", headerList.get(0));
				if(headerList.size()>1){
					ArrayList list = new ArrayList(headerList);
					list.remove(0);
					velocityContext.put("newsList", list);
				}
			} 
		 AlipayNewstemplate alipayNewstemplate = alipayNewstemplateDao.get(templateId);
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		 if(alipayNewstemplate.getCreateDate()!=null){
			 velocityContext.put("addtime", sdf.format(alipayNewstemplate.getCreateDate()));
		 }
		 String viewName = "alipay/sucai/alipayNewsitem-showmessage.vm";
		 ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 12
Source Project: urule   Source File: ScorecardEditorServletHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String method=retriveMethod(req);
	if(method!=null){
		invokeMethod(method, req, resp);
	}else{
		VelocityContext context = new VelocityContext();
		context.put("contextPath", req.getContextPath());
		String file=req.getParameter("file");
		String project = buildProjectNameFromFile(file);
		if(project!=null){
			context.put("project", project);
		}
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		Template template=ve.getTemplate("html/scorecard-editor.html","utf-8");
		PrintWriter writer=resp.getWriter();
		template.merge(context, writer);
		writer.close();
	}
}
 
Example 13
Source Project: heisenberg   Source File: StringUtil.java    License: Apache License 2.0 5 votes vote down vote up
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 14
Source Project: jeewx   Source File: QywxGroupController.java    License: Apache License 2.0 5 votes vote down vote up
/**
  * 详情
  * @return
  */
@RequestMapping(params="toDetail",method = RequestMethod.GET)
public void qywxGroupDetail(@RequestParam(required = true, value = "id" ) String id,HttpServletResponse response,HttpServletRequest request)throws Exception{
		VelocityContext velocityContext = new VelocityContext();
		String viewName = "qywx/base/qywxGroup-detail.vm";
		QywxGroup qywxGroup = qywxGroupDao.get(id);
		velocityContext.put("qywxGroup",qywxGroup);
		ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 15
Source Project: sc-generator   Source File: VelocityUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String writerGeneratorConfig(String url, String username, String password, String driverClass,
		String packagePath, String targetPath, List<String> tables) throws IOException, SQLException {
	VelocityContext ctx = new VelocityContext();
	Template template = getTempate("templates/generatorConfig.vm");
	ctx.put("url", url);
	ctx.put("username", username);
	ctx.put("password", password);
	ctx.put("driverClass", driverClass);
	ctx.put("tables", tables);

	Map<String, String> primaryKeys = new HashMap<>();

	Connection connection = DriverManager.getConnection(url, username, password);
	for (String tableName : tables) {
		String primaryKey = TblUtil.getPrimaryKey(connection, tableName);
		String key = toHump(primaryKey);
		primaryKeys.put(tableName, key);
	}
	ctx.put("primaryKeys", primaryKeys);
	List<String> models = new ArrayList<String>();
	for (String table : tables) {
		String modelName = tableNameConvertModelName(table);
		models.add(modelName);
	}
	ctx.put("models", models);
	ctx.put("packagePath", packagePath);
	ctx.put("targetPath", targetPath);
	StringWriter writer = new StringWriter();
	template.merge(ctx, writer);
	writer.flush();
	writer.close();
	return writer.toString();
}
 
Example 16
Source Project: jeewx-boot   Source File: CmsAdController.java    License: 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();
		 CmsAd cmsAd = cmsAdService.queryById(id);
		 velocityContext.put("cmsAd",cmsAd);
		 velocityContext.put("mainId", request.getParameter("mainId"));
		 String viewName = "cms/back/cmsAd-edit.vm";
		 ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 17
Source Project: quartz-glass   Source File: VelocityTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void merge() {
    Context context = new VelocityContext();
    context.put("message", "hi");

    Assert.assertEquals("hi", merge("/org/n3r/quartz/glass/velocity/velocity-test.vm", context));
}
 
Example 18
Source Project: jeewx-boot   Source File: CmsArticleController.java    License: Apache License 2.0 5 votes vote down vote up
/**
  * 详情
  * @return
  */
@RequestMapping(value="toDetail",method = RequestMethod.GET)
public void cmsArticleDetail(@RequestParam(required = true, value = "id" ) String id,HttpServletResponse response,HttpServletRequest request)throws Exception{
		VelocityContext velocityContext = new VelocityContext();
		String viewName = "cms/back/cmsArticle-detail.vm";
		CmsArticle cmsArticle = cmsArticleService.queryById(id);
		velocityContext.put("cmsArticle",cmsArticle);
		ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 19
Source Project: jeewx-boot   Source File: JwSystemUserJwidController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 跳转到添加页面
 * @return
 */
@RequestMapping(value = "/toAdd",method ={RequestMethod.GET, RequestMethod.POST})
public void toAddDialog(String userId,HttpServletRequest request,HttpServletResponse response,ModelMap model)throws Exception{
	 VelocityContext velocityContext = new VelocityContext();
	 velocityContext.put("userId", userId);
	 List<WeixinAccountDto> jwidList = jwWebJwidService.queryJwidsNotInUser(userId);
	 velocityContext.put("jwids", jwidList);
	 String viewName = "system/back/jwSystemUserJwid-add.vm";
	 ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 20
Source Project: jeewx-boot   Source File: JwSystemRoleController.java    License: 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 21
Source Project: ruoyiplus   Source File: GenServiceImpl.java    License: MIT License 5 votes vote down vote up
private Map generatorAdvCodeOnlyWeb(
        String tmplName, TableInfo table, List<ColumnInfo> columns, Map<String, String[]> params) {
    Map retMap = new HashMap();
    // 设置主键
    table.setPrimaryKey(table.getColumnsLast());
    // 设置表格的访问地址
    table.setUri(Convert.toStr(GenUtils.getParam(params, "uri"), "system/unknown"));
    VelocityInitializer.initVelocity();

    String packageName = GenUtils.getParam(params, "package");
    String moduleName = GenUtils.getParam(params, "module");
    table.setModule(moduleName);

    String genJava = Convert.toStr(GenUtils.getParam(params, "gen-java"), "0");
    String genHtml = Convert.toStr(GenUtils.getParam(params, "gen-html"), "0");
    TableInfo.GenStyle genStyle = TableInfo.GenStyle.All;
    if (genJava.equals("1") && genHtml.equals("0")) {
        genStyle = TableInfo.GenStyle.Java;
    } else if (genHtml.equals("1") && genJava.equals("0")) {
        genStyle = TableInfo.GenStyle.Web;
    }
    VelocityContext context = GenUtils.getVelocityContext(table, packageName);

    // 获取模板列表
    List<String> templates = GenUtils.getTemplatesWeb(genStyle, tmplName);
    return putIntoMap(retMap, context, templates);
}
 
Example 22
private String applyGistTemplate(GHGist gist, GHGistFile gistFile, boolean firstGistFile) {
    final VelocityContext context = new VelocityContext();
    context.put("gist", gist);
    context.put("gistFile", gistFile);
    context.put("renderDescription", firstGistFile && useGistDescription);
    final StringWriter templateWriter = new StringWriter();
    template.merge(context, templateWriter);
    return templateWriter.toString();
}
 
Example 23
/**
 * Initializes Velocity engine
 */
private void init() {
       velocityEngine.setProperty(VelocityEngine.RESOURCE_LOADER, "class");
       velocityEngine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
       setLogFile();

       DateTool dateTool = new DateTool();
       dateTool.configure(this.configMap);
       MathTool mathTool = new MathTool();
       NumberTool numberTool = new NumberTool();
       numberTool.configure(this.configMap);
       SortTool sortTool = new SortTool();
       
       defaultContext = new VelocityContext();
       defaultContext.put("dateTool", dateTool);
       defaultContext.put("dateComparisonTool", new ComparisonDateTool());
       defaultContext.put("mathTool", mathTool);
       defaultContext.put("numberTool", numberTool);
       defaultContext.put("sortTool", sortTool);
       // Following tools need VelocityTools version 2.0+
       //defaultContext.put("displayTool", new DisplayTool());
       //defaultContext.put("xmlTool", new XmlTool());
       
       try {
		velocityEngine.init();
	} catch (Exception e) {
		throw new VelocityException(e);
	}
}
 
Example 24
Source Project: CodeGen   Source File: DefaultProviderImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void create(CodeTemplate template, CodeContext context, Map<String, Object> extraMap){

    VelocityContext velocityContext = new VelocityContext(BuilderUtil.transBean2Map(context));
    velocityContext.put("serialVersionUID", BuilderUtil.computeDefaultSUID(context.getModel(), context.getFields()));
    // $!dateFormatUtils.format($!now,'yyyy-MM-dd')
    velocityContext.put("dateFormatUtils", new org.apache.commons.lang.time.DateFormatUtils());
    if (extraMap != null && extraMap.size() > 0) {
        for (Map.Entry<String, Object> entry: extraMap.entrySet()) {
            velocityContext.put(entry.getKey(), entry.getValue());
        }
    }

    String fileName = VelocityUtil.evaluate(velocityContext, template.getFilename());
    String subPath = VelocityUtil.evaluate(velocityContext, template.getSubPath());
    String temp = VelocityUtil.evaluate(velocityContext, template.getTemplate());

    WriteCommandAction.runWriteCommandAction(this.project, () -> {
        try {
            VirtualFile vFile = VfsUtil.createDirectoryIfMissing(outputPath);
            PsiDirectory psiDirectory = PsiDirectoryFactory.getInstance(this.project).createDirectory(vFile);
            PsiDirectory directory = subDirectory(psiDirectory, subPath, template.getResources());
            // TODO: 这里干啥用的, 没用的话是不是可以删除了
            if (JavaFileType.INSTANCE == this.languageFileType) {
                PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(directory);
                if (psiPackage != null && !StringUtils.isEmpty(psiPackage.getQualifiedName())) {
                    extraMap.put(fileName, new StringBuilder(psiPackage.getQualifiedName()).append(".").append(fileName));
                }
            }
            createFile(project, directory, fileName + "." + this.languageFileType.getDefaultExtension(), temp, this.languageFileType);
        } catch (Exception e) {
            LOGGER.error(StringUtils.getStackTraceAsString(e));
        }
    });
}
 
Example 25
Source Project: olat   Source File: IQEditReplaceWizard.java    License: Apache License 2.0 5 votes vote down vote up
private void doStep3(final UserRequest ureq) {
    final StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(Settings.getServerContextPathURI());
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(course, true);
    stringBuilder.append("/url/RepositoryEntry/").append(re.getKey());
    stringBuilder.append("/CourseNode/").append(courseNode.getIdent());

    final String[] bodyArgs = new String[] { course.getCourseTitle(), stringBuilder.toString() };

    final String subject = translate("inform.users.subject", bodyArgs);
    final String body = translate("inform.users.body", bodyArgs);

    final MailTemplate mailTempl = new MailTemplate(subject, body, MailTemplateHelper.getMailFooter(null, ureq.getIdentity()), null) {
        @Override
        @SuppressWarnings({ "unused" })
        public void putVariablesInMailContext(final VelocityContext context, final OLATPrincipal identity) {
            // nothing to do
        }
    };

    removeAsListenerAndDispose(mailCtr);
    mailCtr = new MailNotificationEditController(getWindowControl(), ureq, mailTempl, false);
    listenTo(mailCtr);

    vcStep3 = createVelocityContainer("replacewizard_step3");
    vcStep3.put("mailform", mailCtr.getInitialComponent());
    setNextWizardStep(translate("replace.wizard.title.step3"), vcStep3);
}
 
Example 26
Source Project: jeewx-boot   Source File: JwSystemUserController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 分配公众号
 * @return
 * @throws Exception 
 */
@RequestMapping(value="toJwidTree",method = RequestMethod.GET)
public void toPrivilegeTree(@RequestParam(required = true, value = "id" ) Long id,HttpServletResponse response,HttpServletRequest request) throws Exception{
		 VelocityContext velocityContext = new VelocityContext();
		 JwSystemUser jwSystemuser = jwSystemUserService.queryById(id);
		 velocityContext.put("jwSystemuser",jwSystemuser);
		 String viewName = "system/back/jwSystemUser-jwidtree.vm";
		 ViewVelocity.view(request,response,viewName,velocityContext);
}
 
Example 27
Source Project: erp-framework   Source File: Generator.java    License: MIT License 5 votes vote down vote up
public void generateServiceImpl(String targetDir, Table table) {
    VelocityEngine velocityEngine = createVelocityEngine();
    VelocityContext context = createContext(table);
    Writer writer = createWriter(targetDir, configure.getServiceImplPackage()
            .replace(".", "/") + "/" + table.getBeanName() + "ServiceImpl.java");
    Template t = velocityEngine.getTemplate("serviceImplTemplate.vm");

    t.merge(context, writer);
    flushWriter(writer);
}
 
Example 28
Source Project: olat   Source File: SelectionController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create default template which fill in context 'firstname' , 'lastname' and 'username'.
 * 
 * @param subject
 * @param body
 * @return
 */
private MailTemplate createMailTemplate(final String subject, final String body, final Identity sender) {
    return new MailTemplate(subject, body, MailTemplateHelper.getMailFooter(null, sender), null) {
        @Override
        public void putVariablesInMailContext(final VelocityContext context, final OLATPrincipal principal) {
            context.put("firstname", principal.getAttributes().getFirstName());
            context.put("lastname", principal.getAttributes().getLastName());
            context.put("username", principal.getName());
        }
    };
}
 
Example 29
Source Project: hollow   Source File: HistoryOverviewPage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void setUpContext(HttpServletRequest req, HollowUISession session, VelocityContext ctx) {
    List<HistoryOverviewRow> rows = getHistoryOverview();
    
    ctx.put("overviewDisplayHeaders", ui.getOverviewDisplayHeaders());
    ctx.put("overviewRows", rows);
}
 
Example 30
public void writeWebappBeansGenerate(VelocityContext context,
        Template temp) throws IOException {
    StringWriter wr = new StringWriter();
    temp.merge(context, wr);
    File beansWebappFile = new File(vpc.getDestinationFolder()
            + "/src/main/resources/conf/context/"
            + vpc.getReferential().replace(".", "").toLowerCase()
            + "/web-app/"
            + vpc.getReferential().replace(".", "").toLowerCase()
            + "-beans-webapp.xml");
    FileUtils.writeStringToFile(beansWebappFile, wr.toString());
}