springboot return responseentity return JSON - java

I want to return JSON below.
{
"name": "jackie"
}
Postman is giving me error. Stating
Unexpected 'n'
New to Spring Boot here. 1 day old. Is there a proper way to do this?
// POST method here
#RequestMapping(method = RequestMethod.POST , produces = "application/json")
ResponseEntity<?> addTopic(#RequestBody Topic topic) {
if (Util.save(topicRepository, new Topic(topic.getTopicName(), topic.getQuestionCount())) != null) {
return Util.createResponseEntity("Name : jackie", HttpStatus.CREATED);
}
return Util.createResponseEntity("Error creating resource", HttpStatus.BAD_REQUEST);
}

This is what I use:
#GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, String>> hello() {
try {
Map<String, String> body = new HashMap<>();
body.put("message", "Hello world");
return new ResponseEntity<>(body, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}

Create model and store value in that model and return model from controller.
Check Below code.
class User{
private String name;
//getter and setter
}
#RequestMapping(method = RequestMethod.POST , produces = "application/json")
ResponseEntity<User> addTopic(#RequestBody Topic topic) {
User user=new User();
user.setName("myname");
HttpHeaders httpHeaders = new HttpHeaders();
return new ResponseEntity<User>(user, httpHeaders, HttpStatus.CREATED);
}

Try wrapping your response in object.
class Response implements Serializable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And Controller can be like this:
#RequestMapping(method = RequestMethod.POST , produces = "application/json")
ResponseEntity<?> addTopic(#RequestBody Topic topic) {
if (Util.save(topicRepository, new Topic(topic.getTopicName(), topic.getQuestionCount())) != null) {
Response response = new Response();
response.setName("jackie");
return new ResponseEntity<>(response, HttpStatus.CREATED);
}
return Util.createResponseEntity("Error creating resource", HttpStatus.BAD_REQUEST);
}

#PostMapping("/register/service/provider")
public ResponseEntity<?> registerServiceProvider(#RequestBody ServiceProviderRequestPayload providerContext) {
try {
if (providerContext == null)
throw new BadRequestException("the request body can not be null or empty.");
if (!providerContext.isValid())
throw new BadRequestException("The request body doesn't seems to be valid");
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(new ObjectMapper().writeValueAsString(providerContext));
} catch (BadRequestException | IllegalArgumentException e) {
return ResponseEntity.badRequest().header("message", e.getMessage())
.contentType(MediaType.APPLICATION_JSON).build();
} catch (DuplicateKeyException keyException) {
return ResponseEntity.badRequest().header("message", "There seems to be farmer config" + keyException.getCause())
.contentType(MediaType.APPLICATION_JSON).build();
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}

Related

unable to call AOP is advice

Aop is unable to trigger when userData method is called.
#RequestMapping(value = "/service/userDate", method = RequestMethod.POST)
public ResponseEntity<Response> UserApp(#RequestBody UserVO userVO) {
Response res = new Response(HttpStatus.OK.value());
try {
logger.debug("UserController : </ UserApp> ");
res = userService.userApp(userVO);
return new ResponseEntity<>(res, HttpStatus.OK);
} catch (Exception e) {
logger.error("Exception in approveUser" + e.getMessage());
return new ResponseEntity<>(
new Response(ErocErrorConstants.ERROR_STRING, HttpStatus.EXPECTATION_FAILED.value()),
HttpStatus.BAD_REQUEST);
}
}
package com.gf.service
public class UserService {
#Transactional
public Response userData(User userData) {
}
}
#Aspect
public class EmailAopService {
#Pointcut("execution(* com.gf.service.UserService.userData(..)) && args(userData))")
private void selectAll() {}
#Before("selectAll()")
public void logBefore(User userData) {
//
}
}

Produce Different type of response from spring boot rest controller

I have a scenario to create a rest method which return json response if there is any validation fail. and if everything is correct then download a pdf method.
Is it possible to be done via same method?
PFB the method signature what i need to achieve.
#RequestMapping(value = "/getPdf", method = RequestMethod.POST, consumes = MediaType.ALL_VALUE, produces = {"application/pdf","application/json"})
public #ResponseBody LinkedHashMap<String, Object> getPdf(#Valid #RequestBody DownloadPdfDTO downloadPdfDTO,BindingResult result,HttpServletRequest request,HttpServletResponse response) throws IOException {
}
This Method works fine when everything correct and PDF is getting download.
But when there is any validation fail then no response is getting render and i am getting Status : 406 Not Acceptable.
Thanks
Yes u can dot it using global exception handler.
#Order(Ordered.HIGHEST_PRECEDENCE)
#ControllerAdvice
public class GlobalExceptionHandler {
ObjectMapper objectMapper = new ObjectMapper();
#ExceptionHandler(AccessDeniedException.class)
public void handleAccessDenied(HttpServletResponse response, AccessDeniedException ex) {
response.setStatus(HttpStatus.UNAUTHORIZED);
try (PrintWriter writer = response.getWriter()) {
objectMapper.writeValue(writer, YOUR_OBJECT_TO_RETURN);
} catch (IOException ex) {
}
}
#ExceptionHandler({MethodArgumentNotValidException.class, ConstraintViolationException.class})
public void handleException(HttpServletResponse response, Exception ex) {
response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY);
try (PrintWriter writer = response.getWriter()) {
objectMapper.writeValue(writer, YOUR_OBJECT_TO_RETURN);
} catch (IOException ex) {
}
}
#ExceptionHandler(NullPointerException.class)
public void handleNullPointerException(HttpServletResponse response, Exception ex) {
//return your required response
}
}
You can give a return type as ResponseEntity. With ResponseEntity you can bind different response as per your business logic.
An example will be like this
#ApiOperation(value = "Get PDF API", consumes = "application/json", httpMethod = "GET")
#ApiResponses(value = {#ApiResponse(code = 404, message = "Bad request")})
#RequestMapping(value = "/pdf/{filename}", headers = "Accept=application/json", method = RequestMethod.GET)
public
#ResponseBody
ResponseEntity getPDF(#ApiParam(value = "filename", required = true) #PathVariable String filename) {
try {
Boolean validationPass = checkValidation();
if (validationPass) {
resp = getPDF();
responseHeaders.setContentType(MediaType.APPLICATION_PDF);
responseHeaders.set("charset", "utf-8");
responseHeaders.setContentLength(resp.length);
responseHeaders.set("Content-disposition", "attachment; filename=response.pdf");
return new ResponseEntity<>(resp,responseHeaders, HttpStatus.OK);
}
else {
// create your json validation eneity here
return new ResponseEntity<>(validation entity, HttpStatus.BAD_REQUEST);
}
} catch (Exception e) {
return new ResponseEntity<>( createExceptionEntity(e) ,HttpStatus.BAD_REQUEST);
}
}

