MULE ESB : Binding multiple Web Services to one Client - service

I have a client which connects to a Web service to get some information. I have a requirement where I have to send the same information to multiple services using different ports. To solve this without modifying the client code I found MULE ESB, which is supposed to do exactly what I need.
I've found a guide where I could connect one client to one service using MULE ESB and one port, but I cant find a way to chain the services so they all listen to one port but have different themselves.
This is how it's supposed to look like:
UPDATE :
here is my current Mule Applications config :
<mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="CE-3.2.1" xsi:schemaLocation="
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd ">
<flow name="flows1Flow1" doc:name="flows1Flow1">
<http:inbound-endpoint exchange-pattern="request-response" address="http://localhost:4433/miniwebservice" mimeType="text/xml" doc:name="HTTP"/>
<http:outbound-endpoint exchange-pattern="request-response" address="http://localhost:4434/miniwebservice?wsdl" mimeType="text/xml" doc:name="HTTP"/>
</flow>
</mule>
Here is the WebService :
Client :
package miniwebservice;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class TestWsClient
{
public static void main( final String[] args ) throws Throwable
{
String url = ( args.length > 0 ) ? args[0] : "http://localhost:4434/miniwebservice";
Service service = Service.create(
new URL( url + "?wsdl" ),
new QName( "http://miniwebservice/", "HalloWeltImplService" ) );
HalloWelt halloWelt = service.getPort( HalloWelt.class );
System.out.println( "\n" + halloWelt.hallo( args.length > 1 ? args[1] : "" ) );
}
}
Server :
package miniwebservice;
import javax.xml.ws.Endpoint;
public class TestWsServer
{
public static void main( final String[] args )
{
String url = ( args.length > 0 ) ? args[0] : "http://localhost:4434/miniwebservice";
Endpoint.publish( url, new HalloWeltImpl() );
}
}
InterfaceImpl :
package miniwebservice;
import javax.jws.WebService;
#WebService( endpointInterface="miniwebservice.HalloWelt" )
public class HalloWeltImpl implements HalloWelt
{
public String hallo( String wer )
{
return "Hallo " + wer;
}
}
interface :
package miniwebservice;
import javax.jws.*;
#WebService
public interface HalloWelt
{
public String hallo( #WebParam( name = "wer" ) String wer );
}
If I start the Server and the Mule aplication and try to reach http://localhost:4434/miniwebservice?wsdl ower http://localhost:4433/miniwebservice I get the folowing Exception in my Browser (FireFox 8.0) :
Couldn't create SOAP message due to exception: XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
Message: Content is not allowed in prolog.
I just started to work with Mule so I thouth that this would be enouth to get redirect mule to the Service to get the wsdl but its seems like its a bit complicatet.

Disclaimers:
This is not the final solution to the whole problem, which includes dispatching to several services and aggregating results, but a step in the right direction.
This is not representative of how web service proxying is done in Mule (which is way simpler) but a barebone approach to HTTP request routing so aggregation can be added.
Since you want to forward HTTP GET requests to the ?wsdl processor and HTTP POST SOAP request to the web service, you need to handle the target HTTP method and request URI propagation yourself:
<flow name="flows1Flow1">
<http:inbound-endpoint exchange-pattern="request-response"
address="http://localhost:4433/miniwebservice" />
<message-properties-transformer scope="outbound">
<add-message-property key="http.method" value="#[header:INBOUND:http.method]" />
</message-properties-transformer>
<logger level="INFO" category="ddo" />
<http:outbound-endpoint exchange-pattern="request-response"
address="http://localhost:4434#[header:INBOUND:http.request]" />
</flow>
(tested and validated with TestWsClient and TestWsServer)

Related

Customizing Spring Integration Web Service SOAP Envelope/Header

I am trying to send a SOAP request using Spring Integration like
<int:chain input-channel="wsOutChannel" output-channel="stdoutChannel">
<int-ws:header-enricher>
<int-ws:soap-action value="..."/>
</int-ws:header-enricher>
<int-ws:outbound-gateway
uri="..."/>
</int:chain>
but you can only add the SOAP body, and Spring Integration adds the envelope, header, and body tags like
<SOAP-ENV:Envelope>
<SOAP-ENV:Header>
<SOAP-ENV:Body>
...
</SOAP-ENV:Body>
<SOAP-ENV:Header>
</SOAP-ENV:Envelope>
I need to customize the envelope and header tags with specific attributes, for example:
<soapenv:Envelope attribute1="value1" attribute2="value2">
and child elements, for example:
<soapenv:Header>
<child>...<child>
<soapenv:Header>
Is this possible with Spring Integration Web Services, or should I not use int-ws:outbound-gateway and take a different approach?
You can add a ClientInterceptor (via the interceptor attribute) which allows you to modify the request before it's sent out.
EDIT
#Artem's suggestion is simpler but the interceptor gives you access to the response too; but either way, the code is similar.
For the interceptor:
public class MyInterceptor extends ClientInterceptorAdapter {
#Override
public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
SoapMessage request = (SoapMessage) messageContext.getRequest();
SoapEnvelope envelope = request.getEnvelope();
envelope.addAttribute(new QName("foo"), "bar");
SoapHeader header = envelope.getHeader();
header.addHeaderElement(new QName("http://fiz/buz", "baz"));
return super.handleRequest(messageContext);
}
}
For the callback version:
#Override
public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
SoapEnvelope envelope = ((SoapMessage) message).getEnvelope();
envelope.addAttribute(new QName("foo"), "bar");
SoapHeader header = envelope.getHeader();
header.addHeaderElement(new QName("http://fiz/buz", "baz"));
}
I thing you can inject WebServiceMessageCallback:
<xsd:attribute name="request-callback" type="xsd:string">
<xsd:annotation>
<xsd:documentation>
Reference to a Spring Web Services WebServiceMessageCallback. This enables changing
the Web Service request message after the payload has been written to it but prior
to invocation of the actual Web Service.
</xsd:documentation>
<xsd:appinfo>
<tool:annotation kind="ref">
<tool:expected-type type="org.springframework.ws.client.core.WebServiceMessageCallback"/>
</tool:annotation>
</xsd:appinfo>
</xsd:annotation>
</xsd:attribute>
and cast the message to the SoapMessage and use its getEnvelope() to customize a desired way.

