In my code I am using,
#RequestMapping(value = "/getBlueprintById", method = RequestMethod.GET)
public #ResponseBody BlueprintsMessage find(#FormDataParam("id") String id, final HttpServletResponse response) {
ResponseStatus status = null;
Long blueprintId = Long.parseLong(id);
response.setHeader("Cache-Control", "no-cache");
Iterable<Map<String, Object>> entity = null;
try {
entity = blueprintService.getBlueprintById(blueprintId);
status = new ResponseStatus(ResponseStatusCode.STATUS_OK, "SUCCESS");
} catch (Exception e) {
e.printStackTrace();
}
return new BlueprintsMessage(status, entity);
}
and the output value was,
{
"blueprint": {
"relation": [
{
"id": 1271,
"relationParam": [
{
"value": "{\"canaries\":\"1\",\"canary_watch_time\":\"30000-180000\",\"update_watch_time\":\"30000-180000\",\"max_in_flight\":\"4\"}"
}
]
}
]
}
}
I want to remove \ in my output and the output was same as Iterable<Map<String, Object>> type. The values saved into database, i just get the values from DB.
Related
I developed an OCR API using Flask to scan photos and return the scanned data. I want to call this API from Spring boot, So i can POST the photo to the API endpoint and get a response and use that response to map it to my POJO. When ever i put my photo using postman i get all Parameters as NULL. everything i did is correct. I converted the image and i sent it to the correct URL. I don't exactly know the problem here.
Flask API results with POSTMAN
{
"2": {
"adadFar": "ا 0",
"esmTijari": "PFE",
"esmTijariLatin": "EXAMPLE RNE",
"makarEjtima": "Shand! شارع الطيب",
"makarNachat": "شارع الطيب المهيري",
"nithamKanouni": "مسؤولية محدودة ald",
"rasMal": "1000000",
"tasmiya": "FACULTE DES SCIENCES",
"tasmiyaLatin": "LCS 3"
},
"adad_sejel: ": "F1700655698",
"modatCharika: ": "99",
"mouaref: ": "1887415R",
"nachatRaisi: ": "بيع الاعلاف و الالات الفلاحية و الصناعية",
"tarikh: ": "2015/09/29",
"tarikhBideyetNachat: ": "2001-12-6",
"tarikhEchhar: ": "2005-01-26"
}
Spring boot Result when POSTING the photo
{
"mouaref": null,
"adad_sejel": null,
"tarikh": null,
"tasmiya": null,
"tasmiyaLatin": null,
"esmTijari": null,
"esmTijariLatin": null,
"makarEjtima": null,
"makarNachat": null,
"nithamKanouni": null,
"rasMal": null,
"adadFar": null,
"nachatRaisi": null,
"tarikhBideyetNachat": null,
"tarikhEchhar": null,
"modatCharika": null
}
Here's my Pojo class:
public class formResponse {
private String mouaref;
private String adad_sejel;
private String tarikh;
private String tasmiya;
private String tasmiyaLatin;
private String esmTijari;
private String esmTijariLatin;
private String makarEjtima;
private String makarNachat;
private String nithamKanouni;
private String rasMal;
private String adadFar;
private String nachatRaisi;
private String tarikhBideyetNachat;
private String tarikhEchhar;
private String modatCharika;
\\getters and setters
public formResponse(){
}
Here's my Service class:
#Service
public interface FormRecognition {
public static formResponse getInfoClientFromRne(MultipartFile image) {
try {
formResponse form = new formResponse();
MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
bodyMap.add("image", new FileSystemResource(convert(image)));
// System.out.println("body map ;" + bodyMap.size());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyMap, headers);
// System.out.println("Headers: "+requestEntity.getHeaders());
// System.out.println("requestEntity ; "+requestEntity.toString());
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<formResponse> response = restTemplate.exchange("http://172.20.10.3:3500/upload-image", HttpMethod.POST, requestEntity,
formResponse.class);
form= response.getBody();
// System.out.println("form ; "+response);
// System.out.println("form ; "+form.getMouaref());
return form;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static File convert(MultipartFile file) {
File convertFile = new File(file.getOriginalFilename());
try {
convertFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convertFile);
fos.write(file.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertFile;
}
}
Here's my Controller:
#RestController
public class FileUploadController
{
#RequestMapping(value = "/upload", produces = {
MediaType.APPLICATION_JSON_VALUE }, method = RequestMethod.POST)
public formResponse upload(#RequestParam("image") MultipartFile[] image){
System.out.println("params: emtry");
try {
formResponse form = FormRecognition.getInfoClientFromRne(image[0]);
System.out.println("params: " + form);
return form;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Solved it! It turns out i was making ':' in the Flask response. That's why Spring boot couldn't read the response because it was different. I changed my Python script to match the exact naming in spring boot and that's when i got the data.
I have a case to transform a response from
Dogs API
to a different structure like this :
[
{
"breed": "pug",
"sub_breed": []
},
{
"breed": "ridgeback",
"sub_breed": [
{
"breed": "rhodesian",
"sub_breed": []
}
]
},
{
"breed": "doberman",
"sub_breed": []
},
{
"breed": "hound",
"sub_breed": [
{
"breed": "Ibizan",
"sub_breed": []
},
{
"breed": "afghan",
"sub_breed": []
}
]
}
]
I am confused after getting the response and don't know how to transform it.
Here is what I do until getting the response
public List<DogResponse> getDogs() {
List<DogResponse> response = new ArrayList<DogResponse>();
try {
String url = "https://dog.ceo/api/breeds/list/all";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = mapper.readValue(result.getBody().toString(), Map.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map.get("message")));
for (Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key : "+key);
System.out.println("val : "+value);
}
} catch (Exception e) {
// TODO: handle exception
}
return response;
}
DogResponse
public class DogResponse {
private String breed;
private DogResponse sub_breed;
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public DogResponse getSub_breed() {
return sub_breed;
}
public void setSub_breed(DogResponse sub_breed) {
this.sub_breed = sub_breed;
}
}
I am trying using Map but failed when I want to print the key and value, it's showing nothing.
You should map the response to List of DogResponse you may have an issue because of circular dependency.
List<DogResponse> dogs = mapper.readValue(jsonString, new TypeReference<List<DogResponse>>() {});
You can try this.
public List<DogResponse> getDogs() {
List<DogResponse> response = new ArrayList<DogResponse>();
try {
String url = "https://dog.ceo/api/breeds/list/all";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
ObjectMapper mapper = new ObjectMapper();
Map<String, Map<String, List<String>>> map = mapper.readValue(result.getBody().toString(), Map.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map.get("message")));
Map<String, List<String>> innerMap = map.get("message");
for (Entry<String, List<String>> entry : innerMap.entrySet()) {
String key = entry.getKey();
List<String> value = entry.getValue();
System.out.println("key : " + key);
System.out.println("val : " + value);
}
} catch (Exception e) {
// TODO: handle exception
}
return response;
}
ResponseEntity result = restTemplate.getForEntity(url, DogResponse.class);
This should work.
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);
}
}
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;
}
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.