/** * @return a new context with some tools initialized. * * @see NumberTool * @see DateTool * @see MathTool */ public static VelocityContext getPrepopulatedVelocityContext() { final NumberTool numberTool = new NumberTool(); final DateTool dateTool = new DateTool(); final MathTool mathTool = new MathTool(); VelocityContext context = new VelocityContext(); context.put("numberTool", numberTool); context.put("dateTool", dateTool); context.put("mathTool", mathTool); context.put("enLocale", Locale.ENGLISH); context.put("service", new ICommonService() { @Override public String getHttpBaseRef() { return BLLManager.getInstance().getConfigManager().getMotuConfig().getHttpBaseRef(); } }); return context; }
/** * Setup report context variables for * graph, buffers, etc. * * @param ctx */ public void setupReportContext(NodeWizardReportContext ctx) { final Map<String, String> buffers = new HashMap<>(); final Map<String, DefaultTableDataSource> tables = new HashMap<>(); for(String bufferName:bufferPanel.getBufferNames()) { final String data = bufferPanel.getBuffer(bufferName).getLogBuffer().getText(); buffers.put(bufferName, data); final DefaultTableDataSource table = bufferPanel.getBuffer(bufferName).getExtension(DefaultTableDataSource.class); if(table != null) { tables.put(bufferName, table); } } ctx.put("Class", Class.class); ctx.put("FormatterUtil", FormatterUtil.class); ctx.put("Math", new MathTool()); ctx.put("ParticipantHistory", ParticipantHistory.class); ctx.put("graph", getGraph()); ctx.put("bufferNames", bufferPanel.getBufferNames()); ctx.put("buffers", buffers); ctx.put("tables", tables); }
/** * Generates the mail message based on the file import status. * * @param importStatus The import status to generate file import mail message. * @return The file import mail message for the status. */ private String makeImportMailMessage(ImportStatus importStatus) { Map<String, Object> model = new HashMap<String, Object>(); model.put("importStatus", importStatus); model.put("dateTool", new DateTool()); model.put("mathTool", new MathTool()); model.put("numberTool", new NumberTool()); model.put("StringUtils", StringUtils.class); try { return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, fileImportMailTemplate, "utf-8", model); } catch (VelocityException ve) { logger.error("Error while making file import mail message", ve); // Use the log text instead... return logImportStatus(importStatus); } }
private void generateHtmlfile(Map<String, Object> input) { try{ VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class",ClasspathResourceLoader.class.getName()); ve.init(); Template template = ve.getTemplate("templates/acmeair-report.vtl"); VelocityContext context = new VelocityContext(); for(Map.Entry<String, Object> entry: input.entrySet()){ context.put(entry.getKey(), entry.getValue()); } context.put("math", new MathTool()); context.put("number", new NumberTool()); context.put("date", new ComparisonDateTool()); Writer file = new FileWriter(new File(searchingLocation + System.getProperty("file.separator") + RESULTS_FILE)); template.merge( context, file ); file.flush(); file.close(); }catch(Exception e){ e.printStackTrace(); } }
/** * 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); } }
@Test public void testExposeHelpers() throws Exception { final String templateName = "test.vm"; WebApplicationContext wac = mock(WebApplicationContext.class); given(wac.getServletContext()).willReturn(new MockServletContext()); final Template expectedTemplate = new Template(); VelocityConfig vc = new VelocityConfig() { @Override public VelocityEngine getVelocityEngine() { return new TestVelocityEngine(templateName, expectedTemplate); } }; Map<String, VelocityConfig> configurers = new HashMap<String, VelocityConfig>(); configurers.put("velocityConfigurer", vc); given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(configurers); // let it ask for locale HttpServletRequest req = mock(HttpServletRequest.class); given(req.getAttribute(View.PATH_VARIABLES)).willReturn(null); given(req.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE)).willReturn(new AcceptHeaderLocaleResolver()); given(req.getLocale()).willReturn(Locale.CANADA); final HttpServletResponse expectedResponse = new MockHttpServletResponse(); VelocityView vv = new VelocityView() { @Override protected void mergeTemplate(Template template, Context context, HttpServletResponse response) throws Exception { assertTrue(template == expectedTemplate); assertTrue(response == expectedResponse); assertEquals("myValue", context.get("myHelper")); assertTrue(context.get("math") instanceof MathTool); assertTrue(context.get("dateTool") instanceof DateTool); DateTool dateTool = (DateTool) context.get("dateTool"); assertTrue(dateTool.getLocale().equals(Locale.CANADA)); assertTrue(context.get("numberTool") instanceof NumberTool); NumberTool numberTool = (NumberTool) context.get("numberTool"); assertTrue(numberTool.getLocale().equals(Locale.CANADA)); } @Override protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception { model.put("myHelper", "myValue"); } }; vv.setUrl(templateName); vv.setApplicationContext(wac); Map<String, Class<?>> toolAttributes = new HashMap<String, Class<?>>(); toolAttributes.put("math", MathTool.class); vv.setToolAttributes(toolAttributes); vv.setDateToolAttribute("dateTool"); vv.setNumberToolAttribute("numberTool"); vv.setExposeSpringMacroHelpers(false); vv.render(new HashMap<String, Object>(), req, expectedResponse); assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, expectedResponse.getContentType()); }
@Test public void testVelocityToolboxView() throws Exception { final String templateName = "test.vm"; StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(new MockServletContext()); final Template expectedTemplate = new Template(); VelocityConfig vc = new VelocityConfig() { @Override public VelocityEngine getVelocityEngine() { return new TestVelocityEngine(templateName, expectedTemplate); } }; wac.getDefaultListableBeanFactory().registerSingleton("velocityConfigurer", vc); final HttpServletRequest expectedRequest = new MockHttpServletRequest(); final HttpServletResponse expectedResponse = new MockHttpServletResponse(); VelocityToolboxView vv = new VelocityToolboxView() { @Override protected void mergeTemplate(Template template, Context context, HttpServletResponse response) throws Exception { assertTrue(template == expectedTemplate); assertTrue(response == expectedResponse); assertTrue(context instanceof ChainedContext); assertEquals("this is foo.", context.get("foo")); assertTrue(context.get("map") instanceof HashMap<?,?>); assertTrue(context.get("date") instanceof DateTool); assertTrue(context.get("math") instanceof MathTool); assertTrue(context.get("link") instanceof LinkTool); LinkTool linkTool = (LinkTool) context.get("link"); assertNotNull(linkTool.getContextURL()); assertTrue(context.get("link2") instanceof LinkTool); LinkTool linkTool2 = (LinkTool) context.get("link2"); assertNotNull(linkTool2.getContextURL()); } }; vv.setUrl(templateName); vv.setApplicationContext(wac); Map<String, Class<?>> toolAttributes = new HashMap<String, Class<?>>(); toolAttributes.put("math", MathTool.class); toolAttributes.put("link2", LinkTool.class); vv.setToolAttributes(toolAttributes); vv.setToolboxConfigLocation("org/springframework/web/servlet/view/velocity/toolbox.xml"); vv.setExposeSpringMacroHelpers(false); vv.render(new HashMap<String,Object>(), expectedRequest, expectedResponse); }
/** * . * * @throws MotuException */ private void listLogFiles(File logFolder) throws MotuException { // Filter all MotuQSLog files xml or csv and display a link to download files String[] fileNames = logFolder.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.matches(".*motuQSlog.*"); } }); List<LogTransaction> logTransactionList = new ArrayList<LogTransaction>(); DateFormat df = new SimpleDateFormat("yyyy.MM.dd HH.mm.ss.SSS"); for (String fileName : fileNames) { File f = new File(logFolder, fileName); double sizeInMBytes = UnitUtils.toMegaBytes(new Double(f.length())); long lastModifiedDate = f.lastModified(); logTransactionList.add(new LogTransaction(fileName, sizeInMBytes, lastModifiedDate, df.format(lastModifiedDate))); } // Sort by date DESC Collections.sort(logTransactionList, new Comparator<LogTransaction>() { @Override public int compare(LogTransaction o1, LogTransaction o2) { return Long.valueOf(o1.getLastModifiedTimeStamp()).compareTo(o2.getLastModifiedTimeStamp()); } }); Collections.reverse(logTransactionList); Map<String, Object> velocityContext = new HashMap<String, Object>(2); velocityContext.put("body_template", VelocityTemplateManager.getTemplatePath(ACTION_NAME, VelocityTemplateManager.DEFAULT_LANG)); velocityContext.put("logTransactionList", logTransactionList); velocityContext.put("logFolder", logFolder); velocityContext.put("math", new MathTool()); String response = VelocityTemplateManager.getInstance().getResponseWithVelocity(velocityContext, null, null); try { writeResponse(response, HTTPUtils.CONTENT_TYPE_HTML_UTF8); } catch (Exception e) { throw new MotuException(ErrorType.SYSTEM, "Error while using velocity template", e); } }
private void doExport_10_Tour( final TourData tourData, final ArrayList<GarminTrack> tracks, final ArrayList<TourWayPoint> wayPoints, final ArrayList<TourMarker> tourMarkers, final GarminLap lap, final String exportFileName) throws IOException { boolean isOverwrite = true; final File exportFile = new File(exportFileName); if (exportFile.exists()) { if (_exportState_IsOverwriteFiles) { // overwrite is enabled in the UI } else { isOverwrite = net.tourbook.ui.UI.confirmOverwrite(_exportState_FileCollisionBehaviour, exportFile); } } if (isOverwrite == false) { return; } final VelocityContext vc = new VelocityContext(); // math tool to convert float into double vc.put("math", new MathTool());//$NON-NLS-1$ if (_isSetup_GPX) { vc.put(VC_IS_EXPORT_ALL_TOUR_DATA, _exportState_GPX_IsExportAllTourData && tourData != null); } else if (_isSetup_TCX) { vc.put("iscourses", _exportState_TCX_IsCourses); //$NON-NLS-1$ vc.put("coursename", _exportState_TCX_CourseName); //$NON-NLS-1$ } vc.put(VC_LAP, lap); vc.put(VC_TRACKS, tracks); vc.put(VC_WAY_POINTS, wayPoints); vc.put(VC_TOUR_MARKERS, tourMarkers); vc.put(VC_TOUR_DATA, tourData); vc.put(VC_HAS_TOUR_MARKERS, Boolean.valueOf(tourMarkers.size() > 0)); vc.put(VC_HAS_TRACKS, Boolean.valueOf(tracks.size() > 0)); vc.put(VC_HAS_WAY_POINTS, Boolean.valueOf(wayPoints.size() > 0)); vc.put("dateformat", _dateFormat); //$NON-NLS-1$ vc.put("dtIso", _dtIso); //$NON-NLS-1$ vc.put("nf1", _nf1); //$NON-NLS-1$ vc.put("nf3", _nf3); //$NON-NLS-1$ vc.put("nf8", _nf8); //$NON-NLS-1$ doExport_20_TourValues(vc); final Writer exportWriter = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(exportFile), UI.UTF_8)); final Reader templateReader = new InputStreamReader(this.getClass().getResourceAsStream(_formatTemplate)); try { Velocity.evaluate(vc, exportWriter, "MyTourbook", templateReader); //$NON-NLS-1$ } catch (final Exception e) { StatusUtil.showStatus(e); } finally { exportWriter.close(); } }
@Test public void testExposeHelpers() throws Exception { final String templateName = "test.vm"; WebApplicationContext wac = mock(WebApplicationContext.class); given(wac.getServletContext()).willReturn(new MockServletContext()); final Template expectedTemplate = new Template(); VelocityConfig vc = new VelocityConfig() { @Override public VelocityEngine getVelocityEngine() { return new TestVelocityEngine(templateName, expectedTemplate); } }; Map<String, VelocityConfig> configurers = new HashMap<String, VelocityConfig>(); configurers.put("velocityConfigurer", vc); given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(configurers); // let it ask for locale HttpServletRequest req = mock(HttpServletRequest.class); given(req.getAttribute(View.PATH_VARIABLES)).willReturn(null); given(req.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE)).willReturn(new AcceptHeaderLocaleResolver()); given(req.getLocale()).willReturn(Locale.CANADA); final HttpServletResponse expectedResponse = new MockHttpServletResponse(); VelocityView vv = new VelocityView() { @Override protected void mergeTemplate(Template template, Context context, HttpServletResponse response) throws Exception { assertTrue(template == expectedTemplate); assertTrue(response == expectedResponse); assertEquals("myValue", context.get("myHelper")); assertTrue(context.get("math") instanceof MathTool); assertTrue(context.get("dateTool") instanceof DateTool); DateTool dateTool = (DateTool) context.get("dateTool"); assertTrue(dateTool.getLocale().equals(Locale.CANADA)); assertTrue(context.get("numberTool") instanceof NumberTool); NumberTool numberTool = (NumberTool) context.get("numberTool"); assertTrue(numberTool.getLocale().equals(Locale.CANADA)); } @Override protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception { model.put("myHelper", "myValue"); } }; vv.setUrl(templateName); vv.setApplicationContext(wac); Map<String, Class> toolAttributes = new HashMap<String, Class>(); toolAttributes.put("math", MathTool.class); vv.setToolAttributes(toolAttributes); vv.setDateToolAttribute("dateTool"); vv.setNumberToolAttribute("numberTool"); vv.setExposeSpringMacroHelpers(false); vv.render(new HashMap<String, Object>(), req, expectedResponse); assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, expectedResponse.getContentType()); }
@Test public void testVelocityToolboxView() throws Exception { final String templateName = "test.vm"; StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(new MockServletContext()); final Template expectedTemplate = new Template(); VelocityConfig vc = new VelocityConfig() { @Override public VelocityEngine getVelocityEngine() { return new TestVelocityEngine(templateName, expectedTemplate); } }; wac.getDefaultListableBeanFactory().registerSingleton("velocityConfigurer", vc); final HttpServletRequest expectedRequest = new MockHttpServletRequest(); final HttpServletResponse expectedResponse = new MockHttpServletResponse(); VelocityToolboxView vv = new VelocityToolboxView() { @Override protected void mergeTemplate(Template template, Context context, HttpServletResponse response) throws Exception { assertTrue(template == expectedTemplate); assertTrue(response == expectedResponse); assertTrue(context instanceof ChainedContext); assertEquals("this is foo.", context.get("foo")); assertTrue(context.get("map") instanceof HashMap<?,?>); assertTrue(context.get("date") instanceof DateTool); assertTrue(context.get("math") instanceof MathTool); assertTrue(context.get("link") instanceof LinkTool); LinkTool linkTool = (LinkTool) context.get("link"); assertNotNull(linkTool.getContextURL()); assertTrue(context.get("link2") instanceof LinkTool); LinkTool linkTool2 = (LinkTool) context.get("link2"); assertNotNull(linkTool2.getContextURL()); } }; vv.setUrl(templateName); vv.setApplicationContext(wac); @SuppressWarnings("unchecked") Map<String, Class> toolAttributes = new HashMap<String, Class>(); toolAttributes.put("math", MathTool.class); toolAttributes.put("link2", LinkTool.class); vv.setToolAttributes(toolAttributes); vv.setToolboxConfigLocation("org/springframework/web/servlet/view/velocity/toolbox.xml"); vv.setExposeSpringMacroHelpers(false); vv.render(new HashMap<String,Object>(), expectedRequest, expectedResponse); }
/** * 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; }