使用groovy循环模板GStringTemplateEngine()(looping a template using groovy GStringTemplateEngine())
我的要求是创建一个模板引擎来支持循环 。
最终的模板应该是这样的:
#cat output.template env: - name : param1 value : 1 - name : param2 value : 2
我有伪代码来解释我的要求
def f = new File('output.template') def engine = new groovy.text.GStringTemplateEngine() def mapping = [ [ name : "param1", value : "1"], [ name : "param2", value : "2" ] ] // This mapping can consists of a multiple key value pairs. def Template = engine.createTemplate(f).make(mapping) println "${Template}"
有人可以帮助我如何实现模板内循环的这种要求,我应该如何修改我的模板?
*更新:
tim_yates
或Eduardo Melzer
提供的所有解决方案tim_yates
在模板末尾添加带空行的输出。 造成这种情况的原因是什么?*解决方案提供商是否无法看到此行为或问题仅限于我的系统?# groovy loop_template.groovy env: - name: param1 value : 1 - name: param2 value : 2 root@instance-1:
My requirement is to create a template engine to support a looping in it.
The final template should look something like this:
#cat output.template env: - name : param1 value : 1 - name : param2 value : 2
I have pseudo code to explain my requirement
def f = new File('output.template') def engine = new groovy.text.GStringTemplateEngine() def mapping = [ [ name : "param1", value : "1"], [ name : "param2", value : "2" ] ] // This mapping can consists of a multiple key value pairs. def Template = engine.createTemplate(f).make(mapping) println "${Template}"
Can someone help me how to achieve this requirement of looping inside the templates and how should I modify my template?
*UPDATE : All the solutions provided by
tim_yates
or byEduardo Melzer
has resulted in following output with extra blank lines at the end of template. What could be the reason for that?* Are the solution providers not able to see this behavior or the issue is my system only?.# groovy loop_template.groovy env: - name: param1 value : 1 - name: param2 value : 2 root@instance-1:
原文:https://stackoverflow.com/questions/49444475
最满意答案
您可以使用JAX-RS API的
HttpHeaders
管理由ExceptionMapper
返回的适当格式,并获取请求实体的MediaType
,请参阅javadoc: http : //docs.oracle.com/javaee/7/api/javax/ws /rs/core/HttpHeaders.html#getMediaType--所以你的代码如下:
@Provider public class GenericExceptionMapper implements ExceptionMapper<Exception> { @Context private HttpHeaders m_headers; private final Logger LOG = LoggerFactory.getLogger(GenericExceptionMapper.class); @Override public Response toResponse(Exception exception) { ErrorResponse errorResponse = new ErrorResponse(exception.getClass().getSimpleName(), exception.getMessage()); if (exception instanceof WebApplicationException) { LOG.error("Type: {}", exception.getClass().getSimpleName()); LOG.error("Message: {}", exception.getMessage()); WebApplicationException webApplicationException = (WebApplicationException) exception; return Response.status(webApplicationException.getResponse().getStatus()).entity(errorResponse).build(); } return Response.serverError().entity(errorResponse).type(m_headers.getMediaType()).build(); } }
In case of custom exceptions which extend
WebApplicationException
such aspublic class MyCustomException extends WebApplicationException
does not require an explicit
ExceptionMapper<MyCustomerException>
for exception handling and response creation.ExceptionMapper can be very helpful to handle exceptions which derive from
Exception
(or its subclasses) but notWebApplicationException
(and its subclasses) (noteWebApplicationException
is also a child class ofException
)For example ExceptionMapper can be used to handle an exception such as
IllegalArgumentException
and creating a response.In both case above the response can be serialized according to the
@Produces
specified on the Resource method.However after looking at the spec implementation of RestEasy I found out, the even for
WebApplicationException
(s), if an ExceptionMapper is@Provided
by the rest service, it will be trigged.resteasy-jaxrs:3.1.0.Final class: ExceptionHandler method: public Response handleException(HttpRequest request, Throwable e) // First try and handle it with a mapper if ((jaxrsResponse = executeExceptionMapper(e)) != null) { return jaxrsResponse; }
So either I make sure that ExceptionMapper is used for some specific Exceptions such as
ExceptionMapper<IllegalArgumentException>
instead of catching all exceptions as shown above in the codeExceptionMapper<Exception>
or simply return the response as shown in the code below:if (exception instanceof WebApplicationException) { WebApplicationException webApplicationException = (WebApplicationException) exception; return webApplicationException.getResponse(); }
The serialization error will not occur. Why? because the framework takes care of this (based on
@Produces
annotation it will serialize the response for NON WebApplicationException based responses. And forWebApplicationException
based response as shown above, framework will take care of the response as well (since ErrorResponse entity was never used)However coming to the problem mentioned in this ticket.
NotAllowedException
occurs in the spec implementation code before the method associated with URI gets executed. Thus the@Produces
annotation doesn't take effect and while Marshalling the response, a default MediaType octet-stream is used.resteasy-jaxrs:3.1.0.Final class: SegmentNode method: public Match match(List<Match> matches, String httpMethod, HttpRequest request)
So while the following exceptions occur; DefaultOptionsMethodException NotAllowedException NotSupportedException NotAcceptableException
request attribute
RESTEASY_CHOSEN_ACCEPT
doesn't get setrequest.setAttribute(RESTEASY_CHOSEN_ACCEPT, sortEntry.getAcceptType()); return sortEntry.match;
and when the server tries to write a response it doesn't find the MediaType (as we never set it while creating a response object)
resteasy-jaxrs:3.1.0.Final class: ServerResponseWriter method: public static void writeNomapResponse(BuiltResponse jaxrsResponse, final HttpRequest request, ... if (jaxrsResponse.getEntity() != null && jaxrsResponse.getMediaType() == null) { setDefaultContentType(request, jaxrsResponse, providerFactory, method); }
It tries to set it from method annotations; which as mentioned before were never set, since the
NotAllowedException
occurred beforeRESTEASY_CHOSEN_ACCEPT
could have been set.It finds a wild card as no accept headers were specified and thus octet stream was set
resteasy-jaxrs:3.1.0.Final class: ServerResponseWriter method: protected static void setDefaultContentType(HttpRequest request, BuiltResponse ... if (chosen.isWildcardType()) { chosen = MediaType.APPLICATION_OCTET_STREAM_TYPE; }
(this a just a summary; for detailed steps I must go back to the spec implementation code)
Thus I must specify a mediatype. This can done looking at the
HttpHeaders
from@Context
to make it dynamic or if nothing is specified in the headers as in my case, I provide a default MediaTypeApplication/XML
for serialization to proceed.Hope this helps someone also facing the same issue.
相关问答
更多-
我无法使用ExceptionMapper 。 我使用ResponseEntityExceptionHandler解决了这个问题。 代码如下: @EnableWebMvc @ControllerAdvice public class ServiceExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(HystrixRuntimeException.class) @ResponseBody ...
-
异常映射器适用于从资源方法主体抛出的异常。 如果您修改资源以抛出TestException : public String updateSometh(@NotNull @QueryParam("key") String key, @QueryParam(value = "somethID") Long somethID) throws TestException { throw new TestException(); } 映射器应该捕获异常。 问题出在你测试的方式上。 E ...
-
您可以使用JAX-RS API的HttpHeaders管理由ExceptionMapper返回的适当格式,并获取请求实体的MediaType ,请参阅javadoc: http : //docs.oracle.com/javaee/7/api/javax/ws /rs/core/HttpHeaders.html#getMediaType-- 所以你的代码如下: @Provider public class GenericExceptionMapper implements ExceptionMapper将预期的类类型更改为com.sun.jersey.api.client.ClientResponse protected ClientResponse executeGet(String path){ WebResource resource = resource().path(path); Builder builder = resource.header("Content-Type", "application/json;charset=UTF-8"); return build ...
Dropwizard的ExceptionMapper需要哪个依赖项?(Which dependency does ExceptionMapper for Dropwizard require?)[2021-11-20]
当你引用dropwizard-core时,应该已经dropwizard-core ExceptionMapper接口。 您不应该添加任何其他依赖项。 dropwizard-core依赖于dropwizard-jersey ,它依赖于jersey-server ,它依赖于jersey-common ,它依赖于具有ExceptionMapper接口的javax.ws.rs-api 。 The ExceptionMapper interface should already be pulled in when y ...Liberty中NotAllowedException的ExceptionMapper(ExceptionMapper for NotAllowedException in Liberty)[2022-11-01]
简短的回答是否定的,没有办法(当前)配置Liberty来抛出更具体的NotAllowedException。 Liberty使用Apache CXF作为底层JAX-RS实现,我对源代码进行了快速扫描,对JAX-RS客户端代码的唯一引用NotAllowedException,这对服务器无济于事。 查看服务器端代码,看起来修改CXF以抛出NotAllowedException而不是ClientErrorException应该不难。 Liberty组织定期从CXF社区提取更新,因此如果您在CXF中打开JIRA请求 ...并不总是这样,您的ExceptionMapper将捕获Exception层次结构下的所有异常。 如果还有其他更具体的映射器,比如RuntimeException , 那么映射器将用于RuntimeException及其子类型的所有异常。 这就是说(假设你使用resteasy-validation-provider-11 ),已经有一个处理ValidationException的ResteasyViolationExceptionMapper 。 @Provider public cla ... Map和GenericEntity的编组失败的原因是因为没有与它们相关联的JAXB定义。 当你将地图包装在一个用@XmlRootElement注释的POJO中时; 它能够正确地编组它。 The reason the marshalling failed for both Map and GenericEntity is because there is no JAXB definition associated with them. And when you wrapped the map in a POJ ...响应中设置的媒体类型错误。 它应该是.type("image/png")而不是image/img 。 这是我在本地测试时的代码。 return Response .status(Response.Status.BAD_REQUEST) .entity(Paths.get("/home","kishore","Pictures","Meme.png").toFile()) .type("image/png") .b ...什么是ExceptionMapper ? 但是,如何调用我的自定义异常映射器类来抛出相同的异常? 我希望自定义异常映射器类能够处理抛出API中发生的异常。 因此,我不想直接抛出异常(我的第二个代码片段),而是想调用异常映射器类并希望它抛出异常。 背后的想法和ExceptionMapper是将已抛出的Exception 映射到Response 。 检查ExceptionMapper#toResponse(E)方法签名,您将看到它收到扩展Throwable并且必须返回Response 。 这种方法由JAX-RS ...相关文章
更多- Gradle构建Groovy项目
- 《Joomla 2.5 模板教程:宁皓网》(Create a Joomla 2.5 Template)前两章 + 模板资源[光盘镜像]
- Groovy 循环语句
- Groovy 环境配置
- Groovy 快速入门程序
- Groovy 数字类型
- Groovy 方法详解
- Groovy def可选类型
- Groovy 变量详解
- Spring4新特性——Groovy Bean定义DSL
最新问答
更多- 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
- 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
- OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
- 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
- codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
- 在计算机拍照在哪里进入
- 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
- No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
- 单页应用程序:页面重新加载(Single Page Application: page reload)
- 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
- System.StackOverflow错误(System.StackOverflow error)
- KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
- 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
- android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
- TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
- 企业安全培训的各项内容
- 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
- C#类名中允许哪些字符?(What characters are allowed in C# class name?)
- NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
- 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
- 将多个行和可变行移动到列(moving multiple and variable rows to columns)
- 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
- 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
- Angular $资源不会改变方法(Angular $resource doesn't change method)
- 在Angular 5中不是一个函数(is not a function in Angular 5)
- 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
- 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
- 常见的python rpc和cli接口(Common python rpc and cli interface)
- Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
- 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)