In my project I have to create some Soap web service clients I'm using apache cxf to create the ports and consume the web services I notice that the port creation I'm duplicating a lot of code so I create an abstract class like this
public abstract class WebServiceConsumerPort<P>{
protected Class<P> port;
private static Logger log = LoggerFactory.getLogger(WebServiceConsumerPort.class);
public void createPort(String url, String timeoutS) {
try {
Long timeout = Long.parseLong(timeoutS);
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(port.getClass());
factory.setAddress(url);
port = (Class<P>) factory.create();
Client client = ClientProxy.getClient(port);
if (client != null) {
log.info("Timeout WEB WERVICES: {}", timeout);
HTTPConduit conduit = (HTTPConduit) client.getConduit();
HTTPClientPolicy policy = new HTTPClientPolicy();
policy.setAllowChunking(false);
policy.setConnectionTimeout(timeout * 1000);
policy.setReceiveTimeout(timeout * 1000);
conduit.setClient(policy);
}
} catch (Exception e) {
log.error("Peoblem creating the port", e);
}
}
}
Then I want to create the specific class to create the port: For example I have the WebService1 with methods method1() and method2() and WebService2 with methods method3() and method4()
My consumer looks like:
public class WebService1Consumer extends WebServiceConsumerPort<WebService1Interface> {
public void consumeMethod1() {
port.method1();
}
public void consumeMethod2() {
port.method2();
}
}
And another class looks like
public class WebService2Consumer extends WebServiceConsumerPort<WebService2Interface> {
public void consumeMethod1() {
port.method3();
}
public void consumeMethod2() {
port.method4();
}
}
But in two classes say that Cannot resolve method in port.
Finally it works, the code looks like:
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class WebServiceConsumerPort<P>{
protected P puerto;
private static Logger log = LoggerFactory.getLogger(WebServiceConsumerPort.class);
public void creaPuerto(String url, String timeoutS, Class<P> tipoClase) {
try {
Long timeout = Long.parseLong(timeoutS);
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(tipoClase);
factory.setAddress(url);
puerto = (P) factory.create();
Client client = ClientProxy.getClient(puerto);
if (client != null) {
HTTPConduit conduit = (HTTPConduit) client.getConduit();
HTTPClientPolicy policy = new HTTPClientPolicy();
policy.setAllowChunking(false);
policy.setConnectionTimeout(timeout * 1000);
policy.setReceiveTimeout(timeout * 1000);
conduit.setClient(policy);
}
nIntento = 0;
} catch (Exception e) {
puerto = null;
nIntento++;
}
}
}
Thanks to @ben-thurley with his answer in post