首页 \ 问答 \ 使用groovy循环模板GStringTemplateEngine()(looping a template using groovy GStringTemplateEngine())

使用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 by Eduardo 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
更新时间:2023-09-08 13:09

最满意答案

您可以使用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 as

public 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 not WebApplicationException (and its subclasses) (note WebApplicationException is also a child class of Exception)

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 @Producesspecified 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 code ExceptionMapper<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 for WebApplicationException 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 set

  request.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 before RESTEASY_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 MediaType Application/XML for serialization to proceed.

Hope this helps someone also facing the same issue.

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用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)