Spring - Rest controller handles json input as null string - java

While playing around with the facebook messenger api I created a simple REST controller
#RestController
public class ChatController
{
private static final Logger LOG = LoggerFactory.getLogger(ChatController.class);
#RequestMapping(value="/webhook", method=RequestMethod.POST, consumes="application/json")
public String onWebhookEvent(String event)
{
LOG.info("Received event {}",event);
return "test";
}
}
However, when I POST the following json to the the /webhook endpoint the event input is logged as null ("Received event null")
{"object":
"page",
"entry":[
{
"id":43674671559,
"time":1460620433256,
"messaging":[
{"sender":{"id":123456789},
"recipient":{"id":987654321},
"timestamp":1460620433123,
"message":{"mid":"mid.1460620432888:f8e3412003d2d1cd93","seq":12604,"text":"Testing Chat Bot .."}
}
]
}
]
}
Why is that and how can I fix that? Since json is a serialization mechanism I assumed it will be presented as string to the onWebhookEvent method.
Thanks for the help

If you want a request's body to be tied up to a parameter, use #RequestBody.
By the way, return a ResponseEntity object, as it is a wrapper to whatever you want to return, and you can specify additional information (for example, headers of the response)

Related

Find the Content-type of the incoming request in Spring boot

I have a Spring-Boot controller application that will be called by the front-end. The Spring-boot #PostMapping would accept the XML and JSON. I want to call different methods based on the Content-Type.
Is there a way to check what is the incoming content type?
#CrossOrigin(origins = "*")
#RestController
#RequestMapping("/api")
public class MyController {
#PostMapping(value = "/generator", consumes = {"application/json", "application/xml"}, produces = "application/json")
public String generate(#RequestBody String input) {
try {
System.out.println("INPUT CONTENT TYPE : ");
if(contentType == "application/xml")
{
//Call Method-1
}else if(contentType == "application/json"){
//Call Method-2
}
} catch (Exception exception) {
System.out.println(exception.getMessage());
}
}
}
As we can see the RestController method accepts XML and JSON. I want to check whats the incoming Content-type is based on its need to make different decisions. Can someone please explain to me how to do it?
Please Note:
I am aware that I can create different methods to handle XML and JSON but I would like to do it in a single method so it would be easy and efficient.
Add RequestHeader with its name Content-type:
public String generate(#RequestBody String input, #RequestHeader("Content-type") String contentType)
Annotation which indicates that a method parameter should be bound to a web request header.
You can use
#RequestHeader Map<String, String> headers
inside param of your generate() methode for get all Header come from the client.
After that, just check the
Content-Type
value

Forcing Twilio Voice Callback to JSON to facilitate deserialization in Spring

I'm using the Java SDK to start a voice call using something similar to
Call.creator(to, from, callbackAddress)
I provide a URL (callbackAddress) that will receive the callback once the call is connected. Is there some way to configure this callback to be in JSON instead of "application/x-www-form-urlencoded; charset=UTF-8"?
The reason why I'm trying to do that is because I'm using Spring and ultimately I'm trying to receive the request parameters already in a deserialized Pojo in my RestController (parameter body in my example below), which is standard in SpringMVC. This is much easier to do using jackson, which requires a JSON request body
As a secondary question, is there a class in the Twilio SDK that encapsulates all the parameters in a request already or I would have to create such class?
Here is a dummy rest controller to illustrate what I'm trying to do. Note that the logic there with the "out of city" error is just a silly demo to show why I need to access the request parameters. All the samples I found about callbacks always ignored the request parameters and returned a static TwiML
#RestController
#RequestMapping(value = "/twilio", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class TwilioCallbackController {
#PostMapping
public String handleCallback(RequestBody body /*this arg should have all request params*/) {
log.info("received callback for callId {}", body.getCallSid())
if (!body.toCity().equals("my-city")) {
throw new Exception("outside of city");
}
return createTwiML(body);
}
}
Twilio developer evangelist here.
There is no way to have Twilio send you the webhook in JSON format, it will be sent as form encoded parameters. However, there shouldn't be an issue having Spring parse them.
As this answer suggests, you can create a class that will parse the parameters into it by creating a class with getters and setters for each of the parameters.
So, for example, you could create the following class:
public class TwilioWebhook {
private String CallSid;
private String From;
public String getCallSid() {
return CallSid;
}
public void setText(String CallSid) {
this.CallSid = CallSid;
}
}
Which you could then use to parse the CallSid from the incoming webhook parameters like:
#RestController
#RequestMapping(value = "/twilio", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public class TwilioCallbackController {
#PostMapping
public String handleCallback(TwilioWebhook request) {
log.info("received callback for callId {}", request.getCallSid())
// rest of the controller.
}
}
You can parse all the parameters by adding to the TwilioWebhook class. You can see all the parameters that Twilio will send in the Twilio voice request documentation. There isn't a class in the Twilio SDK that does this for you though.

JSON Error on clientside when sending ResponseEntity from serverside after post request

