Response not coming back from one service to another service - microservices - web-services

I am facing strange issue where response as string not coming back from one service to another service. we have created microservices where one service is calling another service. i can see response printed in logs . after that line immediately i am returning that response but its coming back as null.
I created similar method with same code and it works fine. I have put code for calling service and service method from which i am returning response.
controller:
#RequestMapping(value = "/test/save", method = RequestMethod.POST)
#ResponseBody
public String save(#RequestBody Calculation calculation,
HttpServletRequest request) {
logger.info("In .save");
String result = "false";
try {
result = CalService.save(calculation);
logger.info("Response from service is :" + result);
} catch (Exception e) {
logger.error("Exception occured in save:", e);
}
return result;
}
method call client :
public String saveCal(Calculation calculation) {
String result = null;
try {
logger.info("In save");
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("REMOTE_USER", "test");
HttpEntity<Calculation> request = new HttpEntity<Calculation>(Calculation, headers);
RestTemplate template = new RestTemplate();
template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
result = template.postForObject(url+"/test/save", request, String.class);
} catch (Exception e) {
logger.error("Exception occured in SaveMddMd", e);
result = "fail";
}
logger.info("Save"+result);
return result;
}
result returned is success or failure.
I can see result printed in controller as success but when it comes back to client it prints as null. I created exact same method with different signature which returns result as success. we are using microservices here.
Jordan

Related

Junit Unable to return mocked Response and return as null

I m new to Mockito and trying to mock the webservice responses, I did tried mocking at some extent few Objects got worked, But the end mocked WebResponse is always returning null.
Service Method i am going to test:getWebResponse Method
public WebResponse getWebResponse(String crmNumber) throws JSONException, ExecutionException, WebException {
Map<String, String> HEADERS_POST = new HashMap<String, String>() {
{
put(WebUtil.HEADER_CONTENT, WebUtil.CONTENT_JSON);
put(WebUtil.HEADER_ACCEPT, WebUtil.CONTENT_JSON);
}
};
JSONObject requestJson = new JSONObject();
requestJson.put("crmNumber", crmNumber);
requestJson.put("application", "ABCD");
requestJson.put("feature", "DDDFL");
// Using internal web service becuase device authentication is done separately.
String url = CommonUtil.getServiceBaseUrl(true) + "/ett";
WebServiceClient client = WebServiceClientRegistry.getClient(ApacheCustom.class);
WebRequest webReq = new GenericWebRequest(WebRequestMethod.POST, url, HEADERS_POST, requestJson.toString());
// Till here i m getting all mocked object (client also Mocked) after this stament the webRes is returning null;
WebResponse webRes = client.doRequest(webReq);
return webRes;
}
And here the test Method:
#Test
public void getWebResponseTest() {
mockStatic(CommonUtil.class);
mockStatic(WebServiceClientRegistry.class);
this.webResponse = new GenericWebResponse(200, "", new HashMap(), "");
try {
Mockito.when(CommonUtil.getServiceBaseUrl(true)).thenReturn("https://stage.com/service");
WebRequest webReq = new GenericWebRequest(WebRequestMethod.POST, "https://stage.com/service", new HashMap(), "");
Mockito.when(WebServiceClientRegistry.getClient(ApacheCustom.class)).thenReturn(client);
Mockito.when(client.doRequest(webReq)).thenReturn(this.webResponse);
WebResponse wesponse = this.ServiceResponse.getWebResponse("Number");
Assert.assertEquals(wesponse.getStatusCode(), 200);
} catch (Exception e) {
Assert.fail();
}
}
But the getWebResonse method from Test class always returning null Response(Even Though it is mocked)
You mock client.doRequest as follows:
Mockito.when(client.doRequest(webReq)).thenReturn(this.webResponse);
but you create a new instance of WebRequest in your service under test.
You call doRequest with a different argument than recorded in your test.
Arguments are compared with equals.
Most likely WebRequest does not override equals, so recorded interaction is ignored and a default response (null) is rerurned.
I guess WebResuest may not be the code you own (you haven’t specified this in your question), so it may be impossible to override it.
Thus, you can use a different argument matcher.
You can use ArgumentMatchers.any() for good start, or implement a custom argument matcher.