Not able to typecast from String to a class in Spring REST

Getting following exception while hitting a Rest endpoint. How do I typecast from String to ProtectPanReplyType class?
Error:
Error - Request: http://localhost:9090/hosted-payments-webapp-1.0.0/pan/protect
raised java.lang.ClassCastException: com.gsicommerce.api.checkout.ProtectPanReplyType cannot be cast to java.lang.String
ProtectPanServiceImpl.java
#Service
public class ProtectPanServiceImpl implements ProtectPanService {
#Override
public ResponseEntity<?> sendProtectPanRequest(ProtectPan protectPan) {
String pan = protectPan.getPaymentAccountNumber();
String tenderClass = protectPan.getTenderClass();
String protectPanRequest = XMLHelper.createProtectPanRequest(pan, tenderClass);
System.out.println("protectPanRequest = " + protectPanRequest);
ResponseEntity<String> response = null;
try {
response = ApiClientUtils.callClientByEndpointandMessage(protectPanRequest, DEV_PUBLIC_API_URL,
ProtectPanReplyType.class);
System.out.println("response.getClass() = " + response.getClass());
//DOES NOT WORK
//ProtectPanReplyType protectPanReplyType = (ProtectPanReplyType)response.getBody();
//THROWS ClassCastException HERE
System.out.println(response.getBody());
} catch (JiBXException e) {
e.printStackTrace();
}
return response;
}
}
ApiClientUtils.java
public ResponseEntity<String> callClientByEndpointandMessage(String xmlRequest, String endpoint, Class<?> replyType) throws JiBXException {
HttpEntity<String> request = createRequestForUser("username", "secret",xmlRequest);
ResponseEntity<String> response = restOperations.postForEntity(endpoint, request, String.class);
ResponseEntity formattedResponse = new ResponseEntity(null, HttpStatus.BAD_REQUEST);
try {
Object jibxObject = JibxHelper.unmarshalMessage(response.getBody(), replyType);
formattedResponse = new ResponseEntity(jibxObject, HttpStatus.OK);
} catch (JiBXException e) {
FaultResponseType faultResponse = JibxHelper.unmarshalMessage(response.getBody(), FaultResponseType.class);
formattedResponse = new ResponseEntity(faultResponse, HttpStatus.BAD_REQUEST);
}
return formattedResponse;
}
ProtectPan.java
public class ProtectPan {
#JsonProperty("paymentAccountNumber")
private String paymentAccountNumber;
#JsonProperty("tenderClass")
private String tenderClass;
public String getPaymentAccountNumber() {
return paymentAccountNumber;
}
public String getTenderClass() {
return tenderClass;
}
}
ProtectPanReplyType.java
public class ProtectPanReplyType {
private String token;
private List<Element> anyList = new ArrayList<Element>();
private String sessionId;
//getters and setter removed for brevity
}
Use ResponseEntity<ProtectPanReplyType> instead ResponseEntity<String>
Build and Return ProtectPanReplyType from your restOperations.postForEntity()
Was finally able to get the object after making following changes.
ApiClientUtils.java
public ResponseEntity<?> callClientByEndpointandMessage(String xmlRequest, String endpoint, Class<?> replyType) throws JiBXException {
HttpEntity<String> request = createRequestForUser("payment", "SONitc2m8y", xmlRequest);
ResponseEntity<String> response = restOperations.postForEntity(endpoint, request, String.class);
ResponseEntity<?> formattedResponse = null;
try {
Object jibxObject = JibxHelper.unmarshalMessage(response.getBody(), replyType);
formattedResponse = new ResponseEntity(jibxObject, HttpStatus.OK);
} catch (JiBXException e) {
FaultResponseType faultResponse = JibxHelper.unmarshalMessage(response.getBody(), FaultResponseType.class);
formattedResponse = new ResponseEntity(faultResponse, HttpStatus.BAD_REQUEST);
}
return formattedResponse;
}
ProtectPanServiceImpl.java
#Override
public ResponseEntity<?> sendProtectPanRequest(ProtectPan protectPan) {
String pan = protectPan.getPaymentAccountNumber();
String tenderClass = protectPan.getTenderClass();
String protectPanRequest = XMLHelper.createProtectPanRequest(pan, tenderClass);
ResponseEntity<?> response = null;
try {
response = publicApiClientUtils.callClientByEndpointandMessage(protectPanRequest, DEV_PUBLIC_API_URL, ProtectPanReplyType.class);
ProtectPanReplyType protectPanReplyType = (ProtectPanReplyType) response.getBody();
System.out.println("protectPanReplyType = " + protectPanReplyType);
} catch (JiBXException e) {
e.printStackTrace();
}
return response;
}

