WSO2 Custom Mediator Set value for the Envelope - wso2

Deal All,
I'd create one custom mediator in my WSO2 ESB project at the OutSequence.
I would like to change the result in SOAP Envelope being send from the back end to the consumer. But with a little bit of adjustment to the data according to the result.
this is the SOAP Envelope
<soapenv:Bodyxmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<jsonObject>
<serviceRequestID>12345</serviceRequestID>
<statusCode>1</statusCode>
<errorCode></errorCode>
<errorDescription></errorDescription>
<addressID>1.23456794E9</addressID>
<source>consumer name</source>
<requestId>910514</requestId>
</jsonObject>
I want to create a custom mediator to set the Error Description base on the Error Code.
For example,
if error code 1 = error description = one
if error code 2 = error description = two
if error code 3 = error description = three
This is my custom mediator code.
private void ResponseLogging(MessageContext mc) throws OMException{
try {
String errorCode = mc.getEnvelope().getBody().getFirstElement().getFirstChildWithName(new QName("errorCode")).getText();
String errorDescription = null;
if(errorCode.equals("1")) {
errorDescription = "One";
}else if(errorCode.equals("2")) {
errorDescription = "Two";
}else if(errorCode.equals("3")) {
errorDescription = "Three";
}
mc.getEnvelope().getBody().getFirstElement().getFirstChildWithName(new QName("errorDescription")).setText(errorDescription);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
Expected response,
<soapenv:Bodyxmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<jsonObject>
<serviceRequestID>12345</serviceRequestID>
<statusCode>1</statusCode>
<errorCode>1</errorCode>
<errorDescription>One</errorDescription>
<addressID>1.23456794E9</addressID>
<source>consumer name</source>
<requestId>910514</requestId>
</jsonObject>
But now, I only get the error description as null.
kindly help. any advice would be great !
Thanks.
UPDATED !
Apparently, after set the value using the setText() method. The error description value change to One as expected in the log.
</statusCode><errorCode>1</errorCode><errorDescription>One</errorDescription>
But when the response is sent back to the client, it still null value.
{"serviceRequestID": "12345","statusCode": 1,"errorCode": "1", "errorDescription": "","addressID": 1.23456794E9,"source": "consumer name", "requestId": "910514"}

Try this;
private void ResponseLogging(MessageContext mc) throws OMException{
try {
String errorCode = mc.getEnvelope().getBody().getFirstElement().getFirstChildWithName(new QName("jsonObject")).getFirstChildWithName(new QName("errorCode")).getText();
String errorDescription = null;
if(errorCode.equals("1")) {
errorDescription = "One";
}else if(errorCode.equals("2")) {
errorDescription = "Two";
}else if(errorCode.equals("3")) {
errorDescription = "Three";
}
mc.getEnvelope().getBody().getFirstElement().getFirstChildWithName(new QName("jsonObject")).getFirstChildWithName(new QName("errorDescription")).setText(errorDescription);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}

Related

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

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

Not able to get slot values from user

I stuck in a issue, where I have to fill all slots from user.
Sharing required details -
I used Lex for writing Bot and intent Definition.
I exported Lex configuration to Alexa Skill kit.
Currently, I am facing issue, while fetching values of all slots of given intent from user.
Lambda code snippet -
#Override
public SpeechletResponse onIntent(SpeechletRequestEnvelope<IntentRequest> speechletRequestEnvelope) {
IntentRequest request = speechletRequestEnvelope.getRequest();
Session session = speechletRequestEnvelope.getSession();
log.info(String.format("onIntent. requestId : %s, sessionId : %s, Intent : %s", request.getRequestId(),
speechletRequestEnvelope.getSession().getSessionId(), speechletRequestEnvelope.getRequest().getIntent()));
Intent intent = request.getIntent();
String intentName = (intent != null) ? intent.getName() : null;
if ("HelloWorldIntent".equals(intentName)) {
return getHelloResponse();
} else if ("AMAZON.HelpIntent".equals(intentName)) {
return getHelpResponse();
} else if (LMDTFYIntent.MissingDrivesComplaint.name().equals(intentName)) {
return handleMissingDriveIntent(session, intent);
} else {
return getAskResponse("HelloWorld", "This is unsupported. Please try something else.");
}
}
private SpeechletResponse handleMissingDriveIntent(Session session, Intent intent) {
log.info(String.format("Executing intent : %s. Slots : %s", intent.getName(), intent.getSlots()));
Slot missingDriveSlot = intent.getSlot("missingDate");
Slot missingDrivesCountSlot = intent.getSlot("missingDrivesCount");
printSlots(intent.getSlots());
if(missingDriveSlot == null || missingDriveSlot.getValue() == null) {
printSlots(intent.getSlots());
log.info(String.format("Missing Drives slot is null"));
//return handleMissingDriveDialogRequest(intent, session);
ElicitSlotDirective elicitSlotDirective = new ElicitSlotDirective();
elicitSlotDirective.setSlotToElicit("missingDate");
SpeechletResponse speechletResponse = new SpeechletResponse();
speechletResponse.setDirectives(Arrays.asList(elicitSlotDirective));
SsmlOutputSpeech outputSpeech = new SsmlOutputSpeech();
outputSpeech.setSsml("On which date drives were missing");
speechletResponse.setOutputSpeech(outputSpeech);
return speechletResponse;
} else if(missingDrivesCountSlot == null || missingDrivesCountSlot.getValue() == null) {
printSlots(intent.getSlots());
log.info(String.format("Missing Drive Count is null"));
// return handleMissingDrivesCountDialogRequest(intent, session);
ElicitSlotDirective elicitSlotDirective = new ElicitSlotDirective();
elicitSlotDirective.setSlotToElicit("missingDrivesCount");
SpeechletResponse speechletResponse = new SpeechletResponse();
speechletResponse.setDirectives(Arrays.asList(elicitSlotDirective));
return speechletResponse;
} else if(missingDriveSlot.getValue() != null && missingDrivesCountSlot.getValue() != null) {
printSlots(intent.getSlots());
log.info(String.format("All slots filled."));
SpeechletResponse speechletResponse = new SpeechletResponse();
ConfirmIntentDirective confirmSlotDirective = new ConfirmIntentDirective();
speechletResponse.setDirectives(Arrays.asList(confirmSlotDirective));
return speechletResponse;
} else {
/*SpeechletResponse speechletResponse = new SpeechletResponse();
speechletResponse.setDirectives(Arrays.asList());*/
}
return null;
}
Check method -
handleMissingDriveIntent
Slots-
missingDate
missingDrivesCount
Question-
Amazon Echo Dot is saying - "There were a problem with a requested skill response". How can I figure out the reason ?
"There were a problem with a requested skill response"
Then Alexa responds to that error message back to you. That means there is a runtime error in your code.
You can check the CloudWatch logs from your lambda function (or using ask cli tool if you are using it). It can show you a line number where the error is happening. So you need to proceed from there.

Monitor HTTP NetBeans

Firstly I had a problem with the antiJARLocking attribute that was showing an error in the console:
WARNING [http-nio-8084-exec-69] org.apache.catalina.startup.SetContextPropertiesRule.begin [SetContextPropertiesRule] {Context} Setting property 'antiJARLocking' to 'true' did not find a matching property.
But I commented this part and it does not appear anymore.
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/DivulgueAqui"/>
<!-- antiJARLocking="true" -->
Then got a bug with the netbeans monitor
Showing this error:
The request can not be recorded most likely because the NetBeans HTTP Monitor module is disabled.
But in my last tests to get this error and put here for you this did not happen!
When I'm trying to run the web service it returns me code 500.
The information is arriving in the method and insert but when it arrives in the dao.insert (u);
The service stops working
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Path("usuario/inserir")
public String insertUsuario(String json){
UsuarioDao dao = new UsuarioDao();
Usuario u = new Usuario();
JSONObject jsonObject = null;
JSONParser parser = new JSONParser();
String nome;
String email;
String senha;
try {
jsonObject = (JSONObject) parser.parse(json);
nome = (String) jsonObject.get("nome");
email = (String)jsonObject.get("email");
senha = (String) jsonObject.get("senha");
u.setNome(nome);
u.setEmail(email);
u.setSenha(senha);
dao.inserir(u);
} catch (ParseException ex) {
System.out.println("WS.webService.insertUsuario()" + ex);
Logger.getLogger(webService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
My question is. How do I solve this problem?

How to verify for counter signed XML document?

How to verify the use library Xades4j for counter signed xml document.
Iam getting the following error when verifying with Xades4j :
xades4j.verification.CounterSignatureSigValueRefException:
Verification failed for property 'CounterSignature': the counter
signature doesn't reference the SignatureValue element of the
countersigned signature at
xades4j.verification.CounterSignatureVerifier.verify(CounterSignatureVerifier.java:75)
at
xades4j.verification.CounterSignatureVerifier.verify(CounterSignatureVerifier.java:37)
at
xades4j.verification.GenericDOMDataVerifier.verify(GenericDOMDataVerifier.java:65)
at
xades4j.verification.GenericDOMDataVerifier.verify(GenericDOMDataVerifier.java:30)
at
xades4j.verification.QualifyingPropertiesVerifierImpl.verifyProperties(QualifyingPropertiesVerifierImpl.java:59)
at
xades4j.verification.XadesVerifierImpl.verify(XadesVerifierImpl.java:187)
at
com.fit.einvoice.ingcountersigner.service.xades.XadesVerifyOperation.verifySignature(XadesVerifyOperation.java:92)
at
com.fit.einvoice.ingcountersigner.service.xades.XadesVerifyOperation.verifySignature(XadesVerifyOperation.java:87)
at
com.fit.einvoice.ingcountersigner.service.xades.XadesVerifyOperation.verifySignature(XadesVerifyOperation.java:64)
My validation function :
static void checkSigned(File file) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
XadesVerifyOperation verifyOperation = new XadesVerifyOperation();
ArrayList<XadesVerificationResults> results = verifyOperation.verifySignature(inputStream);
System.out.println("results size: " + results.size());
for (XadesVerificationResults result : results) {
System.out.println(result.SigningCertificate.getIssuerDN());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException ex) {
}
}
}
EDIT:
My counter signed function :
public void CounterSign() throws TransformerFactoryConfigurationError, Exception {
Document doc = SignatureServicesBase.getDocument(_inputStream);
Element sigElem = (Element) doc.getElementsByTagNameNS(Constants.SignatureSpecNS, Constants._TAG_SIGNATURE).item(0);
System.out.println(sigElem.getNodeName());
org.apache.xml.security.Init.init();
XMLSignature xmlSig = new XMLSignature(sigElem, doc.getBaseURI());
//Create counter signer
XadesBesSigningProfile signingProfile = new XadesBesSigningProfile(new Pkcs11KeyingDataProvider(_certInfo));
signingProfile.withAlgorithmsProvider(Sha1AlgProvider.class);
signingProfile.withBasicSignatureOptionsProvider(new MyBasicSignatureOptionsProvider(true, true, false));
final XadesSigner counterSigner = signingProfile.newSigner();
//Extend with counter signature
XadesFormatExtenderProfile extenderProfile = new XadesFormatExtenderProfile();
XadesSignatureFormatExtender extender = extenderProfile.getFormatExtender();
List unsignedProps = Arrays.asList(new CounterSignatureProperty(counterSigner));
extender.enrichSignature(xmlSig, new UnsignedProperties(unsignedProps));
SignatureServicesBase.outputDocument(doc, _outStream);
if (!_isStream) {
_inputStream.close();
_outStream.close();
}
}
I'm not sure I completely understood your question. If you're asking how to verify a counter signature property, it is already done as part of the verification of the "main" signature. Please note:
The same XadesVerifier is used for both the main signature and the counter signature.
If the validation succeeds, a property of type CounterSignatureProperty is added to the result.
You can access the property through the verification result of the main signature
XAdESVerificationResult res = ...;
CounterSignatureProperty p = res.getPropertiesFilter().getOfType(CounterSignatureProperty.class);
EDIT:
The message says everything: the counter signature is probably invalid. By definition, a counter signature must include a reference to the countersigned SignatureValue element.
Can you lookup the CounterSignature element on the original XML document and post it here?

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).