Issue with a WS verifier method when migrating from Play 2.4 to Play 2.5

I have a method I need to refactor, as F.Promise has been deprecated in Play 2.5. It's pretty readable actually. It sends a request and authenticates via a custom security token and returns true if the response is 200.
public boolean verify(final String xSassToken){
WSRequest request = WS.url(mdVerifyXSassTokenURL)
.setHeader("X-SASS", xSassToken)
.setMethod("GET");
final F.Promise<WSResponse> responsePromise = request.execute();
try {
final WSResponse response = responsePromise.get(10000);
int status = response.getStatus();
if(status == 200 ) { //ok
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
First thing I had to do was change this line:
final F.Promise<WSResponse> responsePromise = request.execute();
To this:
final CompletionStage<WSResponse> responsePromise = request.execute();
However, CompletionStage(T) doesn't have an equivalent get() method so I'm not sure the quickest and easiest way to get a WSResponse that I can verify the status of.
Yes, it does not. At least not directly.
What you are doing is "wrong" in the context of PlayFramework. get is a blocking call and you should avoid blocking as much as possible. That is why WS offers a non blocking API and a way to handle asynchronous results. So, first, you should probably rewrite your verify code to be async:
public CompletionStage<Boolean> verify(final String xSassToken) {
return WS.url(mdVerifyXSassTokenURL)
.setHeader("X-SASS", xSassToken)
.setMethod("GET")
.execute()
.thenApply(response -> response.getStatus() == Http.Status.OK);
}
Notice how I'm using thenApply to return a new a java.util.concurrent.CompletionStage instead of a plain boolean. That means that the code calling verify can also do the same. Per instance, an action at your controller can do something like this:
public class MyController extends Controller {
public CompletionStage<Result> action() {
return verify("whatever").thenApply(success -> {
if (success) return ok("successful request");
else return badRequest("xSassToken was not valid");
});
}
public CompletionStage<Boolean> verify(final String xSassToken) { ... }
}
This way your application will be able to handle a bigger workload without hanging.
Edit:
Since you have to maintain compatibility, this is what I would do to both evolve the design and also to keep code compatible while migrating:
/**
* #param xSassToken the token to be validated
* #return if the token is valid or not
*
* #deprecated Will be removed. Use {#link #verifyToken(String)} instead since it is non blocking.
*/
#Deprecated
public boolean verify(final String xSassToken) {
try {
return verifyToken(xSassToken).toCompletableFuture().get(10, TimeUnit.SECONDS);
} catch (Exception e) {
return false;
}
}
public CompletionStage<Boolean> verifyToken(final String xSassToken) {
return WS.url(mdVerifyXSassTokenURL)
.setHeader("X-SASS", xSassToken)
.setMethod("GET")
.execute()
.thenApply(response -> response.getStatus() == Http.Status.OK);
}
Basically, deprecate the old verify method and suggest users to migrate to new one.

java.lang.classcastexception - SOAP Fault - Using KSOAP2 in Android

Searched quite a bit. The problem with these errors is that while the text might appear the same, the problem is always different.
My service takes ONE string value and returns a string response. Here is my code:
private class UploadStats extends AsyncTask<String, Void, String>
{
private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
private static final String SOAP_ADDRESS = "http://192.168.1.101/rss/RSS_Service.asmx?WSDL";
private static final String INSERTURLACTION = "http://192.168.1.101/rss/RSS_Service.asmx/InsertURL";
private static final String INSERTURLMETHOD = "InsertURL";
#Override
protected String doInBackground(String... url)
{
String status = "";
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
INSERTURLMETHOD);
request.addProperty("url", "www.yahoo.com");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try
{
httpTransport.call(INSERTURLACTION, envelope);
SoapObject response = (SoapObject) envelope.bodyIn;
status = response.getProperty(0).toString();
}
catch (Exception exception)
{
Log.d("Error", exception.toString());
}
if(status.equals("1"))
{
Log.d("InsertURL", "New URL Inserterd");
}
else if(status.equals("0"))
{
Log.d("InsertURL", "URL Exists. Count incremented");
}
else
{
Log.d("InsertURL", "Err... No");
}
return status;
}
}
I get the error:
java.lang.classcastexception org.ksoap2.SoapFault
What am I doing wrong? If any more details are needed, I can add them.
The error was related to the webservice.
An incorrect namespace on the service side can cause this error (as can a lot of other problems).
Best way to check is to run the webservice on the local machine (where the service is hosted).

How to get HttpServletRequest in Liferay WebService

Hi I have a webService that is generated from buildServices of Liferay..
the method looks like this
public User getUserTest(long userId) {
User u = null;
try {
Token token = OAuthFactoryUtil.createToken("sasa", "sdad");
} catch (OAuthException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
u = UserLocalServiceUtil.getUser(userId);
System.out.println("xx user " + u.getScreenName());
} catch (Exception e) {
System.out.println(" Exception ************* " + e.toString());
}
return u;
}
the parameters in this ws would be this :
http://localhost:8080/demo-portlet/api/json?serviceClassName=com.sample.portlet.library.service.BookServiceUtil&serviceMethodName=getUserTest&userId=10195&serviceParameters=[userId]
having userId as a parameter..
How would you pass a parameter if you need HttpServletRequest.. my method would look like this
public User getUserTest(HttpServletRequest httpRequest) {
User u = null;
try {
String version = httpRequest.getHeader("X-PHM-APP-VERSION");
Token token = OAuthFactoryUtil.createToken("sasa", "sdad");
} catch (OAuthException e1) {
e1.printStackTrace();
}
try {
String authorization = httpRequest.getHeader("Authorization");
u = UserLocalServiceUtil.getUser(Long.valueOf(authorization));
System.out.println("authorization --> " + authorization);
System.out.println("xx user " + u.getScreenName());
} catch (Exception e) {
System.out.println(" Exception ************* " + e.toString());
}
return u;
}
I need the HttpServletRequest to get the parameters from header, instead of passing through url. Is there a better way to get parameters from header? thanks for your help
I think webservice layer is normally at a later stage where in you would never pass request. Ideally what you would do is pass header parameter to the webservice instead of request
In Liferay, you will get HttpServletRequest from the PortletRequest. Please use com.liferay.portal.util.PortalUtil class.
There are 2 methods in it. getHttpServletRequest() and getOriginalServletRequest(), you will get the both core level http request from these methods.

How to send additional fields to soap handler along with soapMessage?

I am logging RequestXML for a webservice client using SoapHandler as follows
public boolean handleMessage(SOAPMessageContext smc) {
logToSystemOut(smc);
return true;
}
private void logToSystemOut(SOAPMessageContext smc) {
Boolean outboundProperty = (Boolean)
smc.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
out.println("\nOutbound message:");
} else {
out.println("\nInbound message:");
}
SOAPMessage message = smc.getMessage();
try {
message.writeTo(out);
out.println("");
} catch (Exception e) {
out.println("Exception in handler: " + e);
}
}
Got a new requirenment to add this xml to DB along with some extra values(which are not present in the xml). Is there any way I can pass few additional fields to above soap handler (in handleMessage method)?
Please note that changing the xml/WSDL or adding this to SOAP message header is not an option for me as it is owned by other interface. Any other solution?
Thanks!
You can cast your service class to a class of type "BindingProvider". In this form you can use it to assign it objects which you can access later from your SOAPHandler. Another useful usage is that you also can change the endPoint URL this way.
Before calling the service you do:
MySoapServicePortType service = new MySoapService().getMySoapServicePort();
BindingProvider bp = (BindingProvider)service;
MyTransferObject t = new MyTransferObject();
bp.getRequestContext().put("myTransferObject", t);
TypeResponse response = service.doRequest();
SOAPMessage message = t.getRequestMessage(message);
From your logging function you do:
private void logToSystemOut(SOAPMessageContext smc) {
...
MyTransferObject t = (MyTransferObject) messageContext.get("myTransferObject");
if (outboundProperty.booleanValue())
t.setRequestMessage(message);
else
t.setResponseMessage(message);
...
}