JaxWS : Externalize Http Conduit name Attribute - web-services

I have the WSDL file for the SOAP webservice that i need to invoke over http. Using cxf wsdl2java plugin i have created the stub methods.
I have created the webservice client using jaxws. The webservice has basic authentication enabled. I am trying to configure http conduit
my application.properties
--------------------------
webservices.http.auth.username=username
webservices.http.auth.password=password
fold.webservices.http.auth.authtype=Basic
webservices.http.conduit.property.name=https://fixed_deposits-test.co.in/fold-webservices/services.*
fold.updateservice.soap.address=https://fixed_deposits-test.co.in/fold-webservices/services/UpdateService
----------------------------
My Spring Context...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"
xmlns:sec="http://cxf.apache.org/configuration/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd
http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<bean id="properties" class="org.apache.camel.spring.spi.BridgePropertyPlaceholderConfigurer">
<property name="locations">
<util:list>
<value>file:${config.dir}/application.properties</value>
</util:list>
</property>
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
</bean>
<jaxws:client id="updateServiceClient" serviceClass="com.fold.facade.v1.UpdateService" address="${fold.updateservice.soap.address}" >
<jaxws:inInterceptors>
<bean id="loggingInInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor" >
<property name="prettyLogging" value="true" />
</bean>
</jaxws:inInterceptors>
<jaxws:outInterceptors>
<bean id="loggingOutInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" >
<property name="prettyLogging" value="true" />
</bean>
</jaxws:outInterceptors>
</jaxws:client>
<http-conf:conduit name="***?????????***">
<http-conf:authorization>
<sec:UserName>${fold.webservices.http.auth.username}</sec:UserName>
<sec:Password>${fold.webservices.http.auth.password}</sec:Password>
<sec:AuthorizationType>${fold.webservices.http.auth.authtype}</sec:AuthorizationType>
</http-conf:authorization>
</http-conf:conduit>
I have done a lot of searching online so as to what should be the valid value for name attribute..
accouring to CXF documentation it should be...
{WSDL_endpoint_target_namespace}PortName.http-conduit
my WSDL File has..
...
targetNamespace="http://facade.fold.com/" and
...
<wsdl:port binding="tns:UpdateServiceImplServiceSoapBinding"
name="UpdateServiceImplPort">
<soap:address
location="https://fixed_deposits-test.co.in/fold-webservices/services/UpdateService" />
</wsdl:port>
so i tried with these..
<http-conf:conduit name="{http://facade.fold.com/}UpdateServiceImplPort.http_conduit">
or
<http-conf:conduit name="*UpdateServiceImplPort.http_conduit">
or
<http-conf:conduit name="{http://facade.fold.com/}*.http_conduit">
But none of them work as i get 401 unauthorized exception..
org.apache.cxf.transport.http.HTTPException: HTTP response '401: Unauthorized' when communicating with https://fixed_deposits-test.co.in/fold-webservices/services/UpdateService
THERE ARE COUPLE OF WAYS I GOT IT TO WORK
a) <http-conf:conduit name="*.http_conduit">
but i really don't want to do it this way...
b) <http-conf:conduit name="https://fixed_deposits-test.co.in/fold-webservices/services/UpdateService">
this is hardcoding the SOAP service URL... which i don't want as i am looking for externalizing URL as my SOAP URL's are different for different environment..(dev /test /prod etc)
Below is my best shot at externalization, but it failed with 401 Unauthorized Exception...
properties were replaced in all other instances in my spring context, but not for http-conf:conduit name attribute :(
<http-conf:conduit name="${webservices.http.conduit.property.name}">
As a workaround i am currently using the regex approach which works..
<http-conf:conduit name="*.*/fold-webservices/services/UpdateService">
But i really want to figure out if it possible to externalize it and read from properties file. And i want to do it the Spring
configuration way. Please help me !!!

We had the same issue with JBoss Fuse 6.1 (Camel CXF 2.12.0).
You can see what the http-conf:conduit name is set to by enabling DEBUG log level and looking at your log, there should be a log line such as:
DEBUG 10:40:41,437 [Camel (cnpms-as-mnp-ctx) thread #0 - JmsConsumer[cnpms-queue]] org.apache.cxf.transport.http.HTTPConduit.setTlsClientParameters(HTTPConduit.java:901) - Conduit '{http://acme.com/manageporting/v1}ManageportingPortPort.http-conduit' has been (re)configured for plain http.
So in this case you would set the name as:
<http-conf:conduit name="{http://acme.com/manageporting/v1}ManageportingPortPort.http-conduit"
But the Web Service (WS) Interface Class is defined as:
#WebService(targetNamespace = "http://acme.com/manageporting/v1", name = "ManageportingPort")
#SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface ManageportingPort {
Generated from WSDL:
<wsdl:portType name="ManageportingPort">
Note that by following the CXF documentation you would expect the port name component to be "ManageportingPort" NOT "ManageportingPortPort" i.e. with "Port" appended to it.
However looking at how the portQName is resolved in org.apache.cxf.jaxws.support.JaxWsImplementorInfo.getEndpointName(), if the port name is not set in the WS Interface Class, and the name is not null or blank, it sets the port name to portName = name + "Port" otherwise it sets it to portName = implementorClass.getSimpleName() + "Port".

I had the same problem...
In my case the following 2 changes helped:
1) add "Port" postfix to the port name, despite it is not defined in the wsdl this was
e.g wsdl:
<wsdl:port name="XXXSoap">
will be "XXXSoapPort" in the conduit definition
2) remove the "\" at the end of the target namespace name
==> therefore try
<http-conf:conduit name="{http://facade.fold.com}UpdateServiceImplPort.http_conduit">
or
<http-conf:conduit name="{http://facade.fold.com}UpdateServiceImplPortPort.http_conduit">

