private void write() throws IOException { File file = new File(myDirectoryBase, myClientClassSimpleName + ".java"); FileWriter w = new FileWriter(file, false); ourLog.info("Writing file: {}", file.getAbsolutePath()); VelocityContext ctx = new VelocityContext(); ctx.put("packageBase", myPackageBase); ctx.put("className", myClientClassSimpleName); ctx.put("resources", myResources); ctx.put("esc", new EscapeTool()); VelocityEngine v = new VelocityEngine(); v.setProperty("resource.loader", "cp"); v.setProperty("cp.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); v.setProperty("runtime.references.strict", Boolean.TRUE); InputStream templateIs = ResourceGeneratorUsingSpreadsheet.class.getResourceAsStream("/vm/client.vm"); InputStreamReader templateReader = new InputStreamReader(templateIs); v.evaluate(ctx, w, "", templateReader); w.close(); }
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets"); ve.init(); VelocityContext context = new VelocityContext(); init(context, req); Pair<Entity, UserCookie> infoAndCookie = init(context, req); Yaml yaml = new Yaml(); HashMap<String, String> directions = (HashMap<String, String>) yaml.load(((Text) infoAndCookie.x.getProperty("directions")).getValue()); context.put("directions", directions); context.put("school", infoAndCookie.x.getProperty("school")); context.put("location", infoAndCookie.x.getProperty("location")); context.put("address", infoAndCookie.x.getProperty("address")); context.put("esc", new EscapeTool()); close(context, ve.getTemplate("directions.html"), resp); }
/** * Creates a page and sets up the velocity engine to render * * @param request * @param response * @param engine * @param template */ public Page(HttpServletRequest request, HttpServletResponse response, VelocityEngine engine, String template) { this.request = Utils.nonNull(request); this.response = Utils.nonNull(response); this.engine = Utils.nonNull(engine); this.template = Utils.nonNull(template); this.context = new VelocityContext(); this.context.put("esc", new EscapeTool()); this.context.put("session", request.getSession(true)); this.context.put("context", request.getContextPath()); }
/** * Gets an instance of the velocity context * * Add the utility instances that are commonly used in many templates. * * @return the instance */ public static VelocityContext getInstance() { VelocityContext context = new VelocityContext(); context.put("esc", new EscapeTool()); WebUtils utils = new WebUtils(); context.put("utils", utils); return context; }
protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:a") .setHeader("esc", constant(new EscapeTool())) .to("velocity:org/apache/camel/component/velocity/escape.vm"); } }; }
private String processTemplate(String template, VelocityContext context){ context.put("esc", new EscapeTool()); Template temp = velocity.getTemplate(template); // Fetch template into a StringWriter StringWriter writer = new StringWriter(); temp.merge( context, writer ); return writer.toString(); }
protected VelocityContext prepareContext(HttpServletRequest request) { PersistenceManager pm = PMF.get().getPersistenceManager(); ConfigManager configManager = new ConfigManager(pm); String serverName = request.getServerName(); VelocityContext context = new VelocityContext(); context.put("config", configManager); context.put("urlFactory", UrlFactory.getInstance()); context.put("webUtils", WebUtils.getInstance()); context.put("serverName", serverName); context.put("esc", new EscapeTool()); context.put("tools", new HtmlUtils()); context.put("pages", new ArticleManager(pm).findByType(ArticleType.Permanent)); String metaTitle = configManager.getValue(ConfigManager.META_TITLE); String metaKeywords = configManager .getValue(ConfigManager.META_KEYWORDS); String metaDesc = configManager .getValue(ConfigManager.META_DESCRIPTION); context.put("pageTitle", metaTitle); context.put("metaKeywords", metaKeywords); context.put("metaDesc", metaDesc); String feedUrl = "/articles.xml"; if (configManager.valueExists(ConfigManager.FEED_URL)) { feedUrl = configManager.getValue(ConfigManager.FEED_URL); } context.put("feedUrl", feedUrl); context.put("feedDescription", configManager.getValue(ConfigManager.FEED_DESCRIPTION)); return context; }
private void write(ValueSetTm theValueSetTm, File theOutputDirectory, String thePackageBase) throws IOException { if (!theOutputDirectory.exists()) { theOutputDirectory.mkdirs(); } if (!theOutputDirectory.isDirectory()) { throw new IOException(theOutputDirectory + " is not a directory"); } File f = new File(theOutputDirectory, theValueSetTm.getClassName() + ".java"); FileWriter w = new FileWriter(f, false); ourLog.info("Writing file: {}", f.getAbsolutePath()); VelocityContext ctx = new VelocityContext(); ctx.put("valueSet", theValueSetTm); ctx.put("packageBase", thePackageBase); ctx.put("esc", new EscapeTool()); VelocityEngine v = new VelocityEngine(); v.setProperty("resource.loader", "cp"); v.setProperty("cp.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); v.setProperty("runtime.references.strict", Boolean.TRUE); InputStream templateIs = ResourceGeneratorUsingSpreadsheet.class.getResourceAsStream("/vm/valueset.vm"); InputStreamReader templateReader = new InputStreamReader(templateIs); v.evaluate(ctx, w, "", templateReader); w.close(); }
/** * Builds the body of the data provider into JSON form, using all available Commcare configs. * @return the body of the provider, or null if there are no configuration available */ public String generateDataProvider() { Map<String, Object> model = new HashMap<>(); EscapeTool escapeTool = new EscapeTool(); NameTrimmer trimmer = new NameTrimmer(); List<ConfigurationData> configurations = new ArrayList<>(); for (Config config : configService.getConfigs().getConfigs()) { configurations.add(new ConfigurationData(config.getName(), schemaService.getFormsWithApplicationName(config.getName()), schemaService.getCaseTypesWithApplicationName(config.getName()))); } if (configurations.isEmpty()) { // return null in case of no configurations - the provider won't get registered return null; } model.put("configurations", configurations); model.put("unionProperties", getCasePropertiesForGivenCaseType(configurations)); model.put("esc", escapeTool); model.put("trimmer", trimmer); model.put("DisplayNameHelper", DisplayNameHelper.class); StringWriter writer = new StringWriter(); VelocityEngineUtils.mergeTemplate(velocityEngine, COMMCARE_TASK_DATA_PROVIDER, model, writer); String providerJson = writer.toString(); LOGGER.trace("Generated the following tasks data provider: {}", providerJson); return providerJson; }
public static VelocityContext getContext() { VelocityContext context = new VelocityContext(); EscapeTool escapeTool = new EscapeTool(); context.put( "escape", escapeTool ); return context; }
public VelocityManager() { velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); velocityEngine.init(); escapeTool = new EscapeTool(); }
@Override public Pair<Entity, UserCookie> init(VelocityContext context, HttpServletRequest req) throws UnsupportedEncodingException { Pair<Entity, UserCookie> infoAndCookie = super.init(context, req); context.put("error", req.getAttribute("javax.servlet.error.exception")); context.put("errorType", req.getAttribute("javax.servlet.error.exception_type")); context.put("errorMessage", req.getAttribute("javax.servlet.error.message")); context.put("uri", req.getAttribute("javax.servlet.error.request_uri")); context.put("servlet", req.getAttribute("javax.servlet.error.servlet_name")); context.put("diaginfo", RequestPrinter.debugString(req, true).replaceAll("\n", "<br>")); context.put("date", new Date().toString()); context.put("esc", new EscapeTool()); return infoAndCookie; }
private void write(BaseRootType theResource, File theFile, String thePackageBase) throws IOException, MojoFailureException { FileWriter w = new FileWriter(theFile, false); ourLog.info("Writing file: {}", theFile.getAbsolutePath()); ArrayList<String> imports = new ArrayList<String>(); for (String next : myImports) { next = Resource.correctName(next); if (next.contains(".")) { imports.add(next); } else { String string = myLocallyDefinedClassNames.get(next); if (string == null) { imports.add(scanForImportNamesAndReturnFqn(next)); } else { imports.add(thePackageBase + "." + string + "." + next); } } } VelocityContext ctx = new VelocityContext(); ctx.put("includeDescriptionAnnotations", true); ctx.put("packageBase", thePackageBase); ctx.put("hash", "#"); ctx.put("imports", imports); ctx.put("profile", theResource.getProfile()); ctx.put("version", myVersion); ctx.put("versionEnumName", determineVersionEnum().name()); ctx.put("id", StringUtils.defaultString(theResource.getId())); if (theResource.getDeclaringClassNameComplete() != null) { ctx.put("className", theResource.getDeclaringClassNameComplete()); } else { ctx.put("className", (theResource.getName())); } // HumanName} ctx.put("elementName", theResource.getElementName()); ctx.put("classNameComplete", (theResource.getName()) + getFilenameSuffix()); // HumanNameDt ctx.put("shortName", defaultString(theResource.getShortName())); ctx.put("definition", defaultString(theResource.getDefinition())); ctx.put("requirements", defaultString(theResource.getRequirement())); ctx.put("children", theResource.getChildren()); ctx.put("resourceBlockChildren", theResource.getResourceBlockChildren()); ctx.put("childExtensionTypes", ObjectUtils.defaultIfNull(myExtensions, new ArrayList<Extension>())); ctx.put("searchParams", (theResource.getSearchParameters())); ctx.put("searchParamsReference", (theResource.getSearchParametersResource())); ctx.put("searchParamsWithoutComposite", (theResource.getSearchParametersWithoutComposite())); ctx.put("includes", (theResource.getIncludes())); ctx.put("esc", new EscapeTool()); String capitalize = WordUtils.capitalize(myVersion); if ("Dstu".equals(capitalize)) { capitalize="Dstu1"; } ctx.put("versionCapitalized", capitalize); VelocityEngine v = new VelocityEngine(); v.setProperty("resource.loader", "cp"); v.setProperty("cp.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); v.setProperty("runtime.references.strict", Boolean.TRUE); InputStream templateIs = ResourceGeneratorUsingSpreadsheet.class.getResourceAsStream(getTemplate()); InputStreamReader templateReader = new InputStreamReader(templateIs); v.evaluate(ctx, w, "", templateReader); w.close(); }
private void write(TargetType theTarget, ValueSetTm theValueSetTm, File theOutputDirectory, String thePackageBase) throws IOException { if (!theOutputDirectory.exists()) { theOutputDirectory.mkdirs(); } if (!theOutputDirectory.isDirectory()) { throw new IOException(theOutputDirectory + " is not a directory"); } String valueSetName = theValueSetTm.getClassName(); String prefix = myFilenamePrefix; String suffix = myFilenameSuffix; if (theTarget == TargetType.SOURCE) { if (!suffix.endsWith(".java")) { suffix += ".java"; } } String fileName = prefix + valueSetName + suffix; File f = new File(theOutputDirectory, fileName); OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(f, false), "UTF-8"); ourLog.debug("Writing file: {}", f.getAbsolutePath()); VelocityContext ctx = new VelocityContext(); InputStream templateIs = null; ctx.put("valueSet", theValueSetTm); ctx.put("packageBase", thePackageBase); ctx.put("esc", new EscapeTool()); VelocityEngine v = VelocityHelper.configureVelocityEngine(myTemplateFile, myVelocityPath, myVelocityProperties); if (myTemplateFile != null) { templateIs = new FileInputStream(myTemplateFile); } else { String templateName = myTemplate; if (null == templateName) { templateName = "/vm/valueset.vm"; } templateIs = this.getClass().getResourceAsStream(templateName); } InputStreamReader templateReader = new InputStreamReader(templateIs, "UTF-8"); v.evaluate(ctx, w, "", templateReader); w.close(); }
private void preparePage(Page page, Session session) { page.add("viewerName", viewerName); page.add("hideNavigation", !showNav); page.add("userid", session.getUser().getUserId()); page.add("esc", new EscapeTool()); }
public void generateReport(JenkinsView viewData, PrintWriter out, Date startTime) { final List<Job> failedJobs = newArrayList(); failedJobs.addAll(viewData.getFailedJobs()); // sort jobs by build timestamp Collections.sort(failedJobs, new JobByTimestampComparator()); final List<Job> passedJobs = newArrayList(); passedJobs.addAll(viewData.getPassedJobs()); // sort jobs by build timestamp Collections.sort(passedJobs, new JobByTimestampComparator()); final VelocityContext context = new VelocityContext(); context.put("startTime", startTime); final DateTool dateTool = new DateTool(); final Map<String, String> config = new HashMap<String, String>(); config.put("timezone", "Europe/Tallinn"); dateTool.configure(config); context.put("dateTool", dateTool); final NumberTool numberTool = new NumberTool(); numberTool.configure(config); context.put("numberTool", numberTool); final EscapeTool escapeTool = new EscapeTool(); context.put("escapeTool", escapeTool); context.put("view", viewData); context.put("failedJobs", failedJobs); context.put("passedJobs", passedJobs); final StringWriter writer = new StringWriter(); template.merge(context, writer); out.println(writer.toString()); out.flush(); out.close(); }
public VelocityManager(VelocityEngine ve, EscapeTool esc) { velocityEngine = ve; escapeTool = esc; }
/** * Creates a message object with a set of standard parameters * @param entityId * @param userId * @return The message object with many useful parameters */ private MessageDTO initializeMessage(Integer entityId, Integer userId) throws SessionInternalError { MessageDTO retValue = new MessageDTO(); try { UserBL user = new UserBL(userId); ContactBL contact = new ContactBL(); // this user's info contact.set(userId); if (contact.getEntity() != null) { retValue.addParameter("contact", contact.getEntity()); retValue.addParameter("first_name", contact.getEntity().getFirstName()); retValue.addParameter("last_name", contact.getEntity().getLastName()); retValue.addParameter("address1", contact.getEntity().getAddress1()); retValue.addParameter("address2", contact.getEntity().getAddress2()); retValue.addParameter("city", contact.getEntity().getCity()); retValue.addParameter("organization_name", contact.getEntity().getOrganizationName()); retValue.addParameter("postal_code", contact.getEntity().getPostalCode()); retValue.addParameter("state_province", contact.getEntity().getStateProvince()); } if (user.getEntity() != null) { retValue.addParameter("user", user.getEntity()); retValue.addParameter("username", user.getEntity().getUserName()); retValue.addParameter("password", user.getEntity().getPassword()); retValue.addParameter("user_id", user.getEntity().getUserId().toString()); } if (user.getCreditCard() != null) { retValue.addParameter("credit_card", user.getCreditCard()); } // the entity info contact.setEntity(entityId); if (contact.getEntity() != null) { retValue.addParameter("company_contact", contact.getEntity()); retValue.addParameter("company_id", entityId.toString()); retValue.addParameter("company_name", contact.getEntity().getOrganizationName()); } //velocity tools retValue.addParameter("tools-date", new DateTool()); retValue.addParameter("tools-math", new MathTool()); retValue.addParameter("tools-number", new NumberTool()); retValue.addParameter("tools-render", new RenderTool()); retValue.addParameter("tools-escape", new EscapeTool()); retValue.addParameter("tools-resource", new ResourceTool()); retValue.addParameter("tools-alternator", new AlternatorTool()); // retValue.addParameter("tools-valueParser", new ValueParser()); retValue.addParameter("tools-list", new ListTool()); retValue.addParameter("tools-sort", new SortTool()); retValue.addParameter("tools-iterator", new IteratorTool()); //Adding a CCF Field to Email Template if (user.getEntity().getCustomer() != null && user.getEntity().getCustomer().getMetaFields() != null) { for (MetaFieldValue metaFieldValue : user.getEntity().getCustomer().getMetaFields()) { retValue.addParameter(metaFieldValue.getField().getName(), metaFieldValue.getValue()); } } LOG.debug("Retvalue >>>> "+retValue.toString()); LOG.debug("Retvalue partameters >>>> "+retValue.getParameters()); } catch (Exception e) { throw new SessionInternalError(e); } return retValue; }
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets, html/templates"); ve.init(); VelocityContext context = new VelocityContext(); Pair<Entity, UserCookie> infoAndCookie = init(context, req); UserCookie userCookie = infoAndCookie.y; Entity user = userCookie != null ? userCookie.authenticateUser() : null; boolean loggedIn = (boolean) context.get("loggedIn"); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); if (loggedIn && !userCookie.isAdmin()) { context.put("user", user.getProperty("user-id")); context.put("name", user.getProperty("name")); Level level = Level.fromString((String) user.getProperty("schoolLevel")); context.put("levels", Level.values()); context.put("level", level.toString()); context.put("tests", Test.getTests(level)); context.put("subjects", Subject.values()); context.put("Test", Test.class); context.put("Level", Level.class); Query query = new Query("registration").setFilter(new FilterPredicate("email", FilterOperator.EQUAL, user.getProperty("user-id"))); List<Entity> registration = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); context.put("coach", !registration.isEmpty() && registration.get(0).getProperty("registrationType").equals("coach")); Pair<School, Map<Test, Statistics>> schoolAndStats = Retrieve.schoolOverview((String) user.getProperty("school"), level); if (schoolAndStats != null) { context.put("school", schoolAndStats.x); context.put("statistics", schoolAndStats.y); } if (!user.getProperty("school").equals(schoolAndStats.x.getName())) { Map<String, List<String>> schoolGroups = (Map<String, List<String>>) new Yaml().load(((Text) infoAndCookie.x.getProperty(level.toString() + "SchoolGroups")).getValue()); context.put("schoolGroup", schoolGroups.get(schoolAndStats.x.getName())); } context.put("qualifyingCriteria", Retrieve.qualifyingCriteria(infoAndCookie.x)); context.put("date", infoAndCookie.x.getProperty("updated")); context.put("esc", new EscapeTool()); context.put("hideFullNames", false); close(context, ve.getTemplate("schoolScores.html"), resp); } else { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User account required for that operation"); } }