/** * Merge the template with the context. * Can be overridden to customize the behavior. * @param template the template to merge * @param context the Velocity context to use for rendering * @param response servlet response (use this to get the OutputStream or Writer) * @throws Exception if thrown by Velocity * @see org.apache.velocity.Template#merge */ protected void mergeTemplate( Template template, Context context, HttpServletResponse response) throws Exception { try { template.merge(context, response.getWriter()); } catch (MethodInvocationException ex) { Throwable cause = ex.getWrappedThrowable(); throw new NestedServletException( "Method invocation failed during rendering of Velocity view with name '" + getBeanName() + "': " + ex.getMessage() + "; reference [" + ex.getReferenceName() + "], method '" + ex.getMethodName() + "'", cause==null ? ex : cause); } }
@Override public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { String value = (String) node.jjtGetChild(0).value(context); String character = (String) node.jjtGetChild(1).value(context); int len = value.length(); StringBuilder sb = new StringBuilder(len); sb.append(value.charAt(0)); for (int i = 1; i < len; i++) { char c = value.charAt(i); if (Character.isUpperCase(c)) { sb.append(character).append(Character.toLowerCase(c)); } else { sb.append(c); } } writer.write(sb.toString()); return true; }
@Override public WAL wal(String topicsDir, TopicPartition topicPart) { try { Class<? extends WAL> walClass = (Class<? extends WAL>) Class .forName(config.getString(S3SinkConnectorConfig.WAL_CLASS_CONFIG)); if (walClass.equals(DummyWAL.class)) { return new DummyWAL(); } else { Constructor<? extends WAL> ctor = walClass.getConstructor(String.class, TopicPartition.class, Storage.class, HdfsSinkConnectorConfig.class); return ctor.newInstance(topicsDir, topicPart, this, config); } } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | MethodInvocationException | InstantiationException | IllegalAccessException e) { throw new ConnectException(e); } }
@Override public boolean render(RenderHandler handler) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException { String src = handler.getStringParameter(0); String base = handler.getRequest().getContextPath(); // 判断是否启用图片域名 if (Global.getImageDomain()) { base = Global.getImageHost(); } StringBuffer buf = new StringBuffer(); buf.append(base); buf.append(src); handler.write(buf.toString()); return true; }
@Override public boolean render(RenderHandler handler) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException { ServletRequest request = handler.getRequest(); // request 获取参数 String ord = ServletRequestUtils.getStringParameter(request, "ord", Consts.order.NEWEST); int pn = ServletRequestUtils.getIntParameter(request, "pn", 1); // 标签中获取参数 int groupId = handler.getIntParameter(0); String alias = handler.getStringParameter(1); Paging paging = wrapPaing(pn); Paging result = postPlanet.paging(paging, groupId, ord); handler.put(alias, result); handler.doRender(); postRender(handler.getContext()); return true; }
public boolean render(InternalContextAdapter ctx, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { // get the bean ValueStack stack = (ValueStack) ctx.get("stack"); HttpServletRequest req = (HttpServletRequest) stack.getContext().get(ServletActionContext.HTTP_REQUEST); HttpServletResponse res = (HttpServletResponse) stack.getContext().get(ServletActionContext.HTTP_RESPONSE); Component bean = getBean(stack, req, res); Container container = (Container) stack.getContext().get(ActionContext.CONTAINER); container.inject(bean); // get the parameters Map params = createPropertyMap(ctx, node); bean.copyParams(params); //bean.addAllParameters(params); bean.start(writer); if (getType() == BLOCK) { Node body = node.jjtGetChild(node.jjtGetNumChildren() - 1); body.render(ctx, writer); } bean.end(writer, ""); return true; }
@Override public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { int argsNum = node.jjtGetNumChildren(); for(int step = 0 ; step < argsNum; step++) { SimpleNode simpleNode = (SimpleNode) node.jjtGetChild(step); Object argObject = simpleNode.value(context); //传入参数 if(argObject instanceof String) { System.out.println((String)argObject); writer.write((String)argObject); writer.flush(); } } return true; }
/** * Return the String representation of the template rendered using Velocity. * * @param context context use to render the template * @param templateFileName file name of the template in the classpath * @throws TemplateRenderException if there is an error with the template */ public static String renderTemplate(String templateFileName, VelocityContext context) throws TemplateRenderException { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); StringWriter sw = new StringWriter(); try { ve.mergeTemplate(templateFileName, "UTF-8", context, sw); } catch (ResourceNotFoundException | ParseErrorException | MethodInvocationException e) { throw new TemplateRenderException("Error rendering template file: " + templateFileName, e); } return sw.toString(); }
private Set<String> prepareVelocityTemplate(String template) throws PIPException { VelocityContext vctx = new VelocityContext(); EventCartridge vec = new EventCartridge(); VelocityParameterReader reader = new VelocityParameterReader(); vec.addEventHandler(reader); vec.attachToContext(vctx); try { Velocity.evaluate(vctx, new StringWriter(), "LdapResolver", template); } catch (ParseErrorException pex) { throw new PIPException("Velocity template preparation failed", pex); } catch (MethodInvocationException mix) { throw new PIPException("Velocity template preparation failed", mix); } catch (ResourceNotFoundException rnfx) { throw new PIPException("Velocity template preparation failed", rnfx); } if (this.logger.isTraceEnabled()) { this.logger.trace("(" + id + ") " + template + " with parameters " + reader.parameters); } return reader.parameters; }
private String evaluateVelocityTemplate(String template, final Map<String, PIPRequest> templateParameters, final PIPFinder pipFinder) throws PIPException { StringWriter out = new StringWriter(); VelocityContext vctx = new VelocityContext(); EventCartridge vec = new EventCartridge(); VelocityParameterWriter writer = new VelocityParameterWriter(pipFinder, templateParameters); vec.addEventHandler(writer); vec.attachToContext(vctx); try { Velocity.evaluate(vctx, out, "LdapResolver", template); } catch (ParseErrorException pex) { throw new PIPException("Velocity template evaluation failed", pex); } catch (MethodInvocationException mix) { throw new PIPException("Velocity template evaluation failed", mix); } catch (ResourceNotFoundException rnfx) { throw new PIPException("Velocity template evaluation failed", rnfx); } this.logger.warn("(" + id + ") " + " template yields " + out.toString()); return out.toString(); }
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { //render content StringWriter content = new StringWriter(); node.jjtGetChild(0).render(context, content); //compress try { writer.write(htmlCompressor.compress(content.toString())); } catch (Exception e) { writer.write(content.toString()); String msg = "Failed to compress content: "+content.toString(); log.error(msg, e); throw new RuntimeException(msg, e); } return true; }
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { //render content StringWriter content = new StringWriter(); node.jjtGetChild(0).render(context, content); //compress try { writer.write(xmlCompressor.compress(content.toString())); } catch (Exception e) { writer.write(content.toString()); String msg = "Failed to compress content: "+content.toString(); log.error(msg, e); throw new RuntimeException(msg, e); } return true; }
public String evaluate(Map<String, Object> context, TemplatePack templatePack, Template template) throws IOException { StringWriter sw = new StringWriter(); try { engine.evaluate(new VelocityContext(context), sw, template.getName(), template.getTemplate()); return sw.toString(); } catch (ParseErrorException parseException) { handleStopFileGeneration(parseException); log.error("In " + templatePack.getName() + ":" + template.getName() + " template, parse exception " + parseException.getMessage(), parseException.getCause()); displayLinesInError(parseException, templatePack, template); throw new IllegalStateException(); } catch (MethodInvocationException mie) { handleStopFileGeneration(mie); log.error("In " + templatePack.getName() + ":" + mie.getTemplateName() + " method [" + mie.getMethodName() + "] has not been set", mie.getCause()); displayLinesInError(mie, templatePack, template); throw mie; } finally { closeQuietly(sw); } }
public boolean render( InternalContextAdapter context, Writer writer, org.apache.velocity.runtime.parser.node.Node node ) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { String var = node.jjtGetChild( 0 ).getFirstToken().image.substring( 1 ); Node document = ( Node ) node.jjtGetChild( 1 ).value( context ); String xpath = String.valueOf( node.jjtGetChild( 2 ).value( context ) ); XPath xPath = XPathFactory.newInstance().newXPath(); try { Node element = ( Node ) xPath.evaluate( xpath, document, XPathConstants.NODE ); if( element != null ) if( TEXT_NODES.contains( element.getNodeType() ) ) context.put( var, element.getTextContent() ); else context.put( var, element ); else log.warn( "for " + xpath + " nothing found" ); } catch( XPathExpressionException e ) { throw new IOException( "cannot evaluate xpath: " + e.getMessage() ); } return true; }
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { if(node.jjtGetNumChildren() != 1){ throw new RuntimeException(getName() + " only and must accept one parameter!") ; } Object param2 = node.jjtGetChild(0).value(context) ; //如果为null,则什么都不输出。 if(param2 != null){ String param = String.valueOf(param2) ; param = StringUtil.replaceStringIgnoreCase(param, "<script", "< script") ; param = StringUtil.replaceStringIgnoreCase(param, "</script", "</ script") ; writer.append(param) ; } return true; }
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { Object value = node.jjtGetChild(0).value(context); boolean isEmpty = false ; if(value == null){ isEmpty = true ; }else{ if(value instanceof String){ isEmpty = StringUtil.isEmpty((String) value) ; }else if(value instanceof Collection){ isEmpty = ((Collection) value).isEmpty() ; }else if(value.getClass().isArray()){ isEmpty = Array.getLength(value) > 0 ; } } if (isEmpty) { Node content = node.jjtGetChild(1); content.render(context, writer); } return true; }
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { if(node.jjtGetNumChildren() != 2){ throw new RuntimeException(getName() + " accepts 2 parameters. The first is a boolean value indicating whether or not to add this conditon; the second is a List containing your conditions!") ; } Boolean test = (Boolean) node.jjtGetChild(0).value(context) ; if(Boolean.FALSE.equals(test)){ //ignore this condition. return true ; } Collection conditions = (Collection) node.jjtGetChild(1).value(context) ; BoundaryChain chain = (BoundaryChain) context.get(GuzzBoundaryDirective.BOUNDARY_CONTEXT_NAME) ; if(chain == null){ throw new ParseErrorException(getName() + " must be resided inside a guzzBoundary directive.") ; } chain.addLimitConditions(conditions) ; return true; }
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { Object value = node.jjtGetChild(0).value(context); boolean isEmpty = false ; if(value == null){ isEmpty = true ; }else{ if(value instanceof String){ isEmpty = StringUtil.isEmpty((String) value) ; }else if(value instanceof Collection){ isEmpty = ((Collection) value).isEmpty() ; }else if(value.getClass().isArray()){ isEmpty = Array.getLength(value) > 0 ; } } if (!isEmpty) { Node content = node.jjtGetChild(1); content.render(context, writer); } return true; }
@Override public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { Node bodyNode = getBodyNode(context, node); if (AsynchronousContain.isAsyncConext()) { StringWriter sw = new StringWriter(); bodyNode.render(context, sw); PipelineTask task = (PipelineTask) context .get(PipelineTask.ATTR_KEY); task.addJsCode(sw.toString()); } else { writer.write("<script type=\"text/javascript\">\r\n"); bodyNode.render(context, writer); writer.write("</script>\r\n"); } return true; }
/** * Renders the template and writes the output to the given file. * * Strips all trailing whitespace before writing to file. */ public void write(File outputFile) throws IOException { StringWriter stringWriter = new StringWriter(); try { engine.mergeTemplate(template, "UTF-8", context, stringWriter); } catch (ResourceNotFoundException|ParseErrorException|MethodInvocationException e) { throw new IOException(e); } stringWriter.close(); String[] lines = stringWriter.toString().split(System.getProperty("line.separator")); try (FileWriter fileWriter = new FileWriter(outputFile)) { for (String line : lines) { // Strip trailing whitespace then append newline before writing to file. fileWriter.write(line.replaceFirst("\\s+$", "") + "\n"); } } }
/** * 根据模板名字和编码完成Velocity模板对象的创建工作 * * @param templateName * @param encoding * @return * @throws ResourceNotFoundException * @throws ParseErrorException * @throws MethodInvocationException * @throws Exception */ protected Template getTemplate(String templateName, String encoding) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, Exception { String name = parseTemplateName(templateName); if (FrameworkEngine.getWebConfig().isDebug()) return RuntimeSingleton.getTemplate(name, encoding);// 若为Debug状态,则每次都重新载入模板 String templatePath = (String) Velocity .getProperty("file.resource.loader.path"); java.io.File f = new java.io.File(new java.io.File(templatePath), name); Template template = (Template) templateCache.get(name);// 先从Cache中读取模板文件 // 这里得进一步完善,当用户已经更改模板文件后,需要能够自动加载,同时增加Cache数量的限制 if (template == null || (f.exists() && f.lastModified() > template.getLastModified())) synchronized (templateCache) { { logger.info(I18n.getLocaleMessage("core.web.template.file.reloads") + name); template = RuntimeSingleton.getTemplate(name, encoding);// name templateCache.put(name, template); } } return template; }
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { //setting default params String moneyValue = null; //reading params if (node.jjtGetChild(0) != null) { moneyValue = node.jjtGetChild(0).value(context) == null ? null : String.valueOf(node.jjtGetChild(0).value(context)); } //truncate and write result to writer writer.write(moneyUAH(moneyValue)); return true; }
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { //setting default params String ukrValue = null; //reading params if (node.jjtGetChild(0) != null) { ukrValue = node.jjtGetChild(0).value(context) == null ? null : String.valueOf(node.jjtGetChild(0).value(context)); } if (ukrValue == null) { return false; } //truncate and write result to writer writer.write(UkrainianToLatin.generateLat(ukrValue)); return true; }
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { //setting default params String moneyValue = null; //reading params if (node.jjtGetChild(0) != null) { moneyValue = String.valueOf(node.jjtGetChild(0).value(context)); } //truncate and write result to writer writer.write(moneyToStrUAH(moneyValue)); return true; }
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { //setting default params String dateValue = null; //reading params if (node.jjtGetChild(0) != null) { dateValue = String.valueOf(node.jjtGetChild(0).value(context)); } //truncate and write result to writer writer.write(date(dateValue)); return true; }
public static void writeForm(Writer writer, String destination, String relayState, String encodedResponse) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException { LOGGER .entering(VelocityUtil.class.getName(), "writeForm", new Object[] { writer, destination, relayState, encodedResponse }); VelocityContext context = new VelocityContext(); context.put("destination", destination); context.put("encodedResponse", encodedResponse); context.put("relayState", relayState); FORM_TEMPLATE.merge(context, writer); writer.flush(); LOGGER.exiting(VelocityUtil.class.getName(), "writeForm"); }
public static Storage createStorage(Class<? extends Storage> storageClass, Configuration conf, String url) { try { Constructor<? extends Storage> ctor = storageClass.getConstructor(Configuration.class, String.class); return ctor.newInstance(conf, url); } catch (NoSuchMethodException | InvocationTargetException | MethodInvocationException | InstantiationException | IllegalAccessException e) { throw new ConnectException(e); } }
@Override public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { List placeList=(List) context.get("placeList"); if(placeList==null){ return true; } Object value=node.jjtGetChild(0).value(context); placeList.add(value); writer.write("?"); return true; }
@Override public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { String value = (String) node.jjtGetChild(0).value(context); String result = value.replaceFirst(value.substring(0, 1), value.substring(0, 1).toLowerCase()); writer.write(result); return true; }
@Override public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { String clazz = (String) node.jjtGetChild(0).value(context); if (context.containsKey(clazz)) { String packagePath = context.get(clazz).toString(); packagePath = new StringBuilder("import ").append(packagePath).append(";\n").toString(); writer.write(packagePath); return true; } return false; }
@Override public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { String prefix = (String) node.jjtGetChild(0).value(context); String str = (String) node.jjtGetChild(1).value(context); String suffix = (String) node.jjtGetChild(2).value(context); writer.write(String.valueOf(prefix + str + suffix)); return true; }
@Override public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { String value = (String) node.jjtGetChild(0).value(context); String result = value.replaceFirst(value.substring(0, 1), value.substring(0, 1).toUpperCase()); writer.write(result); return true; }
public static Storage createStorage(Class<? extends Storage> storageClass, HdfsSinkConnectorConfig config, Configuration conf, String url) { try { Constructor<? extends Storage> ctor = null; if(storageClass == S3Storage.class) { ctor = storageClass.getConstructor(Configuration.class, HdfsSinkConnectorConfig.class, String.class); return ctor.newInstance(conf, config, url); } else { ctor = storageClass.getConstructor(Configuration.class, String.class); return ctor.newInstance(conf, url); } } catch (NoSuchMethodException | InvocationTargetException | MethodInvocationException | InstantiationException | IllegalAccessException e) { throw new ConnectException(e); } }
@Test @Ignore // This works with Velocity 1.6.2 public void testSimpleRenderWithError() throws Exception { thrown.expect(NestedServletException.class); thrown.expect(new TypeSafeMatcher<Exception>() { @Override public boolean matchesSafely(Exception item) { return item.getCause() instanceof MethodInvocationException; } @Override public void describeTo(Description description) { description.appendText("exception has cause of MethodInvocationException"); } }); VelocityConfigurer vc = new VelocityConfigurer(); vc.setPreferFileSystemAccess(false); vc.setVelocityPropertiesMap(Collections.<String,Object>singletonMap("runtime.references.strict", "true")); VelocityEngine ve = vc.createVelocityEngine(); VelocityView view = new VelocityView(); view.setBeanName("myView"); view.setUrl("org/springframework/web/servlet/view/velocity/error.vm"); view.setVelocityEngine(ve); view.setApplicationContext(wac); Map<String,Object> model = new HashMap<String,Object>(); model.put("command", new TestBean("juergen", 99)); view.render(model, request, response); }
@Override public boolean render(RenderHandler handler) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException { long value = handler.getLongParameter(0); Object out = value; if (value > 1000) { out = value / 1000 + "k"; } else if (value > 10000) { out = value / 10000 + "m"; } handler.write(out.toString()); return true; }
@Get("html") public Representation getCollectorsHtml() throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException, Exception{ List<Map<String, Object>> agents = getCollectorsJson(); VelocityContext ctx = new VelocityContext(); ctx.put("agents",agents); StringWriter writer = new StringWriter(); Velocity.getTemplate("agentsStatusResource.vm").merge(ctx, writer); return new StringRepresentation(writer.toString(), MediaType.TEXT_HTML); }
/** * <p> * Create a Map of properties that the user has passed in. For example: * </p> * * <pre> * #xxx("name=hello" "value=world" "template=foo") * </pre> * * <p> * would yield a params that contains {["name", "hello"], ["value", "world"], ["template", "foo"]} * </p> * @param contextAdapter the context adapter * @param node the Node passed in to the render method * @return a Map of the user specified properties * @throws org.apache.velocity.exception.ParseErrorException * if the was an error in the format of the property */ protected Map createPropertyMap(InternalContextAdapter contextAdapter, Node node) throws ParseErrorException, MethodInvocationException { Map propertyMap; int children = node.jjtGetNumChildren(); if (getType() == BLOCK) { children--; } // Velocity supports an on-the-fly Map-definition syntax that leads // to more readable and faster code: // // #url({'id':'url', 'action':'MyAction'}) // // We support this syntax by checking for a single Map argument // to any directive and using that as the property map instead // of building one from individual name-value pair strings. Node firstChild = null; Object firstValue = null; if(children == 1 && null != (firstChild = node.jjtGetChild(0)) && null != (firstValue = firstChild.value(contextAdapter)) && firstValue instanceof Map) { propertyMap = (Map)firstValue; } else { propertyMap = new HashMap(); for (int index = 0, length = children; index < length; index++) { this.putProperty(propertyMap, contextAdapter, node.jjtGetChild(index)); } } return propertyMap; }