spring boot (mvc) response with different content type encoding on error - rest

I need help with spring handling an error.
a client service is sending a request accepting two different content types - binary and json. when everything works fine I prefer communicating to my server with binary encoding to save bandwidth. but on error I would like serialise ResponseEntity to json as my binary serialiser do not know how to serialise it to binary format, plus it is better for logging, etc.
I configured instance of ResponseEntityExceptionHandler and I am handling different exceptions from that implementation. but spring always choses binary format as it is first on the accept (or produces) list.
all I get is (because spring do not know how to serialise ResponseEntity to my custom binary format. see AbstractMessageConverterMethodProcessor#writeWithMessageConverters)
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
client sends
headers {Accept: [application/custom-binary, application/json]
server's controller is configured to
// pseudo code
#RequestMapping(method = GET, produces = {"application/custom-binary", APPLICATION_JSON_VALUE})
public BannerMetaCollection get(#RequestParam(value = "q") UUID[] q) {
if (q != null) {
return service.getAllDataWith(q);
} else {
throw new IllegalArgumentException("invalid data");
}
}
// pseudo code
public class RestExceptionResolverSupport extends ResponseEntityExceptionHandler {
#ExceptionHandler
public ResponseEntity<Object> illegalArgumentException(IllegalArgumentException ex, WebRequest request {
Object body = errorResponse()
.withCode(BAD_REQUEST)
.withDescription("Request sent is invalid")
.withMessage(ex.getMessage())
.build());
return new ResponseEntity<Object>(body, new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
}
any hints?

What I do to get this to work is that a let my endpoint method return a ResponseEntity and I don't declare what content is produced in the #RequestMapping annotation. I then set the Content-type header myself before returning the response, e.g.
// pseudo code
#RequestMapping(method = GET)
public ResponseEntity<BannerMetaCollection> get(#RequestParam(value = "q") UUID[] q) {
if (q != null) {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "application/custom-binary");
return new ResponseEntity<>(service.getAllDataWith(q),
headers,
HttpStatus.OK);
} else {
throw new IllegalArgumentException("invalid data");
}
}

Related

Feign Client Get Request HttpStatus 200 but body is null when json is very long

I have an issue with my Feign client, I get the response as well when the json not containing lot of data. But when a json is very long I get 200 status inside Response Object but body is null:
#FeignClient(name = "processSvc", url = "${xxx}")
public interface ProcessClient {
#GetMapping(value = "/v1/process/{uid}", produces = "application/json")
Response readProcess(#PathVariable("uid") String uid);
}
Any proposition for resolve this issue ?
The issue was reading a response that is larger than the entire memory allocated to the current process. So, streaming the response fixed the issue by getting the body as InputStream, then convert it to String via IOUtils.toString() :
Response response = null;
String json;
try {
response = processClient.readProcess(uid);
json = IOUtils.toString(response.body().asInputStream(), Charsets.UTF_8.name());
} catch (IOException e) {
throw new RuntimeException(e);
}

Encoded special characters in parameters causing spring boot contract testing query does not match problem

While writing the spring boot contract testing on consumer side, I having problem when request parameters contains special characters. They'll automatically encoding causing the test failed due to the spring consider that the "Query does not match"
"自动制动" has been encoded as "%E8%87%AA%E5%8A%A8%E5%88%B6%E5%8A%A8"
Check the log, i could see:
Query: word = 自动制动 | word: %E8%87%AA%E5%8A%A8%E5%88%B6%E5%8A%A8 <<<<< Query does not match
Here's my groovy file on producer side:
Contract.make {
description "Returns \"Auto hold\"'s canonical value_Mandarin"
name "getSynonym_AutoHold_canonical_Mandarin"
request {
urlPath( "/synonyms"){
headers {"accept: application/json;charset=UTF-8"}
queryParameters {
parameter("filter","canonical")
parameter("lang", "cmn-CHN")
parameter("word","自动制动")
}
}
method GET()
}
response {
status OK()
headers {
contentType applicationJson()
}
body '''
{
"canonical": "autohold",
"word": "自动制动"
}'''
}
}
And here's what I have in consumer side:
#Test
public void testSynonyms_Cmn(){
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/synonyms";
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("filter","canonical")
.queryParam("lang","cmn-CHN")
.queryParam("word","自动制动");
HttpEntity<?> entity = new HttpEntity<>(httpHeaders);
CentralizedSynonyms centralizedSynonyms = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity
, CentralizedSynonyms.class).getBody();
assertThat(centralizedSynonyms.getWord()).isEqualTo("自动制动");
assertThat(centralizedSynonyms.getCanonical()).isEqualTo("autohold");
}
I had something similar and fixed it with this:
url value(consumer("/path1/path2/something%3Dsomethingelse"), producer("/path1/path2/something=somethingelse"))

Unable to set values in the map using webclient call response

I am unable to get values filled in the map after making a web client call and using the response of the previous Mono.Here is the code I have tried.The value of parameters.size() comes out to zero.Not able to get the reason as to why the value is not filled.I basically want to return age ( and not Mono object)
from this method.Using block gives an error block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-3.
Map<String, String> parameters = new HashMap<String,String>();
Mono<Person> obj = webClient
.post()
.uri("dummy url")
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
.retrieve()
.bodyToMono(Person.class)
.flatMap(resp -> {
parameters.put("name", resp.getName());
parameters.put("age", resp.getAge());
return Mono.just(new Person(resp.getName(),resp.getAge()));
}
);
System.out.println(parameters.size());
Please suggest where I am wrong and solution to fix the same.
Since this is about collecting and using a token of some sort collected from a previous HTTP call, your best bet is to delegate all that to an ExchangeFilterFunction.
An ExchangeFilterFunction is a filter that is executed on the client side for each outgoing request. Here is a very, very naïve implementation of such a filter:
class TokenFilterFunction implements ExchangeFilterFunction {
private final AtomicReference<String> token = new AtomicReference<>();
#Override
public Mono<ClientResponse> filter(ClientRequest req, ExchangeFunction next) {
if (this.token.get() == null) {
return fetchToken(next).then(sendRequest(req, next));
}
else {
return sendRequest(req, next);
}
}
private Mono<ClientResponse> sendRequest(ClientRequest req, ExchangeFunction next) {
ClientRequest request = ClientRequest.from(req)
.header("Token", this.token.get()).build();
return next.exchange(request);
}
private Mono<Void> fetchToken(ExchangeFunction next) {
ClientRequest tokenRequest = ClientRequest.create(HttpMethod.GET,
URI.create("https://example.com/token")).build();
return next.exchange(tokenRequest).doOnNext(res -> {
this.token.set(res.headers().header("Token").get(0));
}).then();
}
}
This could automatically call the token endpoint to fetch a token when needed and directly chain with the request you asked in the first place. Again, such an implementation should be much more complex than that, handling domains, errors, and more.
If you're using some authentication technology, such a filter might be implemented already in Spring Security in a much, much better way.
You can configure it on your client during the building phase, like:
WebClient webClient = WebClient.builder().filter(new TokenFilterFunction()).build();

Headers in POST in Grails 3 app are not being sent with rest of service

Using Grails 3.0.9, and grabbing the freshest REST API with this snippet in gradle.build:
compile 'org.grails:grails-datastore-rest-client:4.0.7.RELEASE', {
['commons-codec', 'grails-async', 'grails-core',
'grails-plugin-converters', 'grails-web', 'groovy'].each {
exclude module: it
}
}
I am trying to make the following POST request:
def rest = new RestBuilder(headers:["X-LSS-Env":"devmo"], connectTimeout:10000, readTimeout:20000)
response = rest.post("http://..../..") {
accept "application/json"
contentType "application/json"
json jsonBuilder
}
Now, the POST receiver gets the json okay, give back a response okay, but this is the problem: it receives the headers as an empty map or as null!
So, what is the correct way of passing header data to the POST receiver? This is needed because the environment key X-LSS-Env could have different values, which instructs the receiver to do further routing based on it. Same with the GET request of course.
* UPDATE *
The consumer of my POST requests is actually a Java application, running on Apache Tomcat/8.0.26. The is how the service looks on the other side:
private javax.servlet.http.HttpServletRequest hsr;
#POST
#Path("/na")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response postSomething(Ggfp ggfp ){
try {
Enumeration<String> hnames = hsr.getHeaderNames();
int i = 0;
while (hnames.hasMoreElements()) {
String headerName = hnames.nextElement();
System.out.println(++i+ " headerName: " + headerName);
String val = hsr.getHeader(headerName);
System.out.println(" val: " + val);
}
String hval = hsr.getHeader("X-LSS-Env");
return Response.status(Status.OK).entity("X-LSS-Env is " + hval).build();
} catch (Exception e) {
}
}
Calling this service from Postman works, headers are identified. Calling it from the Grails app results into an empty map - like I am sending no headers!
The RestBuilder constructor never liked the way I used (or abused) it. Here is a clean way of achieving what I set out to do, with tryCatch logic if a timeout transpires.
def makePostWsr(serviceUrl, jsonBuilder) {
try {
def rest = new RestBuilder(connectTimeout:connectTimeout, readTimeout:readTimeout)
def response = rest.post("$wsUrl/$serviceUrl") {
header 'X-LSS-Env', 'devmo'
accept "application/json"
contentType "application/json"
json jsonBuilder
}
response
} catch (Exception e) {
println "== problem makePostWsr on $serviceUrl"
null
}
}

How do I add a SOAP Header using Java JAX-WS

A typical SOAP client request using JAX-WS might be
FooService service = new FooService();
FooPort port = service.getFooPort();
FooPayload payload = new FooPayload();
payload.setHatSize(3);
payload.setAlias("The Hat");
...
port.processRequest(payload);
This generates an HTTP request content something like
<?xml ... ?>
<S:Envelope xmlns:S="http://...soap-envelope">
<S:Body>
<!-- payload -->
</S:Body>
</S:Envelope>
By manipulating the arguments to the port.processRequest() call you can only affect the "payload" part. You can't affect the outer part of the XML message.
I want to insert a SOAP header just before the SOAP Body
<S:Header>
<X:Security xmlns:X="http://...wsssecurity...>
<X:BinarySecurityToken>kjh...897=</X:BinarySecurityToken>
</X:Security>
</S:Header>
How do I do that?
Thanks Nuno,
Just as soon as I work out how to log in properly to stackoverflow.com I'll do the right thing with your reply.
In the mean time here's the code I ended up with:
FooService service = new FooService();
service.setHandlerResolver(new HandlerResolver() {
public List<Handler> getHandlerChain(PortInfo portInfo) {
List<Handler> handlerList = new ArrayList<Handler>();
handlerList.add(new RGBSOAPHandler());
return handlerList;
}
});
FooPort port = service.getFooPort();
FooPayload payload = new FooPayload();
payload.setHatSize(3);
payload.setAlias("The Hat");
...
port.processRequest(payload);
and
class RGBSOAPHandler implements SOAPHandler<SOAPMessageContext> {
public Set<QName> getHeaders() {
return new TreeSet();
}
public boolean handleMessage(SOAPMessageContext context) {
Boolean outboundProperty =
(Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
SOAPMessage message = context.getMessage();
try {
SOAPEnvelope envelope = context.getMessage()
.getSOAPPart().getEnvelope();
SOAPFactory factory = SOAPFactory.newInstance();
String prefix = "X";
String uri = "http://...wsssecurity...";
SOAPElement securityElem =
factory.createElement("Security",prefix,uri);
SOAPElement tokenElem =
factory.createElement("BinarySecurityToken",prefix,uri);
tokenElem.addTextNode("kjh...897=");
securityElem.addChildElement(tokenElem);
SOAPHeader header = envelope.addHeader();
header.addChildElement(securityElem);
} catch (Exception e) {
System.out.println("Exception in handler: " + e);
}
} else {
// inbound
}
return true;
}
public boolean handleFault(SOAPMessageContext context) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void close(MessageContext context) {
//
}
}
you might want to look at handlers and handler chains.- I recently had to add a cookie to a given Webservice call and that was how i did it, just created a handler that intercepted the initial call and injected the cookie, you can also manipulate the call headers with a Pivot Handler
for add Soap header, if you implement the WS on the web application server, the Was will add security part at header , after you have configure as per WS-SECURITY standard , such as web-policy etc. I don't understand why need add yourself except the encrypted content part , such as encrypted password etc