Parse SOAP response and extract specific node using JAVA - java

I'm trying to interact with a SOAP service.
I'm able to get the SOAP response and by using Source sourceContent = soapResponse.getSOAPPart().getContent(); and transformer.transform(sourceContent, result); , I'm able to see what the output/response is and displaying it in the console.
But, I need to extract sessionID from the response and send that sessionID in a different SOAP request.
Please suggest me the extraction method, building a new SOAP request
Parsing is what I need to do!!
Below is the code for sending the request to the SOAP service:
public static void main(String args[]) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "https://WWW.DUMMYURL.COM";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
printSOAPResponse(soapResponse);
soapConnection.close();
}
catch (Exception e) {
System.err.println("Error occurred while sending SOAP Request to Server");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURN = "urn:DUMMYURL.COM";
String serverNS0 = "http://WWW.DUMMYURL.COM";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("urn", serverURN);
envelope.addNamespaceDeclaration("ns0", serverNS0);
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem1 = soapBody.addChildElement("login","urn");
SOAPElement soapBodyElem2 = soapBodyElem1.addChildElement("username","urn");
#SuppressWarnings("unused")
SOAPElement soapBodyElem3 = soapBodyElem2.addTextNode("USERNAME");
SOAPElement soapBodyElem4 = soapBodyElem1.addChildElement("password","urn");
#SuppressWarnings("unused")
SOAPElement soapBodyElem5 = soapBodyElem4.addTextNode("PASSWORD");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", "https://WWW.DUMMYURL.COM" + "login");
soapMessage.saveChanges();
//Print the request message
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
String source = sourceContent.toString();
System.out.print("\nResponse SOAP Message = ");
// Format it
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
System.out.println(transformer.toString());
}
Can someone please suggest me a snippet on how should I save the response I'm getting to a file locally?
Currently in the above code the response is getting displayed in the console.

You can use the writeTo method of the SOAPMessage interface to do the same, for example:
FileOutputStream out = new FileOutputStream("somefile");
soapResponse.writeTo(out);
Vinod.

Related

Sending SOAP request to a specific service

