Add namespace prefix Axis2 - java

This is envelope which i wanna to send to service:
<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
<sear:searchUrls>
<sear:in0>Safeway, 200 S. 3rd St, Renton, WA</sear:in0>
</sear:searchUrls>
</soapenv:Body>
</soapenv:Envelope>
And this is code to construct it:
SOAPFactory fac = OMAbstractFactory.getSOAP12Factory();
SOAPEnvelope envelope = fac.getDefaultEnvelope();
OMNamespace omNs = fac.createOMNamespace("http://schemas.xmlsoap.org/soap/envelope/", "soapenv");
OMNamespace ns1 = fac.createOMNamespace("http://search", "sear");
envelope.setNamespace(omNs);
OMNamespace ns = fac.createOMNamespace("", "")
OMElement method = fac.createOMElement("sear:searchUrls", ns);
OMElement value = fac.createOMElement("sear:in0", ns);
value.setText("Safeway, 200 S. 3rd St, Renton, WA");
method.addChild(value);
envelope.getBody().addChild(method);
But my namespace prefix "sear" is not defined.
How can I set it in code to get
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sear="http://search">
in XML?

envelope.addNamespaceDeclaration("sear", "http://search");

OMNamespace xsi = soapFactory.createOMNamespace(
Constants.URI_DEFAULT_SCHEMA_XSI,
Constants.NS_PREFIX_SCHEMA_XSI);
envelope.declareNamespace(xsi);

Do you have the WSDL and know the end point url ?
You can generate the client side code using the wsdl2java convertor.
More information at http://axis.apache.org/axis2/java/core/docs/userguide-creatingclients.html#choosingclient

Related

How to apply a prefix to all Child elements in SOAP message

While structuring SOAP message having an issue with adding prefix to the subelement of ext:msg_LocationDetails element using QName and javax.xml.soap.Name
I'm using javax.xml.soap.SOAPFactory
When i try to use QName mag = new QName("","Messages","ext");
(new QName(namespaceURI, localPart, prefix))
Exception in thread "main" org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
at com.sun.org.apache.xerces.internal.dom.ElementNSImpl.setName(ElementNSImpl.java:149)
at com.sun.org.apache.xerces.internal.dom.ElementNSImpl.<init>(ElementNSImpl.java:80)
at com.su
It gives the above exception.
SOAPBody soapBody = soapEnvelope.getBody();
soapBody = soapMessage.getSOAPBody();
soapBody.setPrefix("soapenv");
// To add some element
SOAPFactory soapFactory = SOAPFactory.newInstance();
Name bodyName = soapFactory.createName("msg_LocationDetails");
SOAPBodyElement locationDetails = soapBody.addBodyElement(bodyName);
locationDetails.setPrefix("ext");
QName mag = new QName("","Messages","ext");
SOAPElement messages = locationDetails.addChildElement(mag);
//SOAPElement messages = locationDetails.addChildElement("Messages");
//messages.addNamespaceDeclaration("fir", "");
//SOAPElement message = messages.addChildElement("message");
Below is the SOAP message
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ext="http://extdomain.com/">
<soapenv:Header/>
<soapenv:Body>
<ext:msg_LocationDetails>
<ext:Messages>
<ext:Message>
<ext:Location>GSA</ext:Location>
<ext:LocCode>Unit</ext:LocCode>
<ext:LocID>00004</ext:LocID>
<ext:SystemID>TSKSLSLSJJ</ext:SystemID>
<ext:Status>
<ext:ID>4</ext:ID>
<ext:Name>PENDING</ext:Name>
</ext:Status>
</ext:Message>
</ext:Messages>
</ext:msg_LocationDetails>
</soapenv:Header/>
</soapenv:Body>

Soap Request using java - Request call format issue