I came across the same challenge and found no existing solution. Spring doesn't seem to resolve placeholders in bean names (make lots of sense). However, this is a valid case unless cxf allows conduit matching using another attribute.
There are a few ways to solve this problem:
Define conduit beans programmatically (lose the neat of xml declaration)
Find a way to resolve the bean names which contains placeholders
I prefer option 1 and this is the implementation which I'm happy with. Please note that PropertyPlaceholderResolver is our own utility which uses the same defined resolver bean.
public class NameWithPlaceholderBeanFactoryPostProcessor implements BeanFactoryPostProcessor
{
#Override
public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException
{
if (!(beanFactory instanceof DefaultListableBeanFactory))
return;
DefaultListableBeanFactory bf = (DefaultListableBeanFactory) beanFactory;
String[] names = bf.getBeanDefinitionNames();
for (String name : names)
{
if (name.indexOf('$') < 0)
continue;
BeanDefinition bd = bf.getBeanDefinition(name);
bf.removeBeanDefinition(name);
bf.registerBeanDefinition(PropertyPlaceholderResolver.resolvePlaceHolders(name), bd);
}
}
}
The final step is to define this as a spring bean.

Related

How do I set the WS-Addressing MessageId header when using CXF with Apache Camel?

I'm invoking a web service that requires WS-Addressing SOAP headers. I'm using Apache Camel with CXF to invoke the web service. When I configure the CXF endpoint with the web service's WSDL, it's smart enough to automatically add WS-Adressing SOAP headers, but I need to set a custom MessageId.
Here is the message that is currently being sent:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header>
<ws:international xmlns:ws="http://www.w3.org/2005/09/ws-i18n">
<ws:locale xmlns:ws="http://www.w3.org/2005/09/ws-i18n">en_CA</ws:locale>
</ws:international>
<fram:user wsa:IsReferenceParameter="true" xmlns:fram="http://wsbo.webservice.ephs.pdc.ibm.com/Framework/" xmlns:wsa="http://www.w3.org/2005/08/addressing">BESTSystem</fram:user>
<Action soap:mustUnderstand="true" xmlns="http://www.w3.org/2005/08/addressing">http://webservice.ephs.pdc.ibm.com/Client/QueryHumanSubjects</Action>
<MessageID soap:mustUnderstand="true" xmlns="http://www.w3.org/2005/08/addressing">urn:uuid:945cfd10-9fd2-48f9-80b4-ac1b9f3293c6</MessageID>
<To soap:mustUnderstand="true" xmlns="http://www.w3.org/2005/08/addressing">https://panweb5.panorama.gov.bc.ca:8081/ClientWebServicesWeb/ClientProvider</To>
<ReplyTo soap:mustUnderstand="true" xmlns="http://www.w3.org/2005/08/addressing">
<Address>http://www.w3.org/2005/08/addressing/anonymous</Address>
</ReplyTo>
</soap:Header>
<soap:Body>
<ns2:queryHumanSubjectsRequest xmlns:ns2="http://wsbo.webservice.ephs.pdc.ibm.com/Client/" xmlns:ns3="http://wsbo.webservice.ephs.pdc.ibm.com/FamilyHealth/">
<!-- stuff -->
</ns2:queryHumanSubjectsRequest>
</soap:Body>
</soap:Envelope>
As you can see, the MessageId value is "urn:uuid:945cfd10-9fd2-48f9-80b4-ac1b9f3293c6". I need to set a custom value.
I tried adding the MessageId header they way I add the other headers like "international" and "user", but some part of the framework overrides the value.
// Note this doesn't work! Something overrides the value. It works for other headers.
#Override
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
List<SoapHeader> headers = CastUtils.cast((List<?>) in.getHeader(Header.HEADER_LIST));
SOAPFactory sf = SOAPFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
QName MESSAGE_ID_HEADER = new QName("http://www.w3.org/2005/08/addressing", "MessageID", "wsa");
SOAPElement messageId = sf.createElement(MESSAGE_ID_HEADER);
messageId.setTextContent("customValue");
SoapHeader soapHeader = new SoapHeader(MESSAGE_ID_HEADER, messageId);
headers.add(soapHeader);
}
The CXF website has some documentation on how to set WS-Addressing headers, but I don't see how to apply it to Apache Camel. The Apache Camel CXF documentation doesn't specifically mention WS-Addressing either.
The documentation links you posted actually do have the information you need, although it's not immediately obvious how to apply it to Camel.
The CXF documentation says that:
The CXF org.apache.cxf.ws.addressing.impl.AddressingPropertiesImpl object can be used to control many aspects of WS-Addressing including the Reply-To:
AddressingProperties maps = new AddressingPropertiesImpl();
EndpointReferenceType ref = new EndpointReferenceType();
AttributedURIType add = new AttributedURIType();
add.setValue("http://localhost:9090/decoupled_endpoint");
ref.setAddress(add);
maps.setReplyTo(ref);
maps.setFaultTo(ref);
((BindingProvider)port).getRequestContext()
.put("javax.xml.ws.addressing.context", maps);
Note that it sets the addressing properties on the "RequestContext".
The Apache Camel documentation says that:
How to propagate a camel-cxf endpoint’s request and response context
CXF client API provides a way to invoke the operation with request and response context. If you are using a camel-cxf endpoint producer to invoke the outside web service, you can set the request context and get response context with the following code:
CxfExchange exchange = (CxfExchange)template.send(getJaxwsEndpointUri(), new Processor() {
public void process(final Exchange exchange) {
final List<String> params = new ArrayList<String>();
params.add(TEST_MESSAGE);
// Set the request context to the inMessage
Map<String, Object> requestContext = new HashMap<String, Object>();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, JAXWS_SERVER_ADDRESS);
exchange.getIn().setBody(params);
exchange.getIn().setHeader(Client.REQUEST_CONTEXT , requestContext);
exchange.getIn().setHeader(CxfConstants.OPERATION_NAME, GREET_ME_OPERATION);
}
});
The above example has some stuff we don't need, but the important thing is that it shows us how to set the CXF Request Context.
Put them together and you get:
#Override
public void process(Exchange exchange) throws Exception {
AttributedURIType messageIDAttr = new AttributedURIType();
messageIDAttr.setValue("customValue");
AddressingProperties maps = new AddressingProperties();
maps.setMessageID(messageIDAttr);
Map<String, Object> requestContext = new HashMap<>();
requestContext.put(JAXWSAConstants.CLIENT_ADDRESSING_PROPERTIES, maps);
exchange.getIn().setHeader(Client.REQUEST_CONTEXT, requestContext);
}
// org.apache.cxf.ws.addressing.JAXWSAConstants.CLIENT_ADDRESSING_PROPERTIES = "javax.xml.ws.addressing.context"
// org.apache.cxf.endpoint.Client.REQUEST_CONTEXT = "RequestContext"
Warning: In my route, I invoke multiple different web services sequentially. I discovered that after setting the RequestContext as shown above, Camel started using the same RequestContext for all web services, which resulted in an error: "A header representing a Message Addressing Property is not valid and the message cannot be processed". This is because the incorrect "Action" header was used for all web service invocations after the first.
I traced this back to Apache Camel using a "RequestContext" Exchange property, separate from the header we set, which apparently takes priority over the header. If I remove this property prior to calling subsequent web services, CXF automatically fills in the correct Action header.
if your problem not solved, I suggest you to combine your cxf service with custom interceptor. it easy to work with your soap message. like this:
<bean id="TAXWSS4JOutInterceptorBean" name="TAXWSS4JOutInterceptorBean" class="com.javainuse.beans.SetDetailAnswerInterceptor " />
<cxf:cxfEndpoint id="CXFTest" address="/javainuse/learn"
endpointName="a:SOATestEndpoint" serviceName="a:SOATestEndpointService"
serviceClass="com.javainuse.SOATestEndpoint"
xmlns:a ="http://javainuse.com">
<cxf:binding>
<soap:soapBinding mtomEnabled="false" version="1.2" />
</cxf:binding>
<cxf:features>
<wsa:addressing xmlns:wsa="http://cxf.apache.org/ws/addressing"/>
</cxf:features>
<cxf:inInterceptors>
<ref bean="TAXWSS4JInInterceptorBean" />
</cxf:inInterceptors>
<cxf:inFaultInterceptors>
</cxf:inFaultInterceptors>
<cxf:outInterceptors>
<ref bean="TAXWSS4JOutInterceptorBean" />
</cxf:outInterceptors>
<cxf:outFaultInterceptors>
</cxf:outFaultInterceptors>
</cxf:cxfEndpoint>
and in the interceptor you can set soap headers like this:
public class SetDetailAnswerInterceptor extends WSS4JOutInterceptor {
public SetDetailAnswerInterceptor() {
}
#Override
public void handleMessage(SoapMessage mc) {
AttributedURIType value = new AttributedURIType();
value.setValue("test");
((AddressingProperties) mc.get("javax.xml.ws.addressing.context.outbound")).setMessageID(value);
}
}