Okay, so I'm totally new to webservices and for a project I'm working on I'm trying to wrap my head around the whole SOAP thing. I think I have a vague understanding of what is going on, but I'm missing some specific information and I simply can't find anything helpful by googling.
I've read the questions others asked like this one SOAP request to WebService with java but I still can't fully figure out what is going on.
Specifically I'm trying to use the service provided here http://ec.europa.eu/taxation_customs/vies/vatRequest.html with its wsdl file here http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl
I tried adapting the example given in the above question, but I just can't figure out what values to add where so it works with this specific service. All I get is a "405 Method not allowed" response. Here is my attempted adaption:
package at.kmds.soaptest;
import javax.xml.soap.*;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
public class Main {
public static void main(String args[]) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://ec.europa.eu/taxation_customs/vies/vatRequest.html";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
printSOAPResponse(soapResponse);
soapConnection.close();
} catch (Exception e) {
System.err.println("Error occurred while sending SOAP Request to Server");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "http://ec.europa.eu/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("example", serverURI);
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("checkVat");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("countryCode");
soapBodyElem1.addTextNode("...");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("vatNumber");
soapBodyElem2.addTextNode("...");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "checkVat");
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.print("\nResponse SOAP Message = ");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
}
}
If someone could explain to me what exactly I'm doing wrong and how to fix it or maybe even give me a working example I'd be eternally grateful...
The code has to be slightly modified to hit the service.
String url = "http://ec.europa.eu/taxation_customs/vies/services/checkVatService";
is the endpoint you have to hit (this is from the wsdl)
<wsdlsoap:address location="http://ec.europa.eu/taxation_customs/vies/services/checkVatService"/>
Note that when i hit this , i get a soap fault.Looks like the SOAPBody constructed will have to be checked again.
Request SOAP Message = <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ec.europa.eu/"><SOAP-ENV:Header/><SOAP-ENV:Body><checkVat><countryCode>...</countryCode><vatNumber>...</vatNumber></checkVat></SOAP-ENV:Body></SOAP-ENV:Envelope>
Response SOAP Message = <?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode>soap:Client</faultcode><faultstring>Unexpected wrapper element checkVat found. Expected {urn:ec.europa.eu:taxud:vies:services:checkVat:types}checkVat.</faultstring></soap:Fault></soap:Body></soap:Envelope>
Edit a full program that works (looks like) , gives me invalid input because i am passing dots (...).
import javax.xml.namespace.QName;
import javax.xml.soap.*;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
public class Main {
public static void main(String args[]) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://ec.europa.eu/taxation_customs/vies/services/checkVatService";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
printSOAPResponse(soapResponse);
soapConnection.close();
} catch (Exception e) {
System.err.println("Error occurred while sending SOAP Request to Server");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "http://ec.europa.eu/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("tns1", "urn:ec.europa.eu:taxud:vies:services:checkVat:types");
envelope.addNamespaceDeclaration("impl", "urn:ec.europa.eu:taxud:vies:services:checkVat");
// SOAP Body
SOAPBody soapBody = envelope.getBody();
QName bodyQName = new QName("urn:ec.europa.eu:taxud:vies:services:checkVat:types",
"checkVat", "tns1");
SOAPElement soapBodyElem = soapBody.addChildElement(bodyQName);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement(new QName("urn:ec.europa.eu:taxud:vies:services:checkVat:types",
"countryCode", "tns1"));
soapBodyElem1.addTextNode("...");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement(new QName("urn:ec.europa.eu:taxud:vies:services:checkVat:types",
"vatNumber", "tns1"));
soapBodyElem2.addTextNode("...");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "checkVat");
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.print("\nResponse SOAP Message = ");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
}
}
Gives back
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>INVALID_INPUT</faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>

Java client using SAAJ error: SEVERE: SAAJ0008: Bad Response; Unauthorized