CXF log SOAP output

I am having trouble logging an outgoing SOAP message from the server. The handleMessage method does not overwrite the message content as expected. How would I store the outgoing SOAP to the message?
public class OutgoingSoapInterceptor extends AbstractPhaseInterceptor<Message> {
private static final Logger logger = LoggerFactory.getLogger(OutgoingSoapInterceptor.class.getName());
public OutgoingSoapInterceptor ()
{
super(Phase.PRE_STREAM);
}
#Override
public void handleMessage(Message message) throws Fault {
logger.debug("outbound soap handleMessage");
OutputStream os = message.getContent ( OutputStream.class );
CacheAndWriteOutputStream cwos = new CacheAndWriteOutputStream ( os);
message.setContent ( OutputStream.class, cwos );
cwos.registerCallback ( new LoggingOutCallBack ( ) );
}
}
There is a simpler way to log the SOAP messages using CXF LoggingInInterceptor and LoggingOutInterceptor
LogUtils.setLoggerClass(org.apache.cxf.common.logging.Log4jLogger.class);
yourService = new YourService(wsdlURL, SERVICE_NAME);
port = yourService.getServicePort();
Client client = ClientProxy.getClient(port);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
Or configuring interceptors in <cxf:bus> with spring
<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:cxf="http://cxf.apache.org/core"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/core
http://cxf.apache.org/schemas/core.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<cxf:bus>
<cxf:features>
<cxf:logging />
</cxf:features>
</cxf:bus>
<jaxws:endpoint ... />
</beans>
See more examples in How to log Apache CXF Soap Request and Soap Response using Log4j

Apache camel cxfrs—Can't find the request for <URL> Observer

