How to add child nodes to childNode in SOAP HEader? - java

I am trying to create children nodes inside and it should look like the following
<soapenv:Header>
<wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-21" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:Username>USER</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">PAASS</wsse:Password>
<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">==</wsse:Nonce>
<wsu:Created>2012-02-22T16:27:29.088Z</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
with the following
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPElement userNameToken = envelope.getHeader().addChildElement("Usernametoken", WSSE_NS_PREFIX, WSSE_NS);
SOAPElement user = userNameToken.addChildElement("UserName", WSSE_NS, WSSE_NS_PREFIX);
i get the following error when attemping to do so:
NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.

It seems that you mixed order of arguments (WSSE_NS vs WSSE_NS_PREFIX)
It should be
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPElement userNameToken = envelope.getHeader().addChildElement("Usernametoken", WSSE_NS_PREFIX, WSSE_NS);
SOAPElement user = userNameToken.addChildElement("UserName", WSSE_NS_PREFIX, WSSE_NS);

Related

Customize SOAPEnvelope on SOAP webservice in Java

I have a SOAP web service. When it is called, I return a response this way:
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "...")
#ResponsePayload
public JAXBElement<MyResponseObject> mySoapService(#RequestPayload MyRequestObject request) {
MyResponseObject res = new MyResponseObject();
res.setField("my field content");
...
return createJaxbElementWithPrefix(res, MyResponseObject.class, "prefix");
}
Testing with SoapUI, the returned XML is
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<prefix:MyResponseObject xmlns:prefix="http://..url">
<field>my field content</field>
</prefix:MyResponseObject>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Unfortunately, for some reason that's beyond my control, the systems who calls my service, expects the prefix namespace in the envelope, so something like this:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:prefix="http://..url">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<prefix:MyResponseObject>
<field>my field content</field>
</prefix:MyResponseObject>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
This brings to my problem. I need to manually modify the Envelope, but I can't find a way. Could someone help me?

Apache CXF Client for Microsoft WCF service with MTOM returning 400

