How do I to send custom HTTP error responses in String? - java

I am stuck with validating a String if the url is sending the path variables with invalid data.
Currently, the exception is throwing back a response. But I want to send back the response with a message.
E.g {"message": "Invalid Data"}.
I'm using #RestController API.
URL: ==> http://((domain))/getdata/"dd"
#GetMapping(value = { "/{id[]}" })
public ResponseEntity<JsonNode> getData( #PathVariable(name = "id[]") Long[] id ) {..}

Related

OpenFeign not decoding response

#FeignClient(name = "Authorization-API", url = "https://www.reddit.com/api/v1")
public interface AuthorizationApi {
#RequestMapping(method = RequestMethod.POST, value = "/access_token")
Token getToken(#PathVariable("grant_type") String grantType,
#PathVariable String code,
#PathVariable("redirect_uri") String redirectUrl,
#RequestHeader(name = "Authorization") String authorizationHeader,
#RequestHeader("User-agent") String agent
);
}
Call:
Token token = authorizationApi.getToken(
"authorization_code",
code,
REDIRECT_URI,
getAuthorizationCredentials(),
"porymol");
System.out.println(token.access_token()); //returns null
Token record:
public record Token(String access_token, String token_type, Long expires_in, String scope, String refresh_token) {
}
When I make request from Postman I get this response:
{
"access_token": "token",
"token_type": "bearer",
"expires_in": 86400,
"refresh_token": "token",
"scope": "read"
}
Trying to get any value from Token returns null
Java 17, Spring boot 3
Any idea what's going wrong here?
First of all you have declared two path variables which dont show up the path:
#PathVariable String code and #PathVariable("redirect_uri") String redirectUrl.
Overall it looks like you are trying to request an oauth access token which requires an request of content type application/x-www-form-urlencoded.
Maybee this helps: How to POST form-url-encoded data with Spring Cloud Feign

FeignClient API with different response class

I am using Jhipster. I have a yaml file, then generate java code using jhipster openapi-client. It generate several files, including the all the model class needed (to contain the request and response).
DefaultApiClient
#FeignClient(name="${default.name:default}", url="${default.url:https://test.api.com/testing}", configuration = ClientConfiguration.class)
public interface DefaultApiClient extends DefaultApi {
}
DefaultApi
#javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2021-01-22T14:50:31.377193700+08:00[Asia/Singapore]")
#Validated
#Api(value = "Default", description = "the Default API")
public interface DefaultApi {
/**
* POST /req/v1 : This is the request
*
* #param authorization JWT header for authorization (required)
* #param body (required)
* #return successful operation (status code 200)
* or server cannot or will not process the request (status code 400)
*/
#ApiOperation(value = "This is the request", nickname = "Verification", notes = "", response = ResponseType.class, authorizations = {
#Authorization(value = "clientID")
}, tags={ })
#ApiResponses(value = {
#ApiResponse(code = 200, message = "successful operation", response = ResponseType.class),
#ApiResponse(code = 400, message = "server cannot or will not process the request", response = ServiceMessagesType.class) })
#RequestMapping(value = "/req/v1",
produces = "application/json",
consumes = "application/json",
method = RequestMethod.POST)
ResponseEntity<ResponseType> Verification(#ApiParam(value = "JWT header for authorization" ,required=true, defaultValue="Bearer REPLACE_THIS_KEY") #RequestHeader(value="Authorization", required=true) String authorization,#ApiParam(value = "" ,required=true ) #Valid #RequestBody RequestType body);
}
I can manage to get the response successfully, but the problem appear when I send a false request, It will response with and Bad Request 400 and crash my program.
As you can see on the swagger annotation #ApiResponse, it return different class.
I am really confuse with it. My question is:
Just for confirm, #ApiResponse is only for documentation, right? Does this code affect the program like when it return code 400, the response will automatically be ServiceMessageType class?
How can I handle different response class? As you can see in the function deffinition, ResponseEntity Verification, it will return ResponseType as the body of ResponseEntity. But when I send an error request to this Api, this Api will return ServiceMessageType. And fyi, the code 400 will give my program an error says "failed and no fallback available" so I think I need an error handle to do it.
For no.2, I already search for the solution in several source
https://programmer.group/feign-call-error-failed-and-no-fallback-available.html
but I don't really get it. I use the fallbackFactory, and it can handle the 400 code exception. But I still really confuse about how to return different response class. And I get the result not in correct structure, as the link said:
By implementing FallbackFactory, you can get the exception thrown by the service in the create method. However, please note that the exception here is encapsulated by Feign, and the exception thrown by the original method cannot be seen directly in the exception information. The abnormal information obtained is as follows: status 500 reading TestService#addRecord(ParamVO); content: {"success":false,"resultCode":null,"message":"/ by zero","model":null,"models":[],"pageInfo":null,"timelineInfo":null,"extra":null,"validationMessages":null,"valid":false}
To illustrate, in this example, the interface return information of the service provider will be uniformly encapsulated in the user-defined class Result, and the content is the above content: {"success":false,"resultCode":null,"message":"/ by zero","model":null,"models":[],"pageInfo":null,"timelineInfo":null,"extra":null,"validationMessages":null,"valid":false}
Please explain to me how it work, or you can give me a link about how it works, I will really appreciate the help.