I tried to develop a rest service and expose the same via Apache Camel's CXFRS. I followed all the steps given in http://camel.apache.org/cxfrs.html and also referred to many samples given. I already referred to the question Can't find the the request for url Observer, but in my case it is a simple rest request. Below are the Service class, Route class, and cxf context used:
<?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:camel="http://camel.apache.org/schema/spring"
xmlns:cxf="http://camel.apache.org/schema/cxf" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring
http://camel.apache.org/schema/spring/camel-spring.xsd
http://camel.apache.org/schema/cxf
http://camel.apache.org/schema/cxf/camel-cxf.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<context:annotation-config />
<!-- enable Spring #Component scan -->
<context:component-scan base-package="org.camelsample.rest" />
<cxf:rsServer id="rsServer" address="/rest"
serviceClass="org.camelsample.rest.service.SampleRestService"
loggingFeatureEnabled="true" loggingSizeLimit="20">
<cxf:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</cxf:providers>
</cxf:rsServer>
<camel:camelContext id="samplerestservice"
xmlns="http://camel.apache.org/schema/spring">
<contextScan />
<jmxAgent id="agent" createConnector="true" />
</camel:camelContext>
</beans>
The Service Class:
package org.camelsample.rest.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
public class SampleRestService {
#GET
#Path("/")
public String sampleService() {
return null;
}
}
The Route Class:
package org.camelsample.rest.route;
import org.apache.camel.spring.SpringRouteBuilder;
public class SampleRestRoute extends SpringRouteBuilder {
#Override
public void configure() throws Exception {
// TODO Auto-generated method stub
from("cxfrs:bean:rsServer").log("Into Sample Route").setBody(constant("Success"));
}
}
But when I try to hit and test using http://localhost:8080/rest, I always get the following error message:
2015-05-29 13:38:37.920 WARN 6744 --- [nio-8080-exec-2] o.a.c.t.servlet.ServletController : Can't find the the request for http://localhost:8080/favicon.ico's Observer
2015-05-29 13:38:40.295 WARN 6744 --- [nio-8080-exec-3] o.a.c.t.servlet.ServletController : Can't find the the request for http://localhost:8080/rest's Observer
Am using Spring boot to test the rest sample.
Does it work with this URL instead ?
http://localhost:8181/cxf/rest
If you just use address="/rest" as your address then you will probably get the default Jetty port 8181 and default CXF servlet path /cxf as the base URL.
If you specifically want to use the URL you have given then try this instead:
address="http://0.0.0.0:8080/rest"

How to remove Mule Headers from SOAP response

I have a requirement where I need to expose a SOAP webservice .. So I have the following Mule flow :-
<jms:activemq-connector name="Active_MQ" brokerURL="tcp://localhost:61616" validateConnections="true" doc:name="Active MQ"/>
<flow name="Flow1" doc:name="Flow1" >
<http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8082" path="mainData" doc:name="HTTP"/>
<cxf:jaxws-service serviceClass="com.test.services.schema.maindata.v1.MainData" doc:name="SOAP"/>
<mulexml:object-to-xml-transformer doc:name="Object to XML"/>
<jms:outbound-endpoint queue="NewQueue" connector-ref="Active_MQ" doc:name="JMS" exchange-pattern="request-response"/>
<logger message="Response2 :- #[message.payload]" level="INFO" doc:name="Logger"/>
<mulexml:xml-to-object-transformer doc:name="XML to Object"/>
</flow>
<flow name="flow2" doc:name="flow2" >
<jms:inbound-endpoint connector-ref="Active_MQ" address="jms://tcp:NewQueue" doc:name="JMS" exchange-pattern="request-response" disableTemporaryReplyToDestinations="true" responseTimeout="90000"/>
<set-variable variableName="SOAPRequest" value="#[message.payload]" doc:name="Variable"/>
<mulexml:xml-to-object-transformer doc:name="XML to Object"/>
<component class="com.test.services.schema.maindata.v1.Impl.MainDataImpl" doc:name="JavaMain_ServiceImpl">
<method-entry-point-resolver>
<include-entry-point method="retrieveDataOperation"/>
<include-entry-point method="insertDataOperation"/>
<include-entry-point method="updateDataOperation"/>
<include-entry-point method="deleteDataOperation"/>
</method-entry-point-resolver>
</component>
<mulexml:object-to-xml-transformer doc:name="Object to XML"/>
</flow>
Here you can see the request is getting into JMS queue from the first flow and the second flow use JMS inbound takes it from the JMS queue and the webservice implemented class proccess it .. Now the service works fine without any issue .. the only issue is it get Mule Header in the SOAP in the response like the following :-
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<mule:header xmlns:mule="http://www.muleumo.org/providers/soap/1.0">
<mule:MULE_CORRELATION_ID>ID:ANIRBAN-PC-49483-1408719168461-1:1:10:1:1</mule:MULE_CORRELATION_ID>
<mule:MULE_CORRELATION_GROUP_SIZE>-1</mule:MULE_CORRELATION_GROUP_SIZE>
<mule:MULE_CORRELATION_SEQUENCE>-1</mule:MULE_CORRELATION_SEQUENCE>
</mule:header>
</soap:Header>
<soap:Body>
<deleteDataResponse xmlns="http://services.test.com/schema/MainData/V1">
<Response>Data not exists !!! Please provide correct ID</Response>
<Id>0</Id>
<Age>0</Age>
</deleteDataResponse>
</soap:Body>
</soap:Envelope>
Now please help me to remove the Mule headers from the SOAP response .. I tried with the following :- <cxf:jaxws-service serviceClass="com.test.services.schema.maindata.v1.MainData" enableMuleSoapHeaders="false" doc:name="SOAP"/> but no use .. it's still showing the Mule headers .. Please help ..
You can potentially get away with a temporary workaround until the enableMuleSoapHeaders="false" issue gets solved, by either:
Adding a between the HTTP inbound endpoint and the CXF service ; in order to remove the undue SOAP headers but XSL-Transformation
Using delete-message-property to remove the MULE_* props at the end of Flow1, right after the mulexml:xml-to-object-transformer
I also found an alternate solution off adding it to cxf:outInterceptors
<cxf:jaxws-service serviceClass="com.test.services.schema.maindata.v1.MainData" doc:name="SOAP">
<cxf:outInterceptors >
<spring:bean id="outfault" class="com.test.services.schema.SOAPOptionalData.SOAPInterceptorOutboundHeaderRemover"/>
</cxf:outInterceptors>
</cxf:jaxws-service>
And in the Java class :-
public class SOAPInterceptorOutboundHeaderRemover extends AbstractSoapInterceptor {
public SOAPInterceptorOutboundHeaderRemover() {
super(Phase.PRE_PROTOCOL);
}
#Override
public void handleMessage(SoapMessage arg0) throws Fault {
List<Header> headerList = arg0.getHeaders();
Header muleHeader = null;
boolean isMuleHeader = false;
for (Header header : headerList) {
ElementNSImpl element = (ElementNSImpl) header.getObject();
if ("mule:header".equals(element.getNodeName())) {
isMuleHeader = true;
muleHeader = header;
}
}
if (isMuleHeader) {
arg0.getHeaders().remove(muleHeader);
}
}
}
And this is also working fine