I'm trying to make a SOAP call with this Java code:
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("UserAuthentication", serverURI);
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("UserAuthentication", "UserAuthentication");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("user_name", "UserAuthentication");
soapBodyElem1.addTextNode("pqr#xyz.com");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("password", "UserAuthentication");
soapBodyElem2.addTextNode("123");
soapMessage.saveChanges();
The required format of SOAP call (I'm trying to generate) is:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<UserAuthentication xmlns="http://tempuri.org/">
<user_name>string</user_name>
<password>string</password>
</UserAuthentication>
</soap:Body>
</soap:Envelope>
But the actual call generated by my code doesn't match the required format and is rejected at the receiving end, and I'm trying to figure out why and how to fix it:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:UserAuthentication="http://XXX.XXX.XXX.XXX:XXXX/Logininfo.asmx?op=UserAuthentication">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<UserAuthentication:UserAuthentication>
<UserAuthentication:user_name>pqr#xyz.com</UserAuthentication:user_name>
<UserAuthentication:password>123</UserAuthentication:password>
</UserAuthentication:UserAuthentication>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
What's the error message from the receiving end?
In any case, the namespaces for the UserAuthentication elements differ.
Expected: http://tempuri.org/
Actual: http://XXX.XXX.XXX.XXX:XXXX/Logininfo.asmx?op=UserAuthentication
envelope.addNamespaceDeclaration("UserAuthentication", serverURI);
Why are you adding that namespace when given you desired request it is not needed?
Try removing that line. Then this one:
SOAPElement soapBodyElem = soapBody.addChildElement("UserAuthentication", "UserAuthentication");
Make it:
QName bodyName = new QName("http://tempuri.org/",
"UserAuthentication", "m");
SOAPElement soapBodyElem = soapBody.addChildElement(bodyName);

How to create a SOAP Request like this in Java?

I am pretty new in the WebServices interrogation using Java and I have the following problem.
I have a web service that provide to me a getConfigSettings() method that, by its response, say to me some informations including whether a user is enabled or not on a certain service (it say if the couple username and password is correct and if the user can log into the system).
In particular I have the following REQUEST of the getConfigSettings() method:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>
<tem:getConfigSettings>
<!--Optional:-->
<tem:login>name.surname</tem:login>
<!--Optional:-->
<tem:password>rightPawssword</tem:password>
<!--Optional:-->
<tem:ipAddress>144.44.55.4</tem:ipAddress>
<!--Optional:-->
<tem:clientVersion>1</tem:clientVersion>
<!--Optional:-->
<tem:lastUpdateTime>2</tem:lastUpdateTime>
</tem:getConfigSettings>
</soapenv:Body>
</soapenv:Envelope>
And this is the webservice RESPONSE in case the couple username and password is correct and the user can log into the system:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<getConfigSettingsResponse xmlns="http://tempuri.org/">
<getConfigSettingsResult>
<![CDATA[
<root>
<status>
<id>0</id>
<message></message>
</status>
<drivers>
<drive id="tokenId 11">
<shared-secret>Shared 11</shared-secret>
<encoding>false</encoding>
<compression />
</drive>
<drive id="tokenId 2 ">
<shared-secret>Shared 2 </shared-secret>
<encoding>false</encoding>
<compression>false</compression>
</drive>
</drivers>
</root>
]]>
</getConfigSettingsResult>
</getConfigSettingsResponse>
</s:Body>
</s:Envelope>
In this response the important section is:
<status>
<id>0</id>
<message></message>
</status>
because <id>0</id> means that the user can log into the system
On the contrary if the couple username and password is incorrect I will obtain the following RESPONSE:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<getConfigSettingsResponse xmlns="http://tempuri.org/">
<getConfigSettingsResult><![CDATA[<root>
<status>
<id>-1</id>
<message>Login or password incorrect</message>
</status>
</root>]]></getConfigSettingsResult>
</getConfigSettingsResponse>
</s:Body>
</s:Envelope>
As you can see in this case I have that <id>-1</id> (that represent a situation of error) and in the message tag it specify the type of error occurred.
Ok, now I have to create a Java method that call this getConfigSettings() method passing to it the requested 5 parameters: login, password, ipAddress, clientVersion and lastUpdateTime (also if at this stage the only important parameters are login and password, the others can be whatever...)
And now I have no idea about how do it.
In my project there is another method that call another request report of the same web services that is:
public String getVersion() {
java.net.URL url = null;
java.net.URLConnection conn = null;
java.io.BufferedReader rd = null;
String soapResponse = "";
String risultato = "";
// SOAP ENVELOP for the request:
String soapRequest;
soapRequest = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">" + "<soapenv:Header/>" + "<soapenv:Body> " + "<tem:getVersion/>" + "</soapenv:Body>" + "</soapenv:Envelope>";
try {
// Try to open a connection
url = new java.net.URL(_webServiceUrl);
conn = url.openConnection();
// Set the necessary header fields
conn.setRequestProperty("SOAPAction", "http://tempuri.org/IMyService/getVersion");
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setDoOutput(true);
// Send the request:
java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(conn.getOutputStream());
wr.write(soapRequest);
wr.flush();
// Read the response
rd = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream()));
// Put the entire response into the soapResponse variable:
String line;
while ((line = rd.readLine()) != null) {
//System.out.println(line);
soapResponse = soapResponse + line + System.getProperty("line.separator");
}
rd.close();
// PERFORM SOME ELABORATION ON THE RESPONSE
..........................................
..........................................
..........................................
..........................................
return risultato;
}
Looking at this working method it seems to me that do something like that:
It create a String object that contain the SOAP Envelop for my request.
Try to connect to my WebService.
Then Set the necessary header fields (and this is not clear for me, what exactly mean? and what is tempuri?), what exactly do the following lines:
conn.setRequestProperty("SOAPAction", "http://tempuri.org/IMyService/getVersion");
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setDoOutput(true);
Send my prepared request to the WebService
Obtain the response and put it into my String soapResponse variable
This is what I want to obtain creating the other authentication() method, I have to create the SOAP Envelop using the previous parameters, send it to the webservice and obtain the SOAP response.
I think that my main problem is how to create the right String soapRequest object that use the parameter to do that.

