Consume Realex JSON request -Spring MVC, Spring Boot - java

I need some help with writing a controller to consume a JSON response from a payment system (Realex).
So far, I have the following from the Realex documentation but can't figure out how to write the controller - i'm new to Spring Boot/Spring MVC.
RealexHpp realexHpp = new RealexHpp("Shared Secret");
HppResponse hppResponse = realexHpp.responseFromJson(responseJson);
// responseJson will be the Java variable containing the JSON response string
String result = hppResponse.getResult();
String message = hppResponse.getMessage();
String authCode = hppResponse.getAuthCode();
So far, i have written:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.realexpayments.hpp.sdk.RealexHpp;
import com.realexpayments.hpp.sdk.domain.HppResponse;
#Controller
public class PaymentController {
#RequestMapping(value = "/enrolment/confirmation", method = RequestMethod.GET, consumes = "text/plain")
public String process(#RequestBody String responseJson, Model model) throws Exception {
RealexHpp realexHpp = new RealexHpp("secret");
HppResponse hppResponse = realexHpp.responseFromJson(responseJson);
// responseJson will be the Java variable containing the JSON response string
String result = hppResponse.getResult();
String message = hppResponse.getMessage();
String authCode = hppResponse.getAuthCode();
System.out.println("Result: "+result);
System.out.println("Message: "+message);
System.out.println("AuthCode: "+authCode);
model.addAttribute("result", result);
model.addAttribute("message", message);
model.addAttribute("authcode", authCode);
return "enrolment/confirmation";
}
}

Looks like Spring MVC isn't the right tool here.
See: https://github.com/realexpayments/rxp-hpp-java
It's expecting you to use their SDK to generate the repsonseJson:
HppRequest hppRequest = new HppRequest()
.addAmount(100)
.addCurrency("EUR")
.addMerchantId("merchantId");
RealexHpp realexHpp = new RealexHpp("mySecret");
String requestJson = realexHpp.requestToJson(hppRequest);
You might want to be using Spring MVC to capture the parameters for the request.

Related

Post request to API using Jersey