Global Variable for Asynchronous data access in spring MVC

I have a below controller
#Controller
public class TestController{
public Future<ArrayList<String>> global_value = null;
#Autowired
private AsyncService asyncService;
#RequestMapping(value = "/asyncCall", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String getToken(HttpServletRequest request) {
global_value = asyncService.execute();
return "OK";
}
#RequestMapping(value = "/getAsyncData", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ArrayList<String> getData() {
try {
if (global_value != null && global_value.get().size() > 0) {
return global_value.get();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
}
When I long poll the getAsncData endpoint, how do I maintain the global_value is just for a request. global_value must be unique for the request scope.
How can I achieve this?

500 internal server error in spring mvc 3 controller response for ajax call

my code gives 500 error when I have the following code. It sends a jason response to an ajax call.
#RequestMapping(value = "/savecourse", method = RequestMethod.POST)
public #ResponseBody
Object saveLecturer(#Valid #ModelAttribute(value = "course") Course course,
BindingResult result) {
Map<String, Object> response = new HashMap<String, Object>();
if (result.hasErrors()) {
List<ObjectError> results = result.getAllErrors();
for (ObjectError objectError : results) {
System.out.println(objectError.getDefaultMessage());
}
response.put("message", "Could not add the Course to the system.");
} else {
try {
course.setId(courseDao.saveCourse(course));//returns the id
response.put("course", course);
} catch (Exception e) {
System.out.println(e);
}
}
return response;
}
But when I create a new object and copy the parameters to the other object, it works fine. The second method(Not a good method of course) works well. All the parameters in the request object are set to the cse object as well.
#RequestMapping(value = "/savecourse", method = RequestMethod.POST)
public #ResponseBody
Object saveLecturer(#Valid #ModelAttribute(value = "course") Course course,
BindingResult result) {
Map<String, Object> response = new HashMap<String, Object>();
if (result.hasErrors()) {
List<ObjectError> results = result.getAllErrors();
for (ObjectError objectError : results) {
System.out.println(objectError.getDefaultMessage());
}
response.put("message", "Could not add the Course to the system.");
} else {
try {
course.setId(courseDao.saveCourse(course));//returns the id
Course cse = new Course();
cse.setId(course.getId());
cse.setCourseName(course.getCourseName());
cse.setFee(course.getFee());
Lecturer lec = new Lecturer();
lec.setId(course.getLecturer().getId());
lec.setFirstName(course.getLecturer().getFirstName());
lec.setLastName(course.getLecturer().getLastName());
cse.setLecturer(lec);
cse.setGrade(course.getGrade());
response.put("course", cse);
} catch (Exception e) {
System.out.println(e);
}
}
return response;
}
Can you please tell me what is wrong in the first method?
Any help is greatly appreciated.

Categories

Resources