Get Value from SOAP response

I have such a line:
SOAPMessage soapResponse = soapConnection.call(message, url);
and response looks:
HTTP/1.1 200 OK
Content-Type: text/xml;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 24 Jul 2013 07:44:39 GMT
Server: Apache-Coyote/1.1
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header>
<TransactionID soapenv:actor="http://schemas.xmlsoap.org/soap/actor/next" soapenv:mustUnderstand="1" xmlns="http://somelink"></TransactionID>
</soapenv:Header>
<soapenv:Body>
<soap-env:Fault xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
<soap-env:faultcode>Server</soap-env:faultcode>
<soap-env:faultstring>Server Error</soap-env:faultstring>
<soap-env:Detail>
<soap-env:Status>
<soap-env:StatusCode>3000</soap-env:StatusCode>
<soap-env:StatusText>Server Error</soap-env:StatusText>
<soap-env:Details></soap-env:Details>
</soap-env:Status>
</soap-env:Detail>
</soap-env:Fault>
</soapenv:Body>
</soapenv:Envelope>
how can i get StatusCode (3000) in String from such a soap response?
i tried soapResponse.getSOAPBody().... but all i could get was :status
EDIT:
so i did:
Detail detail = soapResponse.getSOAPPart().getEnvelope().getBody().getFault().getDetail();
Iterator detailEntries = detail.getDetailEntries();
while (detailEntries.hasNext()) {
SOAPBodyElement bodyElement = (SOAPBodyElement) detailEntries.next();
Iterator val = bodyElement.getChildElements();
while (val.hasNext()) {
SOAPBodyElement bodyElement2 = (SOAPBodyElement) val.next();
String val2 = bodyElement2.getValue();
logger.debug("The Value is:" + val2);
}
but got class cast exception
}
Edit2: Solution:
soapResponse.getSOAPPart().getEnvelope().getBody().getFault().getDetail().getTextContent().trim().substring(0, 4));
Starting from the SOAPMessage, you need to call SOAPMessage#getSOAPPart() to obtain a SOAPPart.
By calling SOAPPart#getEnvelope() you can obtain the SOAPEnvelope.
Next you get the SOAPBody using SOAPEnvelope#getBody().
Now you can get the SOAPFault by calling SOAPBody#getFault().
Next, you call SOAPFault#getDetail() to obtain the Detail.
Using Detail#getDetailIterator() you can iterate over all of the DetailEntrys in the Detail object.
Since the DetailEntry interface extends the SOAPElement interface, you can get its content by calling getChildElements(); that way you can navigate to the StatusCode element inside the Status element and get its value.
soapResponse.getBody().getFault().getFaultCode()
http://docs.oracle.com/javaee/5/api/javax/xml/soap/SOAPFault.html#getFaultCode()
and iterate on :
soapResponse.getBody().getFault().getDetailEntries()
http://docs.oracle.com/javaee/5/api/javax/xml/soap/Detail.html#getDetailEntries()

Soap response iterat in java

I am using java soap request and response in my code. I am getting the request and response properly.
But I am not able to iterate the response
Please see my response and code used to iterate below. Please help me to resolve this issue.
Response
<?xml version="1.0" encoding="utf-16"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetUserResponse xmlns="http://XXXX.com/XXXXXXXX.XXXXXXX.WS">
<GetUserResult>
user
<PersonID>111113</PersonID>
<Username>0987654321</Username>
<Password />
<FwyMember>Y</FwyMember>
<WebMember>Y</WebMember>
<FirstName>Mohamed</FirstName>
<Tier>firstclass</Tier>
<CountryOfResidence>IN</CountryOfResidence>
<PreferencesChanged>false</PreferencesChanged>
<FamilyRelationship />
<Title>Mr</Title>
<MiddleName />
........ continue like this
Java code
SOAPBody responseBody = response.getSOAPBody();
QName bodyName1 = new QName("http://XXXX.com/XXXXXXXX.XXXXXXX.WS","GetUserResponse");
java.util.Iterator iterator = responseBody.getChildElements(bodyName1);
while (iterator.hasNext()) {
SOAPBodyElement responseElement = (SOAPBodyElement)iterator.next();
String val = responseElement.getValue();
System.out.println("The values are "+val);
}
There is only one GetUserResponse element below Body. getChildElements only gets child elements, as opposed to descendant elements. You must first reach GetUserResponse and then iterate over its children.

Categories