I have an apache CXF client for a Microsoft WCF service, and I am attempting to send a file via MTOM. However, I keep getting a 400, and the error on the WCF side according to the partner is that there is an error creating the MTOM reader
I've traced the outbound message, and it looks like this:
INFO: Outbound Message
---------------------------
ID: 1
Address: https://someserver.com/ImportService.svc?wsdl
Encoding: UTF-8
Http-Method: POST
Content-Type: multipart/related; type="application/xop+xml"; boundary="uuid:1d46d7c9-047b-440d-928b-ab8689ab5e6f"; start="<root.message#cxf.apache.org>"; start-info="application/soap+xml; action=\"http://tempuri.org/IImportService/UploadFile\""
Headers: {Accept=[*/*], Accept-Encoding=[gzip;q=1.0, identity; q=0.5, *;q=0], Content-Encoding=[gzip]}
Payload: --uuid:1d46d7c9-047b-440d-928b-ab8689ab5e6f
Content-Type: application/xop+xml; charset=UTF-8; type="application/soap+xml; action=\"http://tempuri.org/IImportService/UploadFile\""
Content-Transfer-Encoding: binary
Content-ID: <root.message#cxf.apache.org>
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soap:mustUnderstand="true">
<wsse:UsernameToken wsu:Id="UsernameToken-e51a6fdd-5053-4aae-a9fb-363dde7d9e77">
<wsse:Username>blah#test.com</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">mypassword</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
<ns2:letterOptions xmlns="http://schemas.datacontract.org/2004/07/PublicServices.Import" xmlns:ns2="http://tempuri.org/">
<EnableQBPlanConsolidation>false</EnableQBPlanConsolidation>
<MASKSSN>true</MASKSSN>
<SRPrintedNumberofDays>2</SRPrintedNumberofDays>
<SuppressAllLetters>false</SuppressAllLetters>
<SuppressNewMemberLoginLetter>false</SuppressNewMemberLoginLetter>
<SuppressTakeOverLetterForTermed>false</SuppressTakeOverLetterForTermed>
<SuppressTerminationLetter>false</SuppressTerminationLetter>
</ns2:letterOptions>
<ns2:JobQueueType xmlns="http://schemas.datacontract.org/2004/07/PublicServices.Import" xmlns:ns2="http://tempuri.org/">Import</ns2:JobQueueType>
<Filename xmlns="http://tempuri.org/">testImport.csv</Filename>
<Action xmlns="http://www.w3.org/2005/08/addressing">http://tempuri.org/IImportService/UploadFile</Action>
<MessageID xmlns="http://www.w3.org/2005/08/addressing">urn:uuid:f380e4cc-225f-4b7d-bd46-6b5d607a59ca</MessageID>
<To xmlns="http://www.w3.org/2005/08/addressing">https://someserver.com/ImportService.svc?wsdl</To>
<ReplyTo xmlns="http://www.w3.org/2005/08/addressing">
<Address>http://www.w3.org/2005/08/addressing/anonymous</Address>
</ReplyTo>
</soap:Header>
<soap:Body>
<FileUploadMessage xmlns="http://tempuri.org/" xmlns:ns2="http://schemas.datacontract.org/2004/07/PublicServices.Import" xmlns:ns3="http://schemas.microsoft.com/2003/10/Serialization/">
<FileByteStream>
<xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:68e0408d-81da-496b-a06c-24a0459207d1-1#tempuri.org"/>
</FileByteStream>
</FileUploadMessage>
</soap:Body>
</soap:Envelope>
--uuid:1d46d7c9-047b-440d-928b-ab8689ab5e6f
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
Content-ID: <68e0408d-81da-496b-a06c-24a0459207d1-1#tempuri.org>
[VERSION],1.0
[NPM],552652222,1,Basic Client,Basic Client,Bob,Z,Jones,MR,bjones#test.com,402444555,,1234 Some street,,Omaha,NE,68123,,M,T,F,F
--uuid:1d46d7c9-047b-440d-928b-ab8689ab5e6f--
I've found plenty of other instances where other folks had the same issue:
https://coderanch.com/t/224995/java/Apache-CXF-MTOM-enabled-WCF
HTTP Bad Request error when requesting a WCF service contract
http://mail-archives.apache.org/mod_mbox/cxf-users/201211.mbox/%3CCAPXLCrCLkSkC8dQFeuU8DLY6gne1SOhwT9eMDxAUxLudnqU+YA#mail.gmail.com%3E
None of these were able to resolve my issue. I've tried multiple different versions of CXF and I get the same error with all of them.
This is a consolidated version of the code that is calling the service:
JaxWsProxyFactoryBean proxyFactory = new JaxWsProxyFactoryBean();
proxyFactory.setBindingId(SOAPBinding.SOAP12HTTP_MTOM_BINDING);
proxyFactory.setServiceClass(IImportService.class);
proxyFactory.setAddress(proxyEndpoint);
proxyFactory.getFeatures().add(new WSAddressingFeature());
IImportService importService = (IImportService) proxyFactory.create();
Client client = (Client) importService;
LetterOptions letterOptions = new LetterOptions();
letterOptions.setSRPrintedNumberofDays(2);
letterOptions.setMASKSSN(true);
letterOptions.setEnableQBPlanConsolidation(false);
List<Object> headerList = new ArrayList<>();
headerList.add(new Header(new QName("http://tempuri.org/", "letterOptions"),
letterOptions, new JAXBDataBinding(LetterOptions.class)));
headerList.add(new Header(new QName("http://tempuri.org/", "JobQueueType"), JobQueueType.IMPORT, new JAXBDataBinding(JobQueueType.class)));
headerList.add(new Header(new QName("http://tempuri.org/", "Filename"), "testImport.csv", new JAXBDataBinding(String.class)));
client.getRequestContext().put(Header.HEADER_LIST, headerList);
client.getEndpoint().getActiveFeatures().add(new LoggingFeature());
client.getInInterceptors().add(new GZIPInInterceptor());
client.getInInterceptors().add(new LogResponseInterceptor());
GZIPOutInterceptor outInterceptor = new GZIPOutInterceptor();
outInterceptor.setForce(true);
client.getOutInterceptors().add(outInterceptor);
Map props = new HashMap();
props.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
props.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
props.put(WSHandlerConstants.PW_CALLBACK_CLASS, PasswordCallbackHandler.class.getName());
props.put(WSHandlerConstants.USER, "blah#test.com");
WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(props);
client.getOutInterceptors().add(wssOut);
HTTPConduit conduit = (HTTPConduit) client.getConduit();
HTTPClientPolicy policy = conduit.getClient();
if(policy == null) {
policy = new HTTPClientPolicy();
}
policy.setAllowChunking(false);
FileUploadMessageReponse response = importService.uploadFile(fileUploadMessage);
One interesting tidbit is that I can copy the same request that is being logged into SoapUI, and it works fine.

wrong SOAP request getting created

This is what my code is creating:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://example.com">
<soapenv:Header/>
<soapenv:Body>
<ws:isUserExists>
<userId>10</userId>
</ws:isUserExists>
</soapenv:Body>
</soapenv:Envelope>
In my soapenv:Envelope || xmlns:soapenv is coming twice
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
Now this is what I need:
here xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" is not present in the SOAP request
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/ " xmlns:ws="http://example.com">
<soapenv:Header/>
<soapenv:Body>
<ws:isUserExists>
<userId>10</userId>
</ws:isUserExists>
</soapenv:Body>
</soapenv:Envelope>
The java code which I am using to create the request is:
public static SOAPMessage createIsUserExistsSOAPRequest(User user) throws SOAPException
{
MessageFactory messageFactory =MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
soapMessage.getSOAPHeader().setPrefix("soapenv");
SOAPPart soapPart = soapMessage.getSOAPPart();
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.setPrefix("soapenv");
envelope.addNamespaceDeclaration("ws","http://example.com");
// SOAP Body
SOAPBody soapBody = envelope.getBody();
soapBody.setPrefix("soapenv");
SOAPElement ensureUserExistsElem = soapBody.addChildElement("isUserExists", "ws");
SOAPElement userIdElem = ensureUserExistsElem.addChildElement("userId");
userIdElem.addTextNode(user.userId);
String authorization = new sun.misc.BASE64Encoder().encode(("someid#gmail.com").getBytes());
MimeHeaders hd = soapMessage.getMimeHeaders();
hd.addHeader("Authorization", "Basic " + authorization);
soapMessage.saveChanges();
return soapMessage;
}
Please help : what I am doing wrong?
In my soapenv:Envelope || xmlns:soapenv is coming twice
It does not appear twice. You're defining 2 prefixes that are bound to the same namespace.
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
Please help : what I am doing wrong?
Nothing. It does not matter if the namespace prefix is soapenv or SOAP-ENV or polar-bear-ninjas. As long as the prefix is bound to a namespace you are fully qualifying that XML element. Both XMLs are valid and it does not matter which prefix is used.

Adding the namespace for SOAP message body

i want to add the name space for all the items in the SOAPbody, the configuration related to the XML manipulation is in below i added the name space for the header but it doesn't come to the SOAP-body
Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
SOAPMessage message = smc.getMessage();
try {
SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope();
System.out.println("Envelop : "+envelope);
envelope.addNamespaceDeclaration("sch", "http://api.jasperwireless.com/ws/schema");
SOAPHeader header = envelope.addHeader();
SOAPElement security =
header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
SOAPElement usernameToken =
security.addChildElement("UsernameToken", "wsse");
usernameToken.addAttribute(new QName("xmlns:wsu"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
SOAPElement username =
usernameToken.addChildElement("Username", "wsse");
username.addTextNode("XXXXXXXXX");
SOAPElement password =
usernameToken.addChildElement("Password", "wsse");
password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
password.addTextNode("XXXXXXXXXXXXXX");
//Print out the outbound SOAP message to System.out
message.writeTo(System.out);
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
}
and below is the XML that is created from the above code
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sch="http://api.jasperwireless.com/ws/schema">
<S:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:Username>XXXXXX</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">XXXXXXX</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</S:Header>
<S:Body>
<GetTerminalsByMsisdnRequest xmlns="http://api.jasperwireless.com/ws/schema">
<messageId>my message</messageId>
<version>1.3</version>
<licenseKey>537bba2a-9406-4703-a900-a8fee7a3f310</licenseKey>
<msisdns>
<msisdn>65144099016324</msisdn>
</msisdns>
</GetTerminalsByMsisdnRequest>
</S:Body>
</S:Envelope>
but i wanted to generate it like the below sample. im completely new to java and SOAP please help me
<S:Body>
<sch:GetTerminalsByMsisdnRequest xmlns="http://api.jasperwireless.com/ws/schema">
<sch:messageId>my message</messageId>
<sch:version>1.3</version>
<sch:licenseKey>537bba2a-9406-4703-a900-a8fee7a3f310</licenseKey>
<sch:msisdns>
<sch:msisdn>65144099016324</msisdn>
</sch:msisdns>
</sch:GetTerminalsByMsisdnRequest>
</S:Body>

Spring Web Service with Header and Body In Envelope

We are creating a webservice that came from a WSDL which the soap messagehas both a header and body in the request and response. How can you set this up to work with a Spring WS? I can not find any examples????
In WSDL
<wsdl11:message name="createCourseSectionRequest">
<wsdl11:part name="Parameters" element="tns:createCourseSectionRequest"/>
<wsdl11:part name="HeaderInfoParameters" element="tns:imsx_syncRequestHeaderInfo"/>
</wsdl11:message>
<wsdl11:message name="createCourseSectionResponse">
<wsdl11:part name="Response" element="tns:createCourseSectionResponse"/>
<wsdl11:part name="HeaderInfoResponse" element="tns:imsx_syncResponseHeaderInfo"/>
</wsdl11:message>
Endpoint
#PayloadRoot(localPart="CreateCourseSectionRequest", namespace="")
#ResponsePayload
public CreateCourseSectionResponse createCourseSection(CreateCourseSectionRequest req) {
//TODO
return null;
}
Example
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ims="http://www.imsglobal.org/services/lis/cmsv1p0/wsdl11/sync/imscms_v1p0">
<soapenv:Header>
<ims:imsx_syncRequestHeaderInfo>
<ims:imsx_version>?</ims:imsx_version>
<ims:imsx_messageIdentifier>?</ims:imsx_messageIdentifier>
<!--Optional:-->
<ims:imsx_sendingAgentIdentifier>?</ims:imsx_sendingAgentIdentifier>
</ims:imsx_syncRequestHeaderInfo>
</soapenv:Header>
<soapenv:Body>
.....
</soapenv:Body>
</soapenv:Envelope>
Here is the solution I came up with. It works, but I wish the header part of the Soap message was strongly typed. .NET takes care of this for you while in Java it looks like you have to do more work to replicate a strongly typed object for the header. At least I can access the request/response header of the envelope with MessageContext.
#PayloadRoot(localPart="readCourseSectionRequest", namespace="http://www.imsglobal.org/services/lis/cmsv1p0/wsdl11/sync/imscms_v1p0")
#ResponsePayload
public ReadCourseSectionResponse readCourseSection(#RequestPayload ReadCourseSectionRequest parameters, MessageContext messageContext) {
//SaajSoapMessage response = (SaajSoapMessage) messageContext.getResponse();
//SoapHeader header = response.getSoapHeader();
//header.addHeaderElement(new QName("http://www.w3.org/2005/08/addressing", "MessageID", parameters.getSourcedId()));
return new ReadCourseSectionResponse();
}

Categories