Sunday, November 27, 2016

A Web Service Client for a soap - service

Currently, I can test my web service with a set of soap requests that I call with Soap-ui.

I have to find a way to automatize the system tests for my service, and to integrate them into the build chain.

My intention is to move the soap requests I have in my soap-UI project into a set of java classes, that I can then integrate into my build process.

I started by trying to use Apache CXF for writing my test classes.

This is how I proceeded:

- I created a new IntelliJ project (Facet : WebService Client : JavaEE, WebServices, JAX-WS)
- Separately, I installed the Apache CXF Distribution under my tools - folder (version 3.1.6)
- I downloaded and saved a local copy of the wsdl of the Lossration Service. I edited the pointers to the *.xsd that are included so that they point to a local copy. I did this because wsdl2java requires access to the *.wsdl and related files, and LossratioService is protected (locally: basic authentication, in the diverses environments : https).
- Generate the client classes with the command-line tool of the CXF distribution:

$C:\ieu\tools\apache-cxf-3.1.6\bin\wsdl2java -client -d generated LossratioService.wsdl

- Copy the classes that have been generated to %PROJECT_ROOT%/src/
- Implement the client. Beware the particular problem of the authentication:

public final class Client {
    private static final String WSDL_URL = 
    "http://localhost:8080/LossratioService_v3_0/LossratioService_v3_0/LossratioService?wsdl";
    private static final QName SERVICE_NAME =
            new QName("http://xml.mobi.ch/service/ch/mobi/contractmanagement/LossratioService/v3_0"
            , "LossratioService");

    private static final String USERNAME = "username";
    private static final char[] PASSWORD = "password".toCharArray();

    private Client() {
    }

    public static void main(String args[]) throws Exception {

        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USERNAME, PASSWORD);
            }
        });

        URL wsdlURL = new URL(WSDL_URL);
        LossratioService ss = new LossratioService(wsdlURL, SERVICE_NAME);
        LossratioPortType port = ss.getLossratioPort();

        CallContext ctx = new CallContext();
            ctx.setCaller("ctx-caller");
            ctx.setUser("ctx-user");
            ctx.setUuid("ctx-uuid");

        ShakedownResult resp = port.shakedownTest(ctx);
        port.ping();
 }
}

I found useful hints about access to a protected wsdl on this blog