Sending #RequestBody from node js to Spring Boot Rest API

After spending more than half a day still not able to get down to whats wrong with the following:
Trying to send form data from NodeJSto Spring Rest API.
Node JS:
var inputData = { base : req.body.base, test : req.body.test }
var queryParams = {
host: '127.0.0.1',
port: 8080,
path: '/start',
method: 'POST',
headers: {'Content-type': 'application/json'},
body: inputData //Used JSON.stringify(inputData) - didn't work
};
Using http module to send request:
var req = http.request(queryParams, function(res) {
//do something with response
});
req.end();
Spring Rest:
#RequestMapping(value = "/start", method = RequestMethod.POST, consumes = "application/json")
#ResponseBody
public String startApp(#RequestBody String body) {
System.out.println(body);
return "{\"msg\":\"Success\"}";
}
Using postman I am able to see the same inputData going through the Rest. But when sent from NodeJS, all I see is
{
timestamp: 1506987022646,
status: 400,
error: 'Bad Request',
exception: 'org.springframework.http.converter.HttpMessageNotReadableException',
message: 'Required request body is missing: public java.lang.String ApplicationController.startApp(java.lang.String)',
path: '/start'
}
Using spring-boot-starter parent in the maven.
Am I missing anything here? Any suggestions would be greatly appreciated!
I don't think that you put request body in queryParams will work.
You can try using req.write() to write data to request body as follows:
...
req.write(inputData);
req.end();
...

Java Spring MVC - Send JSON request body error

I am trying to send a JSON string as a request to my application. This is my code:
#RequestMapping(
value = "/mylink/upload",
method = RequestMethod.POST,
consumes ="application/json",
produces = "application/json")
public
#ResponseBody
List<Upload> upload(
#RequestParam(value = "hdfsLocation") String hdfsLocation
) throws Exception {
return S3HdfsTransfer.uploadFromHDFS(hdfsLocation);
}
I am trying to send a request with Postman. The method I use is POST, the header contains: Accept "application/json",Content-Type "application/json", the request body is the following:
{
"hdfsLocation" : "hdfs://145.160.10.10:8020"
}
This is the response I get. If I put the parameter in the URL, it works.
{
"httpStatus": 500,
"appErrorId": 0,
"message": "Required String parameter 'hdfsLocation' is not present",
"trackingId": "8c6d45fd-2da5-47ea-a213-3d4ea5764681"
}
Any idea what I am doing wrong?
Thanks,
Serban
Looks like you have confused #RequestBody with #RequestParam. Do either of following :
Pass the request param as a request param(not as a body). Like, (encoded)
http://example.com?hdfsLocation=http%3A%2F%2Fexample.com%3FhdfsLocation%3Dhdfs%3A%2F%2F145.160.10.10%3A8020
Replace the #RequestParam with #RequestBody. If you are sending a body, don't send it along with request param. Those are two different things.
I guess you over looked :)
Shouldn't it be #RequestBody instead of #RequestParam?
Also, even after using #RequestBody, the whole of the JSON string:
{
"hdfsLocation" : "hdfs://145.160.10.10:8020"
}
will be the value of String hdfsLocation and not just the hdfs url. Hence, you'll have to JSON parse that JSON by yourself to get just the hdfs url.

wrong encoding in jaxrs post method

I'm having an Encoding problem when trying to consume an Arabic json message, however when producing the json in a get method I get the message right here is the code:
#Path("/json")
public class HelloJson {
#GET
#Path("/get")
#Produces("application/json; charset=UTF-8")
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle("الليله");
track.setSinger("عمرو دياب");
return track;
}
#POST
#Path("/post")
#Consumes("application/json; charset=UTF-8")
public Response createTrackInJSON(Track track) throws UnsupportedEncodingException{
String result = new String (("Track saved : " + track).getBytes(), "UTF-8");
System.out.println(result);
return Response.status(201).entity(result).type("text/plain; charset=UTF-8").build();
}
}
you can try this webservice on the following link:
http://java7learning-khalidspace.rhcloud.com/rest/json/get
if asked for authentication use username admin and password admin
this link will return you a json with Arabic values without any Encoding problems.
now take this json message and use it in the post method using the following link:
http://java7learning-khalidspace.rhcloud.com/rest/json/post
you can use the post method using the webservice tester from eclipse or any other webservice just insert the content-type=application/json and authorization = Basic YWRtaW46YWRtaW4= as request headers and but the json in the request body.
the post method will return a massage with the arabic characters as "????"
please tell me what I'm missing and thanks for help.
Already have you tried to send them with the escaped characters?:
{
"title" : "\u0627\u0644\u0644\u064A\u0644\u0647",
"singer" : "\u0639\u0645\u0631\u0648 \u062F\u064A\u0627\u0628"
}
I get with this way using SoapUI and your http://java7learning-khalidspace.rhcloud.com/rest/application.wadl:
Track saved : Track [title=الليله, singer=عمرو دياب]

Categories

Resources