Przykład: implementacja klienta za pomocą JAX-WS Proxy

Kod w języku Java:

package sample;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.WSPasswordCallback;
import org.apache.ws.security.handler.WSHandlerConstants;


public class TestServiceWsClient {

private static final TestServiceWsClient instance = new TestServiceWsClient();

private TestServiceWsClient() {}

private TestService wsClient;

/**
* Gets an instance of service proxy. In multi-threaded environments a synchronization should be used.
*/
public TestService getWsClient() {
if (wsClient == null) {
URL wsdlURL = new URL("http://localhost:8080/palio/webservices/sample/TestService?wsdl");
QName SERVICE_NAME = new QName("http://jpalio.com", "TestService");
Service service = Service.create(wsdlURL, SERVICE_NAME);
wsClient = service.getPort(TestService.class);

// Below code is required if a service is secured by login/password (WS-Security)
org.apache.cxf.endpoint.Client client = org.apache.cxf.frontend.ClientProxy.getClient(wsClient);
org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint();

Map<String,Object> outProps = new HashMap<String,Object>();
outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
// Specify our username
outProps.put(WSHandlerConstants.USER, "ws");
// Password type: plain text
outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
// Callback used to retrieve password for given user.
outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];
// set the password for our message.
pc.setPassword("ws");
}
});

WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);
cxfEndpoint.getOutInterceptors().add(wssOut);
}
return wsClient
}

public static TestServiceWsClient getInstance() {
return instance
}
}

 

Przykład użycia:

TestServiceWsClient.getInstance().getWsClient().getText("Hello world!")