I'm very new to web-service dev and I'm trying to make a POST request to an API using Jersey. The issue is I think I'm mixing documentation and example I'm finding online between client & server. I'm pretty sure that it's simple but I can't figure out why my code is failing.
Here is my main Class :
import deliveryPayload.Payload;
import jakarta.ws.rs.*;
import jakarta.ws.rs.client.*;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import org.apache.commons.lang3.StringUtils;
import responsePayload.ResponsePayload;
import java.net.URI;
import java.util.*;
#Path("/hook")
public class Hook {
private static final String apiToken = "myToken";
private static final String domain = "url";
private static final String apiUrl = "https://" + domain + "/api/v1/";
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Response eventHook(String body, #HeaderParam("Pass") String password) {
ObjectMapper objectMapper = new ObjectMapper();
Payload payload = new Payload();
try {
payload = objectMapper.readValue(body, Payload.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
EventsItem event = payload.getData().getEvents().get(0);
Actor actor = event.getActor();
Response response = ClientBuilder.newClient()
.target(getBaseURI())
.path("apps/" + "someID" + "/users")
.request(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, apiToken)
.post(Entity.entity(actor, MediaType.APPLICATION_JSON));
return response;
}
}
I'm getting this error Parse Error: The response headers can't include "Content-Length" with chunked encoding when using Postman.
Thanks for any help !

o.s.web.servlet.PageNotFound No mapping for GET

friend, I'm using RestController from spring data to consume data from external API.
When I use PostMan to get data, I get this 404 error code.
But if I use direct URL with a header on POSTMAN I get the correct data and response code 200
Could you please help me
Console Intelij
2018-11-13 17:30:42.334 WARN 11820 --- [nio-8080-exec-2] o.s.web.servlet.PageNotFound : No mapping for GET /toto
This my Controller Class
package com.controller;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.json.Json;
#RestController
#CrossOrigin("*") // pour gere les erreu d'ente ex: Orig
public class FlightRestServives {
private static Logger logger = Logger.getLogger(FlightRestServives.class.getName());
#Autowired
private RestTemplate restTemplate;
String serviceURL = "https://api.klm.com/opendata/flightoffers/reference-data?country=NL";
public FlightRestServives() {
}
//Consuming a service by GET method
// #GetMapping("/test")
#RequestMapping(
value = "/toto",
headers = {
"api-key=xmc3vburw886j9zqcsfrdu2t",
"AFKL-TRAVEL-Country=NL",
"AFKL-TRAVEL-Host=KL",
"X-Originating-IP=46.193.67.48"}
/*produces = "application/json",
consumes = "application/json",
headers = {
"api-key=xmc3vburw886j9zqcsfrdu2t",
"AFKL-TRAVEL-Country=NL",
"AFKL-TRAVEL-Host=KL",
"X-Originating-IP=46.193.67.48"}*/
)
public Json getAvailableOperations() {
logger.debug("Flight");
HttpHeaders headers = new HttpHeaders();
headers.add("api-key", "Keyyy");
headers.add("AFKL-TRAVEL-Country", "NL");
headers.add("AFKL-TRAVEL-Host", "KL");
headers.add("X-Originating-IP", "46.193.67.48");
HttpEntity requestEntity = new HttpEntity(headers);
logger.debug("request entities are: " + requestEntity);
return restTemplate.getForObject(serviceURL, Json.class);
/*return restTemplate
.exchange(
serviceURL,
HttpMethod.GET,
requestEntity,
Json.class
);*/
}
}

Spring boot Java post request

I am trying to do a simple post request from React (client side) to Java server side. Here is my controller below.
package com.va.med.dashboard.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.va.med.dashboard.services.VistaServiceImpl;
import gov.va.med.exception.FoundationsException;
#RestController
#RequestMapping("/dashboard")
public class DashboardController {
#Autowired
private VistaServiceImpl vistaService;
#RequestMapping("/main")
String home() {
return "main route";
}
#RequestMapping("/rpc")
String test() throws FoundationsException {
vistaService.myAuth();
return "this is rpc route";
}
#RequestMapping(method = RequestMethod.POST, produces =
"application/json", value = "/vista")
#ResponseStatus(value = HttpStatus.ACCEPTED)
public String getVistaConnection(#RequestBody String ipString, #RequestBody String portString, #RequestBody String accessPin,
#RequestBody String verifyPin) {
System.out.println(ipString);
System.out.println(portString);
System.out.println(accessPin);
System.out.println(verifyPin);
vistaService.connect(ipString, portString, accessPin, verifyPin); // TO-DO populate with serialized vars
if (vistaService.connected) {
return "Connected";
} else {
return "Not Connected";
}
}
}
Below is my react axios post request
axios.post('/dashboard/vista', {
ipString: this.state.ipString,
portString: this.state.portString,
accessPin: this.state.accessPin,
verifyPin: this.state.verifyPin
})
.then(function (response){
console.log(response);
})
.catch(function (error){
console.log(error);
});
This is also the error that I am getting.
Failed to read HTTP message:
org.springframework.http.converter.HttpMessageNotReadableException:
Required request body is missing:
Can anyone please shed some light on this error message? I'm coming from a pure JavaScript background so a lot of things I just don't know for Java because it is automatically implemented inside of JavaScrips language.
Thanks again in advance!
You're doing it wrong.
Instead of
public String getVistaConnection(#RequestBody String ipString, #RequestBody String portString, #RequestBody String accessPin,RequestBody String verifyPin)
You should wrap those parameters in a class:
public class YourRequestClass {
private String ipString;
private String portString;
....
// Getter/setters here
}
and your controller method will look like:
public String getVistaConnection(#RequestBody YourRequestClass request)
From #Rajmani Arya:
Since RestContoller and #RequestBody suppose to read JSON body, so in your axios.post call you should put headers Content-Type: application/json
Try to replace all #RequestBody annotations with #RequestParam
public String getVistaConnection(#RequestParam String ipString, #RequestParam String portString, #RequestParam String accessPin, #RequestParam String verifyPin)

Receiving "Request Entity Cannot be Empty" from paramaterized RESTful GET operation

New to java programming and still learning. I've built a RESTful service and I'm trying to pass in a parameter for a GET routine and I'm getting back a state 400 saying that the "Request entity cannot be empty". When I call the non-parameterized GET, the data comes back just fine. I've stripped down all the functionality of the parameterized GET to just return a simple string and I'm still getting the same message. Searched all over and can't find anything that's very helpful.
Below is the code that I'm running for the service. The method "GetChildAllInfo" makes a call to a local mySQL instance and returns a list of objects; that one works just fine. The parameterized one returns nothing, not even an exception.
Any help would be tremendously appreciated. Even if it's a ridiculously simple solution like a syntax error that I may have missed. AND I'm willing to accept any other advice on what you see in the code as well. Thanks!
package allowanceManagerChild;
import java.util.Set;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.core.MediaType;
import com.google.gson.Gson;
#Path("allowanceManagerChild")
public class AllowanceManagerChild {
#Context
private UriInfo context;
/**
* Creates a new instance of AllowanceManagerChild
*/
public AllowanceManagerChild() {
}
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getJson() {
String response = "";
Set<Child> children = Child.GetAllChildInfo();
for (Child child : children){
Gson gson = new Gson();
String json = gson.toJson(child);
response = response + json;
}
return response;
}
#GET
#Path("/{childID}")
#Produces(MediaType.APPLICATION_JSON)
public String getJson(int childID) {
String response = "";
try{
// Set<Child> children = Child.GetChildInfo(id);
// for (Child child : children){
// Gson gson = new Gson();
// String json = gson.toJson(child);
// response = response + json;
// }
response = "Made it here"; //Integer.toString(childID);
}
catch(Exception e){
response = e.toString();
}
return response;
}
/**
* PUT method for updating or creating an instance of AllowanceManagerChild
* #param content representation for the resource
*/
#PUT
#Consumes(MediaType.APPLICATION_JSON)
public void putJson(String content) {
}
}
Adding the #PathParam annotation to the method parameter might help:
#GET
#Path("/{childID}")
#Produces(MediaType.APPLICATION_JSON)
public String getJson(#PathParam("childID") int childID) {
See the RESTful Web Services Developer's Guide for more details.

android json data to spring mvc4

I am new to using Spring mvc4 annotation . In all i want to do is using spring mvc as a web service . so i would be thankful if anyone could provide me a solution for it.
My android code is as:
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpPost httppost = new HttpPost( "http://localhost:8080/datarequest");
JSONObject json = new JSONObject();
json.put("action", "check_login");
json.put("username","name");
json.put("password", "password");
JSONArray postjson = new JSONArray();
postjson.put(json);
httppost.setHeader("json", json.toString());
httppost.getParams().setParameter("jsonpost", postjson);
System.out.println(postjson);
HttpResponse response = httpclient.execute(httppost);
so far i wrote the web service as:
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
#Controller
#RequestMapping("/datarequest")
public class HelloController {
#RequestMapping(method = RequestMethod.GET)
public String getMethod(ModelMap model) {
System.out.println("GET");
return "hello";
}
#RequestMapping(method = RequestMethod.POST, produces = "application/json")
public String getMethod(ModelMap model) {
System.out.println("POST");
System.out.println("here i want to print json data send from the android ");
return "hello";
}
}
You can use #RequestBody and map it to required class structure. You can refer this SO question #RequestBody and #ReponseBody spring.
To test, you can map it to String. See below example.
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestHeader;
#RequestMapping(method = RequestMethod.POST, produces = "application/json")
public #ResponseBody String getMethod(#RequestHeader(value="json") String headerStr) {
System.out.println("POST");
System.out.println(s);
return "hello";
}
You can add below maven entry in your pom.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.1</version>
</dependency>

Categories

Resources