I have written a Java client code using SAAJ for Primevera P6 webservices. I am getting the below authentication error. I am providing the http username + password to the code but it gives error: SEVERE: SAAJ0008: Bad Response; Unauthorized. Could some one please help me with this issue. I am stuck in this problem since a long time. The wsdl of the web service is: https://sunpower-p6.oracleindustry.com/p6ws-token/services/ProjectService?wsdl.
ERROR:
Request SOAP Message =
11106
Jul 18, 2016 1:03:19 PM com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection post
SEVERE: SAAJ0008: Bad Response; Unauthorized
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Bad response: (401Unauthorized
My code:
public class TestClient {
/*
Method used to create the SOAP Request
*/
private static SOAPMessage createSOAPRequest() throws Exception {
// Next, create the actual message
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "http://xmlns.oracle.com/Primavera/P6/WS/Project/V2";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("ProjectService", serverURI);
//start: setting HTTP headers - optional, comment out if not needed
String authorization = Base64Coder.encodeString("xyz:abc");
MimeHeaders hd = soapMessage.getMimeHeaders();
hd.addHeader("Authorization", "Basic " + authorization);
//end: setting HTTP headers
// Create and populate the body
SOAPBody soapBody = envelope.getBody();
// Create the main element and namespace
SOAPElement soapBodyElem = soapBody.addChildElement("ReadProjects", "ProjectService");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("Field", "ProjectService");
SOAPElement soapBodyElem2 = soapBodyElem1.addChildElement("Id", "ProjectService");
soapBodyElem2.addTextNode("11106");
hd.addHeader("SOAPAction", serverURI + "ReadProjects");
// Save the message
soapMessage.saveChanges();
// Check the input
System.out.println("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
/**
* Method used to print the SOAP Response
*/
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
// Create the transformer
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// Extract the content of the reply
Source sourceContent = soapResponse.getSOAPPart().getContent();
// Set the output for the transformation
System.out.println("\nResponse SOAP Message = ");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
System.out.println();
}
public static void main(String[] args) throws Exception {
try {
// First create the connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
//System.out.println(soapConnection);
//Send SOAP Message to SOAP Server
String url = "https://sunpower-p6.oracleindustry.com/p6ws-token/services/ProjectService?wsdl";
// Send the message and get the reply
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
printSOAPResponse(soapResponse);
soapConnection.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
I realize this is an old question but would like to leave some assistance to anyone in the future who ends up here (like I did). There is a few likely situations that I have recently experienced regarding this.
Check that your details are correct, or that the connection is possible. Be 100% sure before moving on.
You will receive an unauthorized error if your database is not correctly configured for some setups (for instance, on JBoss). In my situation the data-source file was not being read properly when it attempted to connect causing the Unauthorized error on the client side.

Generate SOAP Message from java String

I wrote method, which generate soap message from java string:
private SOAPMessage createRequest(String msg) {
SOAPMessage request = null;
try {
MessageFactory msgFactory = MessageFactory.newInstance();
request = factory.createMessage();
SOAPPart msgPart = request.getSOAPPart();
SOAPEnvelope envelope = msgPart.getEnvelope();
SOAPBody body = envelope.getBody();
StreamSource _msg = new StreamSource(new StringReader(msg));
msgPart.setContent(_msg);
request.saveChanges();
} catch(Exception ex) {
ex.printStackTrace();
}
}
And, after that, I try generate some message. For example:
createRequest("test message");
But here - request.saveChanges(); I catch this exception:
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Error during saving a multipart message
Where is my mistake?
That is because you are not passing a correct protocol formatted message.
Your code doesn't specify which SOAP protocol you want to use, that means it creates a message factory for SOAP 1.1 messages.
Thus, you would need to pass a correct SOAP1.1 message.
I replicated your method like this:
private static SOAPMessage createRequest(String msg) {
SOAPMessage request = null;
try {
MessageFactory msgFactory = MessageFactory
.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
request = msgFactory.createMessage();
SOAPPart msgPart = request.getSOAPPart();
SOAPEnvelope envelope = msgPart.getEnvelope();
SOAPBody body = envelope.getBody();
javax.xml.transform.stream.StreamSource _msg = new javax.xml.transform.stream.StreamSource(
new java.io.StringReader(msg));
msgPart.setContent(_msg);
request.saveChanges();
} catch (Exception ex) {
ex.printStackTrace();
}
return request;
}
and I call it using this string:
String soapMessageString = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body></SOAP-ENV:Body></SOAP-ENV:Envelope>";
createRequest(soapMessageString);
and It works.

Java Created Soap Client is not getting response but same is working from SOAPUI

I am creating a simple soap client payload in java but server replied that "Server didn't recognize the value of http header". I copied the created soap payload and pasted in SOAP-UI and performed the request, the payload works perfectly.
I also double checked soap header information. Everything is correct. But still I am not getting response from my java client.
Can anyone provide me any idea on this?
public class SoapClientClass {
public static void main(String[] args) throws UnsupportedOperationException, SOAPException, IOException, TransformerException {
// TODO Auto-generated method stub
//Getting an instance of Soap Connection factory
SOAPConnectionFactory myFct = SOAPConnectionFactory.newInstance();
//Getting a Soap Connection from the soap connection factory object
SOAPConnection myCon = myFct.createConnection();
//Getting a message factory object to create a message
MessageFactory myMsgFct = MessageFactory.newInstance();
//Using the message factory to create a message
SOAPMessage message = myMsgFct.createMessage();
//Adding message to the body
SOAPPart mySPART = message.getSOAPPart();
SOAPEnvelope myEnvp = mySPART.getEnvelope();
myEnvp.addNamespaceDeclaration("web","http://www.webservicex.net/");
//SOAPHeader header = myEnvp.getHeader();
//javax.xml.soap.Name HeaderName = myEnvp.createName("GetGeoIP", "web","http://www.webservicex.net/");
//SOAPHeaderElement hltp = header.addHeaderElement(HeaderName);
SOAPBody body = myEnvp.getBody();
javax.xml.soap.Name bodyName = myEnvp.createName("GetGeoIP", "web","http://www.webservicex.net/");
SOAPBodyElement gltp = body.addBodyElement(bodyName);
javax.xml.soap.Name myContent = myEnvp.createName("IPAddress","web", "http://www.webservicex.net/");
SOAPElement mySymbol = gltp.addChildElement(myContent);
mySymbol.addTextNode("192.128.62.43");
message.saveChanges();
message.writeTo(System.out);
URLEndpoint endPt = new URLEndpoint("http://www.webservicex.net//geoipservice.asmx");
SOAPMessage reply = myCon.call(message, endPt);
//reply.writeTo(System.out);
System.out.println("\n");
TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();
Source sc = reply.getSOAPPart().getContent();
StreamResult result = new StreamResult(System.out);
tf.transform(sc, result);
System.out.println("test");
//conn.close();
SOAPBody body1 = reply.getSOAPBody();
if ( body1.hasFault() ) {
SOAPFault newFault = body1.getFault();
QName code = newFault.getFaultCodeAsQName();
String string = newFault.getFaultString();
String actor = newFault.getFaultActor();
System.out.println(string);
}
myCon.close();
//System.out.println(reply);
}
This is very old request but still answering if some one might run into similar issue. As per the error it is expecting HTTP header SOAPAction. Above code required two lines of HTTP header setting code.
SOAPEnvelope myEnvp = mySPART.getEnvelope();
MimeHeaders mheader=message.getMimeHeaders();
mheader.setHeader("SOAPAction", "http://www.webservicex.net/GetGeoIP");
myEnvp.addNamespaceDeclaration("web","http://www.webservicex.net/");

Java version of SoapClient

I have a working soaprequest in PhP and i'm trying to create a java program that requires the same call, However i am really struggeling to find the way to create the below php code in java, i have found numerus websites explaining soap requests in java but i cant seem to work how how to send the $param_auth array.
Any help would be most appreciated as i've been stuck on this for a while.
Thanks in advance.
$param_auth=array(
'user'=>$username,
'id'=>$userID,
'message'=>$userMessage
);
$soapclient = new soapclient(WebsiteAddress);
$data->_db = $soapclient->call('uploadMessage',$param_auth);
Finally solved my issue (Ive changed Element names etc.), using eclipse shows you the Soap envelope and XML response which i found useful for debugging the envelope).
Hope this helps anyone trying to do similar.
The "UploadMessage" is the "Login" string and the
$param_auth=array(
'user'=>$username,
'id'=>$userID,
'message'=>$userMessage
);
is the Username and Password, (Left out the Message part).
This code sends an Envelope like this the server:-
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:Login="Your URL"><SOAP-ENV:Header/><SOAP-ENV:Body><Login><UserName>YourUserName</UserName><Password>YourPassword</Password></Login></SOAP-ENV:Body></SOAP-ENV:Envelope>
Code To create the above Envelope is below:-
import javax.xml.soap.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
public class SoapCall {
public static void main(String args[]) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server.
String url = "Your URL";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
printSOAPResponse(soapResponse);
soapConnection.close();
} catch (Exception e) {
System.err.println("Error occurred while sending SOAP Request to Server");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest() throws Exception {
String YourUsername = "UserName";
String YourPassword = "Password";
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "Your URL";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("Login", serverURI);
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("Login");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("UserName");
soapBodyElem2.addTextNode(YourUserName);
SOAPElement soapBodyElem3 = soapBodyElem.addChildElement("Password");
soapBodyElem3.addTextNode(YourPassword);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "Login");
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
/**
* Method used to print the SOAP Response
*/
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.print("\nResponse SOAP Message = ");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
}
}

Categories