How to access a huge JSON coming (from a spring RESTful Service) in a spring MVC app using RestTemplate

My Spring RESTful web service is returning a JSON form of-
[{"key1":"value1","key2":"value2","key3":"value3"},{"key4":"value4","key5":"value5","key6":"value6"}]
Now when my spring MVC app, try to access it, to show in a JSP then Exception occurs saying-no suitable HttpMessageConverter found Please help me where I going wrong.Here is my code-
Inside #Controller class of my spring MVC app calling the RESTful service
//**com.songs.controllers.FrontSongController.java**
</*
author Rohit Tiwari
*/>
#RequestMapping(value="/alls",method=RequestMethod.POST)
public String getAllSongs(ModelMap md)
{
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
String url="http://localhost:7001/SongAppWS/songappWS/allsongsWS";
RestTemplate rt=new RestTemplate();
//SongResource.class is for representation on incoming JSON see below for its code
//This is the line no 48 that you will see in below browser logs
ResponseEntity<SongResource> listofallsongs=rt.exchange(url,HttpMethod.GET,entity, SongResource.class);
md.addAttribute("listname", "Songs available in the repository:");
System.out.println("Response Entity object= "+listofallsongs);
System.out.println("Response Entity body= "+listofallsongs.getBody().toString());
return "Sucess";
}
Inside config-servlet.xml of my spring MVC app calling the RESTful service
<context:component-scan base-package="com.songs.controllers" />
<mvc:annotation-driven />
<context:annotation-config/>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
<bean class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
Inside SongResource.java of my spring MVC app, which I am trying to use for converting the coming JSON to my SongResource.class object, that my spring MVC app can use in a jsp
//**com.songs.service.resource.SongResource.java**
public class SongResource
{
private String name;
private String film;
private String singer;
public SongResource(String name,String film,String singer)
{
this.name=name;
this.film=film;
this.singer=singer;
}
//setter & getters of all above
}
On calling the spring REST service from my spring MVC app the browser is saying as below-
Error 500--Internal Server Error
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [com.songs.service.resource.SongResource] and content type [application/json]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java :77)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:619)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:446)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:401)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:377)
at com.songs.controllers.FrontSongController.getAllSongs(FrontSongController.java:48)
//and so on
Try this, hope it will help you
#RequestMapping(value="/alls",method=RequestMethod.POST)
public String getAllSongs(ModelMap md)
{
String url="http://localhost:7001/SongAppWS/songappWS/allsongsWS";
RestTemplate rt=new RestTemplate();
SongResource[] songRs = template.getForObject(url, SongResource[].class);
List<SongResource> songs = Arrays.asList(songRs);
md.addAttribute("listname", "Songs available in the repository:");
md.addAttribute("listValues", songs);
return "Sucess";
}

