How to parse a string array with Mustache Template Lambda in java

703 views Asked by At

I am currently working on implementing a Mustache Lambda to parse this object: [{name=Content-Type, value=application/hal+json;charset=UTF-8}, {name=Content-Length, value=906}]

My template lambda looks like this:

import java.io.IOException;
import java.io.Writer;
import org.springframework.restdocs.mustache.Mustache.Lambda;
import org.springframework.restdocs.mustache.Template.Fragment;


public class GetContentType implements Lambda {
  @Override
  public void execute(Fragment fragment, Writer writer) throws IOException {
    fragment.execute(writer);
  }
}

The mustache template looks like this

{{#getContentType}}
     {{http-response.headers}}
{{/getContentType}}

The output from generating the template produces the following

[{name=Content-Type, value=application/hal+json;charset=UTF-8}, {name=Content-Length, value=906}]

I am trying to figure out how to return the value application/hal+json from the key Content-Type in the java function. There isn't much documentation on this so any help would be greatly appreciated.

1

There are 1 answers

0
Andy Wilkinson On

The Fragment that is passed into your Lambda has a context that's available via the context() method. The exact type and content of the context depends on how your lambda's being used so it's typed as an Object.

It looks like you're working with the headers that are added to the context by Spring REST Docs. In this case the headers are a List of Map, where each map contains name and value entries.

Hopefully this gives you enough to retrieve the context() from the Fragment and start casting it and drilling down into its content to find the map with a name=Content-Type entry from where you can retrieve the entry that's keyed with value.