Mule SOAP client wrapper as parameter instead of object array

I created a sample Mule flow by first generating client classes with CXF per http://www.mulesoft.org/documentation/display/current/Consuming+Web+Services+with+CXF guide.
The flow is started by going to localhost:8081/test. The parametersObjectArray will transform any message into a hardcoded object array required for the web service method call, like this:
package com.test.example.transformers;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractTransformer;
public class GetCustomersArrayTransformer extends AbstractTransformer {
#Override
protected Object doTransform(Object src, String enc)
throws TransformerException {
Object[] msg = new Object[3];
msg[0] = 10;
msg[1] = 0;
msg[2] = null;
return msg;
}
}
When this transformer is used in a flow to pass a message to a jaxws-client node, everything works as expected:
<custom-transformer name="parametersObjectArray" class="com.test.example.transformers.GetCustomersArrayTransformer" doc:name="Java"/>
<flow name="mulecartFlow" doc:name="mulecartFlow">
<http:inbound-endpoint exchange-pattern="one-way" host="localhost" port="8081" doc:name="HTTP" path="test"/>
<transformer ref="parametersObjectArray" doc:name="Java"></transformer>
<https:outbound-endpoint exchange-pattern="request-response" host="12.34.56.78" port="1234" path="services/SOAP/TestEndpoint" doc:name="HTTP" connector-ref="httpsConnector" method="POST">
<cxf:jaxws-client clientClass="com.test.TestEndpointService" enableMuleSoapHeaders="true" doc:name="SOAP" operation="getCustomers" port="TestEndpoint" />
</https:outbound-endpoint>
<transformer ref="customerInfoTypesToString" doc:name="Transformer Reference"/>
<logger level="INFO" doc:name="Logger" message="#[message:payload]"/>
</flow>
I would like to use a wrapper object, so that parameters are legible and type-safe:
package com.test.example.transformers;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractTransformer;
import com.test.GetCustomers;
public class GetCustomersObjectTransformer extends AbstractTransformer {
#Override
protected Object doTransform(Object src, String enc)
throws TransformerException {
GetCustomers soapRequest = new GetCustomers();
soapRequest.setStartIndex(0);
soapRequest.setMaxBatchSize(1);
return soapRequest;
}
}
However, that does not seem to work. I noticed that the manual page states:
Note: the CXF transport doesn't support wrapper-style web service
method calls. You may need to create a binding file or change the WSDL
directly
What does that mean? How can I send a wrapper object that wraps all method parameters to the web service method?
Add:
<jaxws:bindings xmlns:jaxws="http://java.sun.com/xml/ns/jaxws">
<jaxws:enableWrapperStyle>false</jaxws:enableWrapperStyle>
</jaxws:bindings>
inside wsdl:portType and CXF will generate the wrapper objects you're after.
Also, note that creating a Java transformer to set the payload is overkill: use set-payload with a simple MEL expression and you'll be good.