I have an angular/spring boot webapp. When I send a create user postrequest the angular clientside app isn't able to read the body of the response entity that I send back after the operation. The error is:
{error: SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "User successfully created."}
I know that this is caused because the body content isn't in JSON format. But the error persists even when I add produces = "application/json" as an attribute to the #PostMapping annotation.
Heres the code:
#RestController
#RequestMapping("api/user")
public class UserController {
private final Log logger = LogFactory.getLog(this.getClass());
#Autowired
UserService userService;
#Autowired
UserDao userDao;
#PostMapping(path = "/create", produces = "application/json")
private ResponseEntity<String> createNewUser(#RequestBody UserCreateDTO newUser) {
logger.info("name is: " + newUser.getUserName());
Status status = userService.createUser(newUser);
return ResponseEntity.status(status.isSuccess() ?
HttpStatus.CREATED : HttpStatus.BAD_REQUEST).body(status.getInfo());
}
What should I do to solve this problem? I think it has something to do with the use of ResponseEntity. I could just send the status DTO object that I've made back instead, but I want to be able to manipulate the httpStatus code that is being sent back too, so that's why I want to use the ResponseEntity instead.
It looks like you're returning a string literal instead of a json object. The returning object when converted to json should be like
{
"status": "user created successfully"
}
try returning your full status object instead of status.getInfo() then your return object should look something like:
{
"info": "user created successfully"
}
and you can call status.info within your javascript to reference the return
and will have to change your return type to RepsonseEntity<Status>
In fact yes you are using ResponseEntity but with a String as body, because you are using:
.body(status.getInfo());
You need to specify an object in the body, you can create a POJO that will hold the message for you, wraps the status.getInfo() String, and it will be read as JSON.
The message POJO class:
public class MessageObject {
private String message;
//Constructors, getter and setter
}
Your return code would be:
return ResponseEntity.status(status.isSuccess() ?
HttpStatus.CREATED : HttpStatus.BAD_REQUEST).body(new MessageObject(status.getInfo()));

Spring restful API, is there a method being used like router to get other method's end points or URL?

#RequestMapping("/accounts")
public class controller {
#GetMapping("/get/{id}")
public final ResponseEntity<?> getHandler(){
}
#PostMapping(value = "/create")
public final ResponseEntity<?> createHandler(){
/*
trying to use some spring library methods to get the url string of
'/accounts/get/{id}' instead of manually hard coding it
*/
}
}
This is the mock code, now I am in createHandler, after finishing creating something, then I want to return a header including an URL string, but I don't want to manually concat this URL string ('/accounts/get/{id}') which is the end point of method getHandler(), so I am wondering if there is a method to use to achieve that? I know request.getRequestURI(), but that is only for the URI in the current context.
More explanation: if there is some library or framework with the implementation of route:
Routes.Accounts.get(1234)
which return the URL for the accounts get
/api/accounts/1234
The idea is, that you don't need to specify get or create (verbs are a big no-no in REST).
Imagine this:
#RequestMapping("/accounts")
public class controller {
#GetMapping("/{id}")
public final ResponseEntity<?> getHandler(#PathVariable("id") String id) {
//just to illustrate
return complicatedHandlerCalculation(id).asResponse();
}
#PostMapping
public final ResponseEntity<?> createHandler() {
//return a 204 Response, containing the URI from getHandler, with {id} resolved to the id from your database (or wherever).
}
}
This would be accessible like HTTP-GET: /api/accounts/1 and HTTP-POST: /api/accounts, the latter would return an URI for /api/accounts/2 (what can be gotten with HTTP-GET or updated/modified with HTTP-PUT)
To resolve this URI, you could use reflection and evaluate the annotations on the corresponding class/methods like Jersey does.
A Spring equivalent could be:
// Controller requestMapping
String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0];
and
//Method requestMapping
String methodMapping = new Object(){}.getClass().getEnclosingMethod().getAnnotation(GetMapping.class).value()[0];
taken from How do i get the requestmapping value in the controller?

Intecepting Rest Controller responses

I am building a REST service using spring boot. My controller is annotated with #RestController. For debugging purposes I want to intercept the ResponseEntity generated by each of the controller methods (if possible). Then I wish to construct a new ResponseEntity that is somewhat based on the one generated by the controller. Finally the new generated ResponseEntity will replace the one generated by the controller and be returned as part of the response.
I only want to be able to do this when debugging the application. Otherwise I want the standard response generated by the controller returned to the client.
For example I have the controller
#RestController
class SimpleController
#RequestMapping(method=RequestMethod.GET, value="/getname")
public NameObject categories()
{
return new NameObject("John Smith");
}
}
class NameObject{
private String name;
public NameObject(name){
this.name = name;
}
public String getName(){ return name; }
}
This will generate the response:
{"name" : "John Smith"}
But I would like to change the response to include status info of the actual response e.g:
{"result": {"name" : "John Smith"}, "status" : 200 }
Any pointers appreciated.
The way I would try to achieve such a functionality is first by creating an Interceptor. And example can be found here
Second, I would employ Spring profiles to ensure that interceptor is loaded only in profile that I needed it in. Detail here. It's not exaclty debugging, but might do the trick.
You can do this with spring AOP, something like:
#Aspect
#Component
public class ResponseEntityTamperer {
#Around("execution(* my.package.controller..*.*(..))")
public Object tamperWithResponseEntity(ProceedingJoinPoint joinPoint)
throws Throwable {
Object retVal = joinPoint.proceed();
boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean()
.getInputArguments().toString()
.contains("jdwp");
if(isDebug && retVal instanceof ReponseEntity) {
// tamper with the entity or create a new one
}
return retVal;
}
}
The "find out if we're in debug mode" code is from this answer.

Categories