Camel: route1 started and consuming from: Endpoint[...] but it is not consuming

When I start camel in standalone mode I get a message that my routes are consuming from Endpoints that I have set up:
Route: route1 started and consuming from: Endpoint[http://localhost:9090/hrm/hrm_push?bindingStyle=SimpleConsumer]
Great!
But when I cut & past whats in between [] into my browser I'm getting a 404.
Surely if Camel says it is consuming at that address I should be able to use that address to contact my Rest web service.
Here is my appContext
<bean id="transformer" class="com.xxxx.portlistener.services.Transformer">
</bean>
<cxf:rsServer id="pushServer"
address="http://localhost:9090/hrm/hrm_push?bindingStyle=SimpleConsumer" >
<cxf:serviceBeans>
<ref bean="transformer" />
</cxf:serviceBeans>
</cxf:rsServer>
<cxf:rsServer id="pingServer"
address="http://localhost:9090/hrm/hrm_ping" >
<cxf:serviceBeans>
<ref bean="transformer" />
</cxf:serviceBeans>
</cxf:rsServer>
<!-- Camel Configuration -->
<camel:camelContext id="camel-1" xmlns="http://camel.apache.org/schema/spring">
<package>com.xxxx.portlistener.services</package>
<camel:route id="route1">
<camel:from uri="cxfrs://bean://pushServer"/>
<camel:to uri="log:TEST?showAll=true" />
</camel:route>
<camel:route id="route2">
<camel:from uri="cxfrs://bean://pingServer"/>
<camel:to uri="log:TEST?showAll=true" />
</camel:route>
</camel:camelContext>
My Service Interface:
#Path("/hrm/")
public interface PushService
{
/**
* trasform will change the given Object....
*/
#POST
#Produces("text/plain")
#Path("/hrm_push/")
public Response pusher(Object pushee);
#GET
#Produces("text/plain")
#Path("/hrm_ping/")
public Response ping();
}
The error from the console:
Jan 21, 2014 10:45:50 AM org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor processRequest
WARNING: No root resource matching request path / has been found.
Jan 21, 2014 10:45:51 AM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse
WARNING: WebApplicationException has been caught : no cause is available
Can anyone spot what I'm doing wrong?
Thanks,
Andrew
You have duplicated path settings in the CXF RS bean and in the Java annotations. The two will be combined, therefore the final URL will be something like http://localhost:9090/hrm/hrm_push + "/hrm/" + "/hrm_push/" which is probably not what you wanted.
A recommendation would be to use the CXF RS bean to define the base URL only, then use the Java annotations for everything else.

Calling a web-service dynamically using WSDL

I need to configure the camel route endpoint using WSDL file.
I don't know the service classes and I don't want to put the service class files in my class path. I have only the WSDL file.
How can I solve my task ?
Define the camel cxf endpoint as follows
<cxf:cxfEndpoint id="testServiceEndpoint" address="http://localhost:9000/web-service/TestService" wsdlURL="TestService.wsdl" serviceClass="com.webservice.AllServiceService" endpointName="s:TestServiceHttpSoap11Endpoint" serviceName="s:TestPutService" xmlns:s="http://webservices/testService"/>
Route configuration
<route>
<from uri="cxf:bean:testServiceEndpoint"/>
<to uri="log:output?showAll=true" />
</route>
Note that I have mentioned a serviceClass attribute, but this class can be made generic to handle all webservices by using #WebServiceProvider annotation
#WebServiceProvider
#ServiceMode(Mode.PAYLOAD)
public class AllServiceService implements Provider<StreamSource> {
#Override
public StreamSource invoke(StreamSource request) {
}
}

How can i have two separate web services with identical name space and local name requests be routed to different end points?

I'm attempting to create 2 separate web services, both within one spring deployment, both with the wsdl's being generated from the same xsd schemas, yet have them be routed to two separate end points so i can handle the requests differently in the separate contexts.
Ex:
Webservice 1: subset of access, lower privileges and security constraints
Webservice 2: higher privileges
<sws:dynamic-wsdl id="spml-readonly"
portTypeName="SpmlReadOnlyService"
locationUri="SpmlReadOnly">
<sws:xsd location="/WEB-INF/xsd/spml/pstc_spmlv2_core.xsd"/>
</sws:dynamic-wsdl>
<sws:dynamic-wsdl id="spml-crud"
portTypeName="SpmlCrudService"
locationUri="SpmlCrud">
<sws:xsd location="/WEB-INF/xsd/spml/pstc_spmlv2_core.xsd"/>
<sws:xsd location="/WEB-INF/xsd/spml/pstc_spmlv2_search.xsd"/>
<sws:xsd location="/WEB-INF/xsd/spml/pstc_spmlv2_batch.xsd"/>
</sws:dynamic-wsdl>
Now since both wsdls are based off of the same xsds, the 'namespace' and 'localPart" of the requests come across the wire identical, regardless of which web service i'm hitting (/SpmlReadOnly or /SpmlCrud).
Therefore, that's ruling out the deprecated PayloadRootQNameEndpointMapping since the localPart and namespace are still identical, etc,... and my current config simply routes the requests to the same endpoint method handler, and i have no way of distinguishing which web service was called:
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "lookupRequest")
#ResponsePayload
public Source handleLookupRequest(SoapMessage message) throws Exception {
...
}
Is what I'm able to do even possible? If the xsd's are shared and have identical namespaces at the root of the schema, and the same localPart method requests, will there ever be a way to distinguish between them and map to two different end points? Any information on this would be useful! I'm hoping i don't have to set up two separate .wars and deploy them separately with their own code bases on a server!
Thanks,
Damian
You need something that combines URI and PayloadRoot mapping. Unfortunately Spring-Ws doesn't have something like this. But because it's very extensible it's really easy to achieve this.
TL;DR
See This branch at GitHub for working example
Details
You need to create mapping of combined URI+QName to org.springframework.ws.server.endpoint.MethodEndpoint instances. Also you should minimize the code which would duplicate existing Spring-Ws functions.
So 1) You need to explicitly configure Spring-Ws annotations without using <sws:annotation-driven />:
This is your requirement (with my schemas):
<ws:dynamic-wsdl id="spml-readonly" portTypeName="SpmlReadOnlyService" locationUri="SpmlReadOnly">
<ws:xsd location="classpath:springws/model/schema.xsd" />
</ws:dynamic-wsdl>
<ws:dynamic-wsdl id="spml-crud" portTypeName="SpmlCrudService" locationUri="SpmlCrud">
<ws:xsd location="classpath:springws/model/schema.xsd" />
<ws:xsd location="classpath:springws/model/schema2.xsd" />
</ws:dynamic-wsdl>
This is all you need to do by hand which normally is configured by <sws:annotation-driven /> (one adapter with one JAXB marshaller):
<bean class="org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter">
<property name="methodArgumentResolvers">
<list>
<ref local="marshallingPayloadMethodProcessor"/>
</list>
</property>
<property name="methodReturnValueHandlers">
<list>
<ref local="marshallingPayloadMethodProcessor"/>
</list>
</property>
</bean>
<bean id="marshallingPayloadMethodProcessor" class="org.springframework.ws.server.endpoint.adapter.method.MarshallingPayloadMethodProcessor">
<property name="marshaller" ref="marshaller" />
<property name="unmarshaller" ref="marshaller" />
</bean>
<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="contextPaths">
<list>
<value>springws.model</value>
</list>
</property>
</bean>
This is custom mapping:
<bean class="springws.PathAndPayloadRootAnnotationEndpointMapping" />
And 2) You should create your own mapping
public class PathAndPayloadRootAnnotationEndpointMapping extends PayloadRootAnnotationMethodEndpointMapping
{
#Override
protected QName getLookupKeyForMessage(MessageContext messageContext) throws Exception
{
String urlPart = "";
QName payloadRootPart = super.getLookupKeyForMessage(messageContext);
TransportContext transportContext = TransportContextHolder.getTransportContext();
if (transportContext != null) {
WebServiceConnection connection = transportContext.getConnection();
if (connection != null && connection instanceof HttpServletConnection) {
String requestURI = ((HttpServletConnection)connection).getHttpServletRequest().getRequestURI();
String contextPath = ((HttpServletConnection)connection).getHttpServletRequest().getContextPath();
urlPart = requestURI.substring(contextPath.length());
}
}
return new QName(payloadRootPart.getNamespaceURI(), urlPart + "/" + payloadRootPart.getLocalPart());
}
#Override
protected List<QName> getLookupKeysForMethod(Method method)
{
List<QName> result = new ArrayList<QName>();
RequestMapping rm = AnnotationUtils.findAnnotation(method.getDeclaringClass(), RequestMapping.class);
String urlPart = rm == null || rm.value().length != 1 ? "" : rm.value()[0];
List<QName> methodPart = super.getLookupKeysForMethod(method);
for (QName qName : methodPart) {
result.add(new QName(qName.getNamespaceURI(), urlPart + "/" + qName.getLocalPart()));
}
return result;
}
}
which extends org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping. And all it does is extending the keys (QNames of payload root elements) of messages with the information extracted from the endpoint URI. I've used Spring's #org.springframework.web.bind.annotation.RequestMapping annotation for that, but someone thinking it's a hack may create his/her own annotation.
So for endpoint like this:
#org.springframework.ws.server.endpoint.annotation.Endpoint
#RequestMapping("/ws/SpmlReadOnly")
public class Endpoint1
{
#ResponsePayload
#PayloadRoot(namespace = "urn:test", localPart = "method1Request")
public Response2 method(#RequestPayload Request1 request) throws Exception
{
return new Response2("e1 m1");
}
}
the key is not:
namespace = urn:test
localName = method1Request
but this:
namespace = urn:test
localName = /ws/SpmlReadOnly/method1Request
The protected QName getLookupKeyForMessage(MessageContext messageContext) method ensures that the mapping URI is independent of the WAR context, the application is deployed at.