Skip to content

Integration Example: Java

Global Services Integration

Ensure you have an account setup. You will need the Username, Password and WSDL location.

Please note: Wherever <LatestWSDLVersion> is shown in Example Code below, please replace this with GlobalServices21a.wsdl.

If you are unsure of any of the details you can contact the helpdesk for more information.

Importing the WSDL (Maven)

There are many different ways of importing a WSDL into your program. Use whichever method you are most familiar with.

This sample code uses JAXWS to import and generate the webservice objects with Maven. An example POM is provided below.

<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/pom/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
         xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
    <modelversion>4.0.0</modelversion>
    <groupid>com.gb</groupid>
    <artifactid>idm-globalservices-intergration-example</artifactid>
    <name>idm-globalservices-intergration-example</name>
    <description>example of an address lookup.</description>
 
    <packaging>jar</packaging>
    <version>1.0</version>
 
    <build>
        <resources>
            <resource>
                <filtering>false</filtering>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <filtering>false</filtering>
                <directory>src/main/java</directory>
                <includes>
                    <include>**</include>
                </includes>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <inherited>true</inherited>
                <groupid>org.apache.maven.plugins</groupid>
                <artifactid>maven-compiler-plugin</artifactid>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <optimize>true</optimize>
                    <debug>true</debug>
                </configuration>
            </plugin>
            <plugin>
                <groupid>org.apache.maven.plugins</groupid>
                <artifactid>maven-surefire-plugin</artifactid>
                <version>2.8</version>
            </plugin>
 
            <plugin>
                <groupid>org.codehaus.mojo</groupid>
                <artifactid>jaxws-maven-plugin</artifactid>
                <version>1.10</version>
                <executions>
 
                    <execution>
                        <id>import idm globalservices ws</id>
                        <goals>
                            <goal>wsimport</goal>
                        </goals>
                        <configuration>
                            <packagename>com.gb.idm.ws.globalservices.schema</packagename>
                            <wsdlfiles>
                                <wsdlfile><latestwsdlversion></wsdlfile>
                            </wsdlfiles>
 
                            <extension>true</extension>
                            <stalefile>${project.build.directory}/jaxws/stale/wsdl.globalserviceswsdl.done</stalefile>
                            <bindingfiles>
                                <bindingfile>jaxb-bindings.xml</bindingfile>
                            </bindingfiles>
                        </configuration>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupid>com.sun.xml.ws</groupid>
                        <artifactid>jaxws-tools</artifactid>
                        <version>2.1.3</version>
                    </dependency>
                </dependencies>
            </plugin>
 
            <plugin>
                <groupid>org.apache.maven.plugins</groupid>
                <artifactid>maven-jar-plugin</artifactid>
                <configuration>
                    <archive>
                        <manifest>
                            <mainclass>com.gb.globalservicelookup</mainclass>
                        </manifest>
                        <manifestentries>
                            <mode>development</mode>
                            <url>${pom.url}</url>
                        </manifestentries>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
 
    <repositories>
        <repository>
            <id>apache nexus</id>
            <url>https://repository.apache.org/content/repositories/snapshots/</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
 
</project>

The <LatestWSDLVersion> file is downloaded and saved into "Project_Root/wsdl/<LatestWSDLVersion>". Upon build JAXWS will generate all the web service objects and place them into "globalservices-alu-integration-example\target\jaxws\wsimport\java".

The IDE may automatically exclude the target directory from the project. Go into the module settings and add the "target\jaxws\wsimport\java" as a source.

Creating the Service

In this example a service layer is created to handle the calls to the web service. First an interface is created.

This helps separate the code out so the implementation can be changed without much consequence.

package main.services;
import com.gb.idm.ws.globalservices.schema.executecaptureresponse;
public interface globalservicesws {
    /**
     * executes an address lookup (will also authenticate if required)
     *
     * @param postcode postcode to lookup
     * @return executecaptureresponse with a list of addresses found.
     */
    public executecaptureresponse lookuppostcode(string postcode);
}
protected static final string endpoint = "";
protected static final string username = "";
protected static final string password = "";
protected static final string profile_guid = "";
private authenticationdetails user = new authenticationdetails();

These are hard coded values which is not best practice. Consider moving the authentication details to an external location (database, properties file etc...).
In the example code attached, an external class Settings reads the values from an xml file.

The following method is the implementation of the lookupPostcode(); method shown in the Interface class above:

@override
public executecaptureresponse lookuppostcode(string postcode) {
     system.out.println("authenticating as: " + this.settings.getidmusername());

      // setup the objects to use on the capture request.
     executecapturerequest request = new executecapturerequest();
     profilerequestcapture profilerequestcapture = new profilerequestcapture();
     profilerequestcapturedata profilerequestcapturedata = new profilerequestcapturedata();

      // idm options
     profilerequestcapture.setconfigurationid(1);
     profilerequestcapture.setcustomerreference("samplecode");            profilerequestcapture.setprofileguid(globalserviceswsimpl.matchcode_names_profile_guid);

     // add the objects to form a complete request.
     request.setprofilerequest(profilerequestcapture);
     profilerequestcapture.setrequestdata(profilerequestcapturedata);

     idmdatasearchaddress idmdatasearchaddress = new idmdatasearchaddress();
     idmdatasearchaddress.setpostcode(postcode);

     profilerequestcapturedata.setaddress(idmdatasearchaddress);
     profilerequestcapturedata.setoptions(this.getidmaddressoptions());
     executecaptureresponse response = this.executecapture(request);

     return response;
}

The getSecurityMethod below will attempt an authentication before adding the required username and authenticationToken to the SecurityHeader:

 

private securityheader getsecurityheader() {
    // create a new securityheader
    securityheader securityheader = new securityheader();
 
    // authenticate user if needed.
    this.authenticateuser();
 
    // add the required authentication details to the header.
    securityheader.setauthenticationtoken(this.user.getauthenticationtoken());
    securityheader.setusername(this.user.getusername());
 
    return securityheader;
}

The authenticateUser method will check to see if the user has a valid authenticationToken before validating, if the user has a valid authenticationToken the method will not authenticate against the web service:

public void authenticateuser() {
    system.out.println("checking session...");
 
    // checks to see if the user has a valid authenticationtoken
    if (!user.isvalid()) {
        system.out.println("no valid session - authenticating...");
 
        // create a new authenticateuserrequest
        authenticateuserrequest request = new authenticateuserrequest();
 
        request.setusername(this.settings.getidmusername());
        request.setpassword(this.settings.getidmpassword());
 
        authenticateuserresponse response = null;
 
        try {
            response = this.getwebservice().authenticateuser(request);
        } catch (businessexception exception) {
            system.out.println("business exception.");
            // catch a specific exception and display message
            if (exception.getfaultinfo().getdetail().geterrorcode().equals("be010009")) {
                system.out.println("invalid credentials");
            } else {
                system.out.println("business exception errorcode: " + exception.getfaultinfo().getdetail().geterrorcode());
            }
 
        } catch (serviceexception e) {
            system.out.println("service exception.");
            throw new noauthenticateexception();
        } catch (exception e) {
            system.out.println("exception.");
            throw new noauthenticateexception();
        }
 
        if (response == null) {
            throw new noauthenticateexception();
        }
 
        // create a new authenticationdetails and add the response.
        this.user = new authenticationdetails(response);
 
        if (response != null && response.getauthenticationtime() != null) {
            system.out.println("authentication successful at: " + response.getauthenticationtime().toxmlformat());
        }
    } else {
        system.out.println("session valid reusing authentication token.");
    }
}

Getting the Web Service

The requests are being sent with the this.getWebservice method. This method returns the webservice with the specified endpoint. See the below method:

private idmglobalservices getwebservice() {
 
    idmglobalservices service = null;
 
    try {
        // create a new web service with the endpoint we have supplied.
        final idmglobalservicesservice ws = new idmglobalservicesservice(
                new url(this.settings.getendpointurl()),
                new qname("http://gbworld.gb.co.uk/idm-globalservices/messages/21a/", "idm-globalservicesservice"));
 
        service = ws.getidmglobalservicessoap11();
    } catch (exception e) {
        e.printstacktrace();
    }
 
    return service;
}

Managing Authentication Details and Session Tokens

The AuthenticationDetails class contains the username, authenticationToken, authenticationTime and some logic to refresh authenticationDetails and check the validity of the authenticationToken:

package com.gb.util;
 
import com.gb.idm.ws.globalservices.schema.authenticateuserresponse;
import java.util.date;
 
public class authenticationdetails {
 
    private string username;
 
    private string authenticationtoken;
 
    private date authenticationtime;
 
    private date sessionexpirytime;
 
    public authenticationdetails() {}
 
    public authenticationdetails(authenticateuserresponse response) {
        this.username = response.getfullusername();
        this.authenticationtoken = response.getauthenticationtoken();
        this.authenticationtime = response.getauthenticationtime().togregoriancalendar().gettime();
        this.sessionexpirytime= response.getsessionexpirytime().togregoriancalendar().gettime();
    }
 
    public string getusername() {
        return username;
    }
 
    public string getauthenticationtoken() {
        return authenticationtoken;
    }
 
    public date getauthenticationtime() {
        return authenticationtime;
    }
 
    public date getsessionexpirytime() {
        return sessionexpirytime;
    }
 
    public boolean isvalid() {
        boolean valid = true;
 
        if (this.sessionexpirytime == null || new date().after(this.sessionexpirytime)) {
            valid = false;
        }
 
        return valid;
    }
 
    public void refreshauthenticationtoken(string authenticationtoken, date expiry) {
        this.authenticationtoken = authenticationtoken;
        this.sessionexpirytime = expiry;
    }
}

Telephone Integration

The following code will expand on the examples to demonstrate an integration into the Global Telephone validation service.

Sample Code

The telephone lookup method:

private static void dotelephonelookup() throws exception {
    string mobile = "";
    string landline = "";
 
    system.out.println("enter mobile: ");
    // readline pauses the application an waits for user input.
    mobile = globalservicelookup.reader.readline();
 
 
    system.out.println("enter landline: ");
    // readline pauses the application an waits for user input.
    landline = globalservicelookup.reader.readline();
 
    executecaptureresponse response = globalservicelookup.globalservices.lookuptelephone( mobile, landline);
 
    for (profileresponsedetails profileresponse : response.getprofileresponse().getprofileresponsedetails()) {
        system.out.format("%20s", profileresponse.getcomponentaction());
        system.out.format("%20s", profileresponse.getcomponentstatus() + "\n");
 
        // check for address results.
        if (profileresponse.getcaptureresponse() != null && profileresponse.getcaptureresponse().getresponse() != null) {
            for (captureresponsedata data : profileresponse.getcaptureresponse().getresponse()) {
                for (idmdataaddress address : data.getaddress()) {
                    system.out.format("%20s", globalservicelookup.line_indent + "- " + address.getformattedaddress() + "\n");
                }
            }
        }
 
        // check for telephone results
        if (profileresponse.getvalidateresponse() != null && profileresponse.getvalidateresponse().getresponse() != null) {
            for (validateresponsedata responsedata : profileresponse.getvalidateresponse().getresponse()) {
                // show number
                system.out.format("%20s", globalservicelookup.line_indent + "- " + responsedata.getinput() + "\n");
 
                // show key value pairs
                for (idmdataitem item : responsedata.getvalidationcodes().getitem()) {
                    system.out.format("%20s",
                            globalservicelookup.line_indent +
                                    "\t" +
                                    "- " +
                                    item.getkey() +
                                    " = " +
                                    item.getvalue() +
                                    "\n");
                }
            }
        }
    }
}

This method will call the lookupTelephone method and handle the response to display. The data is output to the console separated by tabs using the GlobalServiceLookup.LINE_INDENT string. 

The following is the lookupTelephone() method. It is very similar to the C# sample code.

@override
public executecaptureresponse lookuptelephone(final string mobile, final string landline) {
    // setup the objects to use on the alu.
    executecapturerequest request = new executecapturerequest();
    profilerequestcapture profilerequestcapture = new profilerequestcapture();
    profilerequestcapturedata profilerequestcapturedata = new profilerequestcapturedata();
    list<idmdatacapturetelephone> telephones = new arraylist<idmdatacapturetelephone>();
    idmdatasearchaddress address = new idmdatasearchaddress();
 
    // idm options
    profilerequestcapture.setconfigurationid(1);
    profilerequestcapture.setcustomerreference("samplecode");
    profilerequestcapture.setprofileguid(globalserviceswsimpl.global_telephone_profile_guid);
 
    // add mobile if provided
    if (!strings.isnullorempty(mobile)) {
        idmdatacapturetelephone phone = new idmdatacapturetelephone();
        phone.setnumber(mobile);
        phone.settype(enumtelephone.mobile);
        telephones.add(phone);
    }
 
    // add landline if provided
    if (!strings.isnullorempty(landline)) {
        idmdatacapturetelephone phone = new idmdatacapturetelephone();
        phone.setnumber(landline);
        phone.settype(enumtelephone.landline);
        telephones.add(phone);
    }
 
    // add the objects to form a complete request.
    request.setprofilerequest(profilerequestcapture);
    profilerequestcapture.setrequestdata(profilerequestcapturedata);
    profilerequestcapturedata.setaddress(address);
    profilerequestcapturedata.setoptions(this.getidmaddressoptions());
    profilerequestcapturedata.gettelephone().addall(telephones);
 
    // call execute capture.
    return this.executecapture(request);
}

The options for the phone lookup have been put into another method getIdmAddresssOptions().

private idmrequestoptions getidmaddressoptions() {
    idmrequestoptions options = new idmrequestoptions();
 
    options.setaddresssearchlevel(enumaddresslevel.premise);
    options.setcasing(enumcasing.mixed);
    options.setmaxreturn(10);
    options.setoffset(0);
    options.setcountrycodeformat(enumcountrycodeformat.iso_3);
    options.setaddressenvelopeformat("a3tcp");
 
    return options;
}

It will call the executeCapture() method which can be re-used to do an extended address lookup.

private executecaptureresponse executecapture(executecapturerequest request) {
    // gets the security header will do an authentication if there is not a valid authentication token.
    request.setsecurityheader(this.getsecurityheader());
 
    executecaptureresponse response = null;
 
    try {
        // try calling the webservice
        response = this.getwebservice().executecapture(request);
 
        this.user.refreshauthenticationtoken(
                response.getsecurityheader().getauthenticationtoken(),
                response.getsecurityheader().getsessionexpirytime().togregoriancalendar().gettime());
    } catch (businessexception exception) {
        // catch a specific exception and display message
        if (exception.getfaultinfo().getdetail().geterrorcode().equals("be010009")) {
            system.out.println("invalid credentials");
        } else {
            system.out.println("business exception errorcode: " + exception.getfaultinfo().getdetail().geterrorcode());
        }
    } catch (serviceexception exception) {
        // service exception show error code and transactionid so it can be relayed to helpdesk.
        system.out.println(
                "service exception - " +
                        exception.getfaultinfo().getdetail().geterrorcode() +
                        " transactionguid: " +
                        exception.getfaultinfo().gettransactionid()
        );
    } catch (exception exception) {
        system.out.println("problem checking details.");
    }
 
    return response;
}

The exception handling is done here as we are outputting to the console we do not require access to any GUI objects. This also means the exception handling will work if doing an extended address lookup.

Bank Integration

The following code will expand on the examples to demonstrate an integration into the Bank Account validation service.

Sample Code

The bank account lookup method:

private static void dobankcheck() throws exception {
    system.out.println("enter short code: ");
    final string shortcode = globalservicelookup.reader.readline();
    system.out.println("enter account number: ");
    final string accountnumber = globalservicelookup.reader.readline();
 
    // ws call
    final executecaptureresponse response = globalservicelookup.globalservices.bankcheck(
            shortcode, accountnumber);
 
    // check for bank results
    boolean found = false;
    if (response != null
            && response.getprofileresponse() != null
            && response.getprofileresponse().getprofileresponsedetails() != null) {
        for (profileresponsedetails profileresponse :
            response.getprofileresponse().getprofileresponsedetails()) {
            if ("bank account validation".equals(profileresponse.getcomponentname())) {
                if (profileresponse.getcomponentstatus() == enumcomponentstatus.success) {
                    if (profileresponse.getvalidateresponse() != null &&
                        profileresponse.getvalidateresponse().getresponse() != null &&
                        !profileresponse.getvalidateresponse().getresponse().isempty() &&
                        profileresponse.getvalidateresponse().getresponse().get(0) != null &&
                        profileresponse.getvalidateresponse().getresponse().get(0).getvalidationcodes() != null &&
                        profileresponse.getvalidateresponse().getresponse().get(0).getvalidationcodes().getitem() != null) {
                        final list<idmdataitem> items =
                            profileresponse.getvalidateresponse().getresponse().get(0).getvalidationcodes().getitem();
                        for (final idmdataitem item : items) {
                            final string line = item.getkey() + ": " + item.getvalue();
                            system.out.format("%20s", globalservicelookup.line_indent + "- " + line + "\n");
                        }
                    } else {
                        system.out.format("%20s", globalservicelookup.line_indent +
                            "- web service call successed but no results returned." + "\n");
                    }
                } else {
                    system.out.format("%20s", globalservicelookup.line_indent + "- failure" + "\n");
                }
                found = true;
                break;
            }
        }
    }
    if (!found) {
        system.out.format("%20s", globalservicelookup.line_indent + "- " + "web service failure" + "\n");
    }
}

This method will call the doBankCheck() method and handle the response to display. The data is output to the console separated by tabs using the GlobalServiceLookup.LINE_INDENT string. 

The following is the bankCheck() method. It is very similar to the C# sample code.

public executecaptureresponse bankcheck(final string sortcode, final string accountnumber) {
 
    // setup the objects to use on the globalservices.
    executecapturerequest request = new executecapturerequest();
    profilerequestcapture profilerequestcapture = new profilerequestcapture();
    profilerequestcapturedata profilerequestcapturedata = new profilerequestcapturedata();
 
    // idm options
    profilerequestcapture.setconfigurationid(1);
    profilerequestcapture.setcustomerreference("samplecode");
    profilerequestcapture.setprofileguid(globalserviceswsimpl.bank_check_guid);
 
    final idmdatacapturebank datacapture = new idmdatacapturebank();
    datacapture.setaccountnumber(accountnumber);
    datacapture.setsortcode(sortcode);
 
    // add the objects to form a complete request.
    request.setprofilerequest(profilerequestcapture);
    profilerequestcapture.setrequestdata(profilerequestcapturedata);
    profilerequestcapturedata.setoptions(this.getidmaddressoptions());
    profilerequestcapturedata.getbank().add(datacapture);
 
    // call execute capture.
    return this.executecapture(request);
}

AddressBase Premium

The following code will expand on the examples to demonstrate an integration into the AddressBase Premium capture service.

Sample Code

The AddressBase Premium lookup method:

private static void doaddressbasepremiumlookup() throws ioexception {
    string postcode = "";
    string building = "";
 
    // keep trying to get an input for a postcode from user.
    while (postcode.isempty()) {
        system.out.println("enter postcode: ");
        // readline pauses the application an waits for user input.
        postcode = globalservicelookup.reader.readline();
    }
    // ask once for a building from user.
    system.out.println("enter building: ");
    // readline pauses the application an waits for user input.
    building = globalservicelookup.reader.readline();
 
    // ws call
    final executecaptureresponse response = globalservicelookup.globalservices.addressbasepremiumlookup(postcode, building);
 
    // check for addressbasepremium results
    boolean found = false;
    stringbuilder sboutput = new stringbuilder();
 
    if (response != null
            && response.getprofileresponse() != null
            && response.getprofileresponse().getprofileresponsedetails() != null) {
        for (profileresponsedetails profileresponse : response.getprofileresponse().getprofileresponsedetails()) {
            if ("addressbase premium".equals(profileresponse.getcomponentname())) {
 
                sboutput.append(profileresponse.getcomponentstatus().tostring() + system.lineseparator());
                if (profileresponse.getcomponentstatus() == enumcomponentstatus.success) {
                    found = true;
                }
                if (profileresponse.getcaptureresponse() != null
                        && profileresponse.getcaptureresponse().getresponse() != null
                        && !profileresponse.getcaptureresponse().getresponse().isempty()) {
                    for (captureresponsedata captureresponsedata : profileresponse.getcaptureresponse().getresponse()) {
                        if (captureresponsedata.getaddress() != null
                                && !captureresponsedata.getaddress().isempty()) {
                            for (idmdataaddress singleaddress : captureresponsedata.getaddress()) {
                                string formatttedaddress = singleaddress.getformattedaddress();
                                sboutput.append(globalservicelookup.line_indent +
                                    "- " + "formattedaddress:" +
                                    formatttedaddress + system.lineseparator());
                                sboutput.append(globalservicelookup.line_indent +
                                    "- " + "osapr:" +
                                    singleaddress.getaposapr() + system.lineseparator());
                                sboutput.append(globalservicelookup.line_indent +
                                    "- " + "al2toid:" +
                                    singleaddress.getosal2toid() + system.lineseparator());
                                sboutput.append(globalservicelookup.line_indent +
                                    "- " + "itntoid:" +
                                    singleaddress.getositntoid() + system.lineseparator());
                                sboutput.append(globalservicelookup.line_indent +
                                    "- " + "topotoid:" +
                                    singleaddress.getostopotoid() + system.lineseparator());
 
                                idmdatablpu blpu = singleaddress.getblpu();
                                if (null != blpu) {
                                    sboutput.append(globalservicelookup.line_indent +
                                        "- " + "blpu.state:" + blpu.getblpustate() + system.lineseparator());
                                    if (null != blpu.getblpustartdate()) {
                                        idmdatadate startdate = blpu.getblpustartdate();
                                        if (null != startdate) {
                                            sboutput.append(globalservicelookup.line_indent +
                                                "- " + "blpu.startdate:" +
                                                startdate.getyear() + "-" + startdate.getmonth() + "-" + startdate.getday() +
                                                system.lineseparator());
                                        }
                                    }
                                    sboutput.append(globalservicelookup.line_indent +
                                        "- " + "blpu.logicalstatus:" +
                                        blpu.getblpulogicalstatus() + system.lineseparator());
                                    sboutput.append(globalservicelookup.line_indent +
                                        "- " + "blpu.easting:" +
                                        blpu.geteasting() + system.lineseparator());
                                    sboutput.append(globalservicelookup.line_indent +
                                        "- " + "blpu.northing:" +
                                        blpu.getnorthing() + system.lineseparator());
                                }
 
                                idmdatalpi lpi = singleaddress.getlpi();
                                if (null != lpi) {
                                    sboutput.append(globalservicelookup.line_indent +
                                        "- " + "lpi.key:" +
                                        lpi.getlpikey() + system.lineseparator());
                                    sboutput.append(globalservicelookup.line_indent +
                                        "- " + "lpi.level:" +
                                        lpi.getlevel() + system.lineseparator());
                                    sboutput.append(globalservicelookup.line_indent +
                                        "- " + "lpi.language:" +
                                        lpi.getlpilanguage() + system.lineseparator());
                                    sboutput.append(globalservicelookup.line_indent +
                                        "- " + "lpi.logicalstatus:" +
                                        lpi.getlpilogicalstatus() + system.lineseparator());
                                }
                            }
                        }
                    }
                }
            }
        }
        // display
        system.out.print(sboutput.tostring());
    }
    if (!found) {
        system.out.format("%20s", globalservicelookup.line_indent + "- " + "web service failure" + "\n");
    }
}

This method calls the doAddressBasePremiumLookup() method and handles the response to display. The data is output to the console separated by tabs using the GlobalServiceLookup.LINE_INDENT string. 

The following is the addressBasePremiumLookup() method. It is very similar to the C# sample code.

public executecaptureresponse addressbasepremiumlookup(final string postcode, final string building) {
    // setup the objects to use on the capture request.
    executecapturerequest request = new executecapturerequest();
    profilerequestcapture profilerequestcapture = new profilerequestcapture();
    profilerequestcapturedata profilerequestcapturedata = new profilerequestcapturedata();
 
    // idm options
    profilerequestcapture.setconfigurationid(1);
    profilerequestcapture.setcustomerreference("samplecode");
    profilerequestcapture.setprofileguid(globalserviceswsimpl.addressbase_premium_profile_guid);
 
    // add the objects to form a complete request.
    request.setprofilerequest(profilerequestcapture);
    profilerequestcapture.setrequestdata(profilerequestcapturedata);
 
    idmdatasearchaddress idmdatasearchaddress = new idmdatasearchaddress();
    idmdatasearchaddress.setpostcode(postcode);
    // building is optional
    if ((null != building) && (0 < building.trim().length())) {
        idmdatasearchaddress.setbuilding(building);
    }
 
    profilerequestcapturedata.setaddress(idmdatasearchaddress);
    profilerequestcapturedata.setoptions(this.getidmaddressoptions());
 
    // call execute capture.
    return this.executecapture(request);
}

Matchcode Names

The following code will expand on the examples to demonstrate an integration into the Matchcode Names capture service.

Sample Code

The following Names lookup method formats the results with \t (tab) to make them more human readable:

private static void donamesearching() throws ioexception {
 
    system.out.println("note: not all fields are required.");
 
    final person person = new person();
 
    system.out.println("enter firstname: ");
    person.setfirstname(globalservicelookup.reader.readline());
 
    system.out.println("enter lastname: ");
    person.setlastname(globalservicelookup.reader.readline());
 
    system.out.println("date of birth: ");
    system.out.println("enter day: ");
    person.getdateofbirth().setday(globalservicelookup.reader.readline());
 
    system.out.println("enter month: ");
    person.getdateofbirth().setmonth(globalservicelookup.reader.readline());
 
    system.out.println("enter year: ");
    person.getdateofbirth().setyear(globalservicelookup.reader.readline());
 
    system.out.println("enter building number or name: ");
    person.getaddress().setbuilding(globalservicelookup.reader.readline());
 
    system.out.println("enter postcode: ");
    person.getaddress().setpostcode(globalservicelookup.reader.readline());
 
    // ws call
    final executecaptureresponse response = globalservicelookup.globalservices.namesearch(person);
 
    boolean found = false;
    if (response != null
            && response.getprofileresponse() != null
            && response.getprofileresponse().getprofileresponsedetails() != null) {
        for (profileresponsedetails profileresponse : response.getprofileresponse().getprofileresponsedetails()) {
            if ("matchcode edited electoral roll names".equals(profileresponse.getcomponentname())) {
                if (profileresponse.getcomponentstatus() == enumcomponentstatus.success) {
                    system.out.println("found results:");
 
                    for (captureresponsedata captureresponse : profileresponse.getcaptureresponse().getresponse()) {
                        for (idmdataaddress idmdataaddress : captureresponse.getaddress()) {
                            int peoplefound = 0;
 
                            if (idmdataaddress.getpersons() != null &&
                                    idmdataaddress.getpersons().getperson() != null) {
                                peoplefound = idmdataaddress.getpersons().getperson().size();
                            }
 
                            system.out.println(peoplefound + " at the following address:");
                            system.out.println("\t" + idmdataaddress.getformattedaddress());
                            system.out.println("\tpeople:");
 
                            if (peoplefound > 0) {
                                for (idmdataperson returnedperson : idmdataaddress.getpersons().getperson()) {
                                    system.out.println("\t\t" + "firstname:\t" +
                                        returnedperson.getfirstname());
                                    system.out.println("\t\t" + "middlename:\t" +
                                        returnedperson.getmiddlename());
                                    system.out.println("\t\t" + "lastname:\t" +
                                        returnedperson.getlastname());
                                    system.out.println("\t\t" + "gender:\t\t" +
                                        returnedperson.getgender());
                                    system.out.println("\t\t" + "dob:\t\t" +
                                        formatter.getformatteddate(returnedperson.getdateofbirth()));
                                    system.out.println(" ");
                                }
                            }
 
                            found = true;
                        }
                    }
                }
            }
        }
    }
    if (!found) {
        system.out.format("%20s", globalservicelookup.line_indent + "- " + "web service failure" + "\n");
    }
}

This shows the construction of the request:

@override
public executecaptureresponse namesearch(final person person) {
 
    // setup the objects to use on the capture request.
    executecapturerequest request = new executecapturerequest();
    profilerequestcapture profilerequestcapture = new profilerequestcapture();
    profilerequestcapturedata profilerequestcapturedata = new profilerequestcapturedata();
 
    // idm options
    profilerequestcapture.setconfigurationid(1);
    profilerequestcapture.setcustomerreference("samplecode");
    profilerequestcapture.setprofileguid(globalserviceswsimpl.matchcode_names_profile_guid);
 
    // add the objects to form a complete request.
    request.setprofilerequest(profilerequestcapture);
    profilerequestcapture.setrequestdata(profilerequestcapturedata);
 
    idmdatasearchaddress idmdatasearchaddress = new idmdatasearchaddress();
 
    idmdatasearchaddress.setfreeformataddress(person.getaddress().getfreeformattedaddress());
 
    idmdatacaptureperson wsperson = new idmdatacaptureperson();
    wsperson.setfirstname(person.getfirstname());
    wsperson.setlastname(person.getlastname());
 
    idmdatadatewithrange dateofbirth = new idmdatadatewithrange();
 
    if (person.getdateofbirth().hasvaliddob()) {
        dateofbirth.setday(person.getdateofbirth().getintday());
        dateofbirth.setmonth(person.getdateofbirth().getintmonth());
        dateofbirth.setyear(person.getdateofbirth().getintyear());
    }
 
    if (person.getaddress().hasaddress()) {
        idmdatasearchaddress.setfreeformataddress(person.getaddress().getfreeformattedaddress());
    }
 
    wsperson.setdateofbirth(dateofbirth);
    idmdataarrayofcaptureperson arrayofcaptureperson = new idmdataarrayofcaptureperson();
    idmdatasearchaddress.setpersons(arrayofcaptureperson);
    idmdatasearchaddress.getpersons().getperson().add(wsperson);
 
    profilerequestcapturedata.setaddress(idmdatasearchaddress);
    profilerequestcapturedata.setoptions(this.getidmaddressoptions());
    return this.executecapture(request);
}

The method uses a placeholder object for the person. It has some utility methods that help with the creation of the request. The following method checks the date for a valid input:

public boolean hasvaliddob() {
    try {
        integer.parseint(this.getday());
        integer.parseint(this.getmonth());
        integer.parseint(this.getyear());
    } catch (numberformatexception e) {
        system.out.println("invalid dob continuing search without.");
        return false;
    }
    return true;
}

Matchcode Premium

Matchcode Premium allows the user to lookup consented telephone numbers for an individual, and also lookup references on social media.

Sample code

The sample code shows how to request the person information, and how to request the type of search required (the social flow type).

private static void domatchcodepremiumsearching() throws ioexception {
    string postcode = "";
    string building = "";
    string firstname = "";
    string lastname = "";
    string email = "";
 
    // keep trying to get an input for a postcode from user.
    while (postcode.isempty()) {
        system.out.println("enter postcode: ");
        // readline pauses the application an waits for user input.
        postcode = globalservicelookup.reader.readline();
    }
    // ask once for a building from user.
    system.out.println("enter building: ");
    // readline pauses the application an waits for user input.
    building = globalservicelookup.reader.readline();
 
    // ask once for a firstname from user.
    system.out.println("enter first name: ");
    // readline pauses the application an waits for user input.
    firstname = globalservicelookup.reader.readline();
 
    // ask once for a lastname from user.
    system.out.println("enter last  name: ");
    // readline pauses the application an waits for user input.
    lastname = globalservicelookup.reader.readline();
 
    final person person = new person();
    person.setlastname(lastname);
    person.setfirstname(firstname);
    person.getaddress().setbuilding(building);
    person.getaddress().setpostcode(postcode);
 
    // ask once for an email from user.
    system.out.println("enter email address: ");
    // readline pauses the application an waits for user input.
    email = globalservicelookup.reader.readline();
 
    // request flowtype
    enummatchcodepremiumsocialflowtype socialflowtype = enummatchcodepremiumsocialflowtype.append;
    system.out.println("select flow type:");
    system.out.println("  a - append (default)");
    system.out.println("  s - social");
    system.out.print("enter selection: ");
    string userinput = globalservicelookup.reader.readline();
    if(userinput.equalsignorecase("s")) {
        socialflowtype = enummatchcodepremiumsocialflowtype.social;
    }
    system.out.println("using flow type => "+socialflowtype.tostring());
 
    boolean fetchconsented = true;
    if(socialflowtype==enummatchcodepremiumsocialflowtype.append) {
        fetchconsented = true;
    }
 
    // ws call
    final executecaptureresponse response = globalservicelookup.globalservices.matchcodepremiumsearch(
            person, email, socialflowtype, fetchconsented);
 
    // check for addressbasepremium results
    boolean found = false;
    stringbuilder sboutput = new stringbuilder();
 
    if (response != null
            && response.getprofileresponse() != null
            && response.getprofileresponse().getprofileresponsedetails() != null) {
        for (profileresponsedetails profileresponse : response.getprofileresponse().getprofileresponsedetails()) {
            if ("matchcode premium".equals(profileresponse.getcomponentname())) {
 
                sboutput.append(profileresponse.getcomponentstatus().tostring() + system.lineseparator());
                if (profileresponse.getcomponentstatus() == enumcomponentstatus.success) {
                    found = true;
                }
                if (profileresponse.getcaptureresponse() != null
                        && profileresponse.getcaptureresponse().getresponse() != null
                        && !profileresponse.getcaptureresponse().getresponse().isempty()) {
                    for (captureresponsedata captureresponsedata : profileresponse.getcaptureresponse().getresponse()) {
                        if (captureresponsedata.getaddress() != null
                                && !captureresponsedata.getaddress().isempty()) {
                            for (idmdataaddress singleaddress
                                    : captureresponsedata.getaddress()) {
                                string formatttedaddress = singleaddress.getformattedaddress();
                                sboutput.append(globalservicelookup.line_indent +
                                    "- " + "formattedaddress:" +
                                    formatttedaddress +
                                    system.lineseparator());
 
                                if((null!=singleaddress.getpersons()) &&
                                        (null!=singleaddress.getpersons().getperson())) {
                                    for(idmdatacaptureperson singleperson
                                            : singleaddress.getpersons().getperson()) {
                                        sboutput.append("\t\t" +
                                            "firstname:\t" + singleperson.getfirstname() +
                                            system.lineseparator());
                                        sboutput.append("\t\t" + "middlename:\t" +
                                            singleperson.getmiddlename() +
                                            system.lineseparator());
                                        sboutput.append("\t\t" + "lastname:\t" +
                                            singleperson.getlastname() +
                                            system.lineseparator());
                                        sboutput.append("\t\t" + "gender:\t\t" +
                                            singleperson.getgender() +
                                            system.lineseparator());
                                        sboutput.append("\t\t" + "dob:\t\t" +
                                            formatter.getformatteddate(singleperson.getdateofbirth()) +
                                            system.lineseparator());
                                        if ((null != singleperson.getconsentedemails()) &&
                                                (0 < singleperson.getconsentedemails().size())) {
                                            for (idmdatasourcedvalue idmdatasourcedvalue
                                                    : singleperson.getconsentedemails()) {
                                                sboutput.append("\t\t" +
                                                "email:\t" +
                                                idmdatasourcedvalue.getvalue() +
                                                system.lineseparator());
                                            }
                                        }
                                        if ((null != singleperson.getconsentedlandlines()) &&
                                                (0 < singleperson.getconsentedlandlines().size())) {
                                            for (idmdatasourcedvalue idmdatasourcedvalue
                                                    : singleperson.getconsentedlandlines()) {
                                                sboutput.append("\t\t" +
                                                "landline:\t" +
                                                idmdatasourcedvalue.getvalue() +
                                                system.lineseparator());
                                            }
                                        }
                                        if ((null != singleperson.getconsentedmobiles()) &&
                                                (0 < singleperson.getconsentedmobiles().size())) {
                                            for (idmdatasourcedvalue idmdatasourcedvalue
                                                    : singleperson.getconsentedmobiles()) {
                                                sboutput.append("\t\t" +
                                                "mobile:\t" +
                                                idmdatasourcedvalue.getvalue() +
                                                system.lineseparator());
                                            }
                                        }
                                        if ((null != singleperson.getadditionalitems()) &&
                                                (null!= singleperson.getadditionalitems().getitem()) &&
                                                (0 < singleperson.getadditionalitems().getitem().size())) {
                                            for(idmdataitem idmdataitem
                                                    : singleperson.getadditionalitems().getitem()) {
                                                sboutput.append("\t\t" +
                                                idmdataitem.getkey() +
                                                ":\t" +
                                                idmdataitem.getvalue() +
                                                system.lineseparator());
                                            }
                                        }
                                        sboutput.append(" ");
                                    }
                                }
 
                            }
                        }
 
                        if((null!=captureresponsedata.getgroupedrelateddata()) &&
                                (0 < captureresponsedata.getgroupedrelateddata().size())) {
                            for(idmdataadditionaldatagroup idmdataadditionaldatagroup
                                    : captureresponsedata.getgroupedrelateddata()) {
                                string groupname = idmdataadditionaldatagroup.getname();
                                sboutput.append("\t\t" + groupname +system.lineseparator());
                                list<idmdataitem> listofgroupdataitem = idmdataadditionaldatagroup.getitem();
                                if((null!=listofgroupdataitem) && (0<listofgroupdataitem.size())) {
                                    for(idmdataitem idmdataitem : listofgroupdataitem) {
                                        sboutput.append("\t\t\t" +
                                        idmdataitem.getkey() +
                                        ":\t" +
                                        idmdataitem.getvalue() +
                                        system.lineseparator());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // display
        system.out.print(sboutput.tostring());
    }
    if (!found) {
        system.out.format("%20s", globalservicelookup.line_indent + "- " + "web service failure" + "\n");
    }
}

Information from social media is returned in the IdmDataAdditionalDataGroup data structure, which can be pared as shown above.

The actual search requires additional parameters, which for convenience are prescribed in the sample code to limit the amount of user input required.

protected static final enummatchcodepremiumsocialtype
    matchcode_premium_social_type = enummatchcodepremiumsocialtype.social_automatic;
protected static final int
    matchcode_premium_social_total = 5;
protected static final enummatchcodepremiumconsentedtype
    matchcode_premium_consented_type = enummatchcodepremiumconsentedtype.any;
protected static final int
    matchcode_premium_consented_total = 5;

The matchcodePremiumSearch() method:

@override
public executecaptureresponse matchcodepremiumsearch(
        final person person,
        final string email,
        enummatchcodepremiumsocialflowtype socialflowtype,
        boolean fetchconsented) {
    // setup the objects to use on the capture request.
    executecapturerequest request = new executecapturerequest();
    profilerequestcapture profilerequestcapture = new profilerequestcapture();
    profilerequestcapturedata profilerequestcapturedata = new profilerequestcapturedata();
 
    // idm options
    profilerequestcapture.setconfigurationid(1);
    profilerequestcapture.setcustomerreference("samplecode");
    profilerequestcapture.setprofileguid(globalserviceswsimpl.matchcode_premium_profile_guid);
 
    // add the objects to form a complete request.
    request.setprofilerequest(profilerequestcapture);
    profilerequestcapture.setrequestdata(profilerequestcapturedata);
 
    idmdatasearchaddress idmdatasearchaddress = new idmdatasearchaddress();
 
    idmdatasearchaddress.setfreeformataddress(person.getaddress().getfreeformattedaddress());
 
    idmdatacaptureperson wsperson = new idmdatacaptureperson();
    wsperson.setfirstname(person.getfirstname());
    wsperson.setlastname(person.getlastname());
 
    idmdatasearchaddress.setpostcode((person.getaddress().getpostcode()));
    idmdatasearchaddress.setbuilding((person.getaddress().getbuilding()));
 
    idmdataarrayofcaptureperson arrayofcaptureperson = new idmdataarrayofcaptureperson();
    idmdatasearchaddress.setpersons(arrayofcaptureperson);
    idmdatasearchaddress.getpersons().getperson().add(wsperson);
    profilerequestcapturedata.setaddress(idmdatasearchaddress);
 
    // email
    if(!email.isempty()) {
        profilerequestcapturedata.getemail().add(email);
    }
    // additional data
    idmdataarrayadditionaldata idmdataarrayadditionaldata = new idmdataarrayadditionaldata();
    list<idmdataitem> listofadditionaldataitem = idmdataarrayadditionaldata.getitem();
    // consented
    idmdataitem dataitemconsented = new idmdataitem();
    dataitemconsented.setkey("consented");
    dataitemconsented.setvalue(fetchconsented ? "yes" : "no");
    listofadditionaldataitem.add(dataitemconsented);
    // flow_type
    idmdataitem dataitemflowtype = new idmdataitem();
    dataitemflowtype.setkey("flow_type");
    dataitemflowtype.setvalue(socialflowtype.tostring());
    listofadditionaldataitem.add(dataitemflowtype);
    // consented_type
    idmdataitem dataitemconsentedtype = new idmdataitem();
    dataitemconsentedtype.setkey("consented_type");
    dataitemconsentedtype.setvalue(matchcode_premium_consented_type.tostring());
    listofadditionaldataitem.add(dataitemconsentedtype);
    // consented_total
    idmdataitem dataitemconsentedtotal = new idmdataitem();
    dataitemconsentedtotal.setkey("consented_total");
    dataitemconsentedtotal.setvalue(integer.tostring(matchcode_premium_consented_total));
    listofadditionaldataitem.add(dataitemconsentedtotal);
    // social_request_action
    idmdataitem dataitemsocialrequestaction = new idmdataitem();
    dataitemsocialrequestaction.setkey("social_request_action");
    dataitemsocialrequestaction.setvalue(matchcode_premium_social_type.tostring());
    listofadditionaldataitem.add(dataitemsocialrequestaction);
    // social_email_total
    idmdataitem dataitemsocialemailtotal = new idmdataitem();
    dataitemsocialemailtotal.setkey("social_email_total");
    dataitemsocialemailtotal.setvalue(integer.tostring(matchcode_premium_social_total));
    listofadditionaldataitem.add(dataitemsocialemailtotal);
 
    profilerequestcapturedata.setadditionaldata(idmdataarrayadditionaldata);
    profilerequestcapturedata.setoptions(this.getidmpremiumoptions());
    return this.executecapture(request);
}

MatchcodePremium requires slightly different options from a simple address or telephone lookup - in particular the search type must be set to REGISTER.

private idmrequestoptions getidmpremiumoptions() {
    idmrequestoptions options = new idmrequestoptions();
 
    options.setaddresssearchlevel(enumaddresslevel.premise);
    options.setaddresssearchtype(enumaddresssearchtype.register);
    options.setcasing(enumcasing.mixed);
    options.setmaxreturn(10);
    options.setoffset(0);
    options.setaddressenvelopeformat("a3tcp");
 
    return options;
}

Exception Handling

The exception handling is done here as we are outputting to the console we do not require access to any GUI objects. This also means the exception handling will work if doing an extended address lookup.

private executecaptureresponse executecapture(executecapturerequest request) {
 
    // gets the security header will do an authentication if there is not a valid authentication token.
    request.setsecurityheader(this.getsecurityheader());
    executecaptureresponse response = null;
 
    try {
        // try calling the webservice
        response = this.getwebservice().executecapture(request);
        this.user.refreshauthenticationtoken(
        response.getsecurityheader().getauthenticationtoken(),
        response.getsecurityheader().getsessionexpirytime().togregoriancalendar().gettime());
    } catch (businessexception exception) {
 
        // todo: handle exception
        // catch a specific exception and display message
        if (exception.getfaultinfo().getdetail().geterrorcode().equals("be010009")) {
            system.out.println("invalid credentials");
        } else {
            system.out.println("business exception errorcode: " + exception.getfaultinfo().getdetail().geterrorcode());
        }
 
    } catch (serviceexception exception) {
 
        // todo: handle exception
        // service exception show error code and transactionid so it can be relayed to helpdesk.
        system.out.println("service exception - "
                + exception.getfaultinfo().getdetail().geterrorcode()
                + " transactionguid: "
                + exception.getfaultinfo().gettransactionid());
 
    } catch (exception exception) {
 
        // todo: handle exception
        system.out.println("problem checking details.");
    }
    return response;
}

Project Source Code

Download the source code here: idm-globalservices-integration-example

PowerSearch REST Integration

Ensure you have an account setup. You will need the Username and Password

If you are unsure of any of the details you can contact the helpdesk for more information.

Creating the Application

Next, we will take a look at several key parts of the Powersearch REST Client Application.

Service Layer (REST Client)

In this example a service layer is created to handle the calls to the REST Web Service. First an interface is created.

This helps separate the code out so the implementation can be changed without much consequence. For instance, we will provide an implementation of a Rest Client using a concrete technology (Apache HttpClient), but the interface operations might be implemented by using any other technology.

Next, the code for this Interface:

public interface ipowersearchrestservice {
    /**
     * communicate to the server to perform the globaladdress operation
     * 
     * @param country
     * @param input
     * @param sessionkey
     * @param format
     * @return
     */
    clientresponse<globalresponse> getglobaladdress(string country, string input, string sessionkey,
            string format);
 
    /**
     * communicate to the server to perform the geocode operation
     * 
     * @param country
     * @param input
     * @return
     */
    clientresponse<globalresponse> getgeocode(string country, string input);
}

As displayed, the Service Client Interface offers two operations to be implemented. These are the same as those offered Powersearch REST WebService.

The following code is the implementation for the two Service Interface Methods

public class powersearchrestservice implements ipowersearchrestservice {
 
    private static final string json_format = "application/json";
    private static final string xml_format = "application/xml";
     
    private settings settings;
     
    public powersearchrestservice(settings settings) {
        this.settings = settings;
    }
     
    @override
    public clientresponse<globalresponse> getglobaladdress(string country, string input, string sessionkey,
            string format) {
        map<string, string> params = new hashmap<>();
        params.put("address", input);
        if (sessionkey != null) {
            params.put("sessionkey", sessionkey);
        }
        if (format != null) {
            params.put("format", format);
        }
        string powersearchurl = settings.geturl();
        // add the countrycode to the url
        powersearchurl = new stringbuffer(powersearchurl).append("/").append(country).tostring();
        httpresponse httpresponse = null;
        try {
            httpresponse = getserverresponse(powersearchurl, params);
        }
        catch (ioexception e) {
            throw new runtimeexception("error when connecting to the server", e);
        }
        globalresponse response = deserializetoobject(httpresponse, settings.getacceptformat(), globalresponse.class);
        return new clientresponse<globalresponse>(response, httpresponse.getstatusline().getstatuscode());
    }
 
    @override
    public clientresponse<globalresponse> getgeocode(string country, string input) {
        map<string, string> params = new hashmap<>();
        params.put("address", input);       
        string powersearchurl = settings.geturl();
        // add the countrycode to the url
        powersearchurl = new stringbuffer(powersearchurl).append("/").append(country).append("/").append("geo").tostring();
        httpresponse httpresponse = null;
        try {
            httpresponse = getserverresponse(powersearchurl, params);
        }
        catch (ioexception e) {
            throw new runtimeexception("error when connecting to the server", e);
        }       
        globalresponse response = deserializetoobject(httpresponse, settings.getacceptformat(), globalresponse.class);
        return new clientresponse<globalresponse>(response, httpresponse.getstatusline().getstatuscode());
    }
 
    /**
     * perform an http request to the rest server. it uses the apache httpclient library to do it.
     * 
     * @param httpgetquery
     * @param params
     * @return
     * @throws ioexception
     */
    private httpresponse getserverresponse(string httpgetquery,
            map<string, string> params) throws ioexception {
 
        credentialsprovider provider = new basiccredentialsprovider();
        usernamepasswordcredentials credentials = new usernamepasswordcredentials(settings.getidmusername(), settings.getidmpassword());
        provider.setcredentials(authscope.any, credentials);
        httpclient client = httpclientbuilder.create().setdefaultcredentialsprovider(provider).build();
         
        httpget request = new httpget(buildhttpgeturl(httpgetquery, params));
        request.addheader("accept", settings.getacceptformat());
 
        httpresponse response = client.execute(request);
        return response;
 
    }
 
    /**
     * compose a url to perform a get http method
     * 
     * @param httpgetquery
     * @param params
     * @return
     * @throws ioexception
     */
    private string buildhttpgeturl(string httpgetquery,
            map<string, string> params) throws ioexception {
        stringbuffer sb = new stringbuffer(httpgetquery);
        if (params != null) {
            if (params.size() > 0) {
                sb.append("?");
            }
            for (map.entry<string, string> entry : params.entryset()) {
                sb.append(entry.getkey()).append("=").append(urlencoder.encode(entry.getvalue(),"utf-8"));
                sb.append("&");
            }
        }
        return sb.tostring();
    }   
     
    /**
     * given an httpresponse, deserialize the content to an object
     * 
     * @param httpresponse
     * @param format
     * @param clazz
     * @return
     */
    private <t> t deserializetoobject(httpresponse httpresponse, string format, class<t&gt clazz) {
        t response = null;
        if (format.equalsignorecase(json_format)) {
            try {
                objectmapper mapper = new objectmapper();
                response = mapper.readvalue(httpresponse.getentity().getcontent(), clazz);
            }
            catch (exception e) {
                throw new runtimeexception("error when parsing the response json", e);
            }           
        }
        else if (format.equalsignorecase(xml_format)) {
            try {
                jaxbcontext jaxbcontext = jaxbcontext.newinstance(clazz);            
                unmarshaller jaxbunmarshaller = jaxbcontext.createunmarshaller();
                response = (t) jaxbunmarshaller.unmarshal(httpresponse.getentity().getcontent());
            }
            catch (exception e) {
                throw new runtimeexception("error when parsing the response xml", e);
            }           
        }       
        return response;
    }
         
}

The getGlobalAddress method performs the Powersearch REST Service Operation called GlobalAddress by composing the URL, adding the parameters and connecting to the Server. The parameters must be within the URL since the REST operation just allows HTTP GET Requests. The method returns ClientResponse, which contains an object full of data and a status code representing the HTTP Response Status.

The getGeocode method performs the Powersearch REST Service Operation called Geocode by composing the URL, adding the parameters and connecting to the Server. Again, the parameters must be within the URL since the this REST operation just allows HTTP GET Requests. The method returns ClientResponse, which contains an object full of data and a status code representing the HTTP Response Status.

Some non-public methods are added to the Service Implementation such as the one in charge of connecting to the Server and getting a HTTP Response (implemented by Apache HttpClient library) and the one de-serializing the XML or JSON Response from the Server into a known Java Object. We'll see this process below

This process is shown below.

Response Deserialization

The PowerSearch REST WebService returns the requested information either in XML or JSON format. This depends on the "Accept" header parameter value. To deal with that information in the Client Application it's highly recommended to de-serialize the chunk of characters (XML or JSON) into some Data Transfer Objects. This makes easier work with the data.

To de-serialize XML or JSON into Objects we need two things: A process to fill the Objects with data and the Objects to be filled. Keeping in mind the information structure returned by the Service, the Data Transfer Objects created to allocate it are as follows:

public class globalresponse {
 
    @xmlelement(name = "sessiondata")
    private sessiondata sessiondata;
 
    @xmlelement(name = "matches")
    private list<string> matches = new arraylist<string>();
 
    @xmlelement(name = "information")
    private string information;
     
    @xmlelement(name="address")
    private powersearchaddress address;
 
    /**
     * no information required.
     */
    public globalresponse() {
    }
 
    /**
     *
     * @param sessiondata
     *            sessiondata
     */
    public globalresponse(final sessiondata sessiondata) {
        this.sessiondata = sessiondata;
    }
 
    /**
     *
     * @param information
     *            string
     */
    public globalresponse(final string information) {
        this.information = information;
    }
 
    /**
     *
     * @param matches
     *            list
     * @param sessiondata
     */
    public globalresponse(final list<string> matches, final sessiondata sessiondata) {
        this.matches = matches;
        this.sessiondata = sessiondata;
    }
 
    /**
     *
     * @return list
     */
    public list<string> getmatches() {
        return matches;
    }
 
    /**
     * information that could be useful to the client.
     *
     * @return string
     */
    public string getinformation() {
        return information;
    }
 
    public sessiondata getsessiondata() {
        return sessiondata;
    }
         
    /**
     * geoinformation
     * @return
     */
    public powersearchaddress getaddress() {
        return address;
    }
 
    public void setaddress(powersearchaddress address) {
        this.address = address;
    }
}
public class powersearchaddress {
    private string freeformat;
     
    @xmlelement(name = "easting")
    private string easting;
     
    @xmlelement(name = "northing")
    private string northing;
     
    @xmlelement(name = "latitude")
    private string latitude;
     
    @xmlelement(name = "longitude")
    private string longitude;
     
 
    public string getfreeformat() {
        return freeformat;
    }
 
    public void setfreeformat(string freeformat) {
        this.freeformat = freeformat;
    }
 
    public string geteasting() {
        return easting;
    }
 
    public void seteasting(string easting) {
        this.easting = easting;
    }
 
    public string getnorthing() {
        return northing;
    }
 
    public void setnorthing(string northing) {
        this.northing = northing;
    }
 
    public string getlatitude() {
        return latitude;
    }
 
    public void setlatitude(string latitude) {
        this.latitude = latitude;
    }
 
    public string getlongitude() {
        return longitude;
    }
 
    public void setlongitude(string longitude) {
        this.longitude = longitude;
    }
}
public class sessiondata {
 
    private string sessionkey;
    private date sessioncommencement;
    private int numberofsessiontransactions;
 
    @xmlelement
    public string getsessionkey() {
        return sessionkey;
    }
 
    @xmlelement
    @jsonformat(shape=shape.string, pattern="yyyy-mm-dd't'hh:mm:ss.sssxxx", timezone="gb")
    public date getsessioncommencement() {
        return sessioncommencement;
    }
 
    /**
     *
     * @return int
     */
    @xmlelement
    public int getnumberofsessiontransactions() {
        return numberofsessiontransactions;
    }
 
}

The above Data Transfer Object definitions are able to store all the information returned by Powersearch.

All the classes include some annotations such as @XmlElement or @JsonAutoDetect, whose purpose is to guide tools to fill the objects with information from either XML or JSON.

Once we have the Data Transfer Object classes, now it's time to fill these Objects by using some tools. In the case of XML, the provided sample code uses JAXB to de-serialize the XML data. In the case of JSON, the provided sample code uses Jackson to do the same for the JSON data. Next is the concrete code (seen before in the Service Implementation) using the tools:

private <t> t deserializetoobject(httpresponse httpresponse, string format, class<t> clazz) {
    t response = null;
    if (format.equalsignorecase(json_format)) {
        try {
            objectmapper mapper = new objectmapper();
            response = mapper.readvalue(httpresponse.getentity().getcontent(), clazz);
        }
        catch (exception e) {
            throw new runtimeexception("error when parsing the response json", e);
        }           
    }
    else if (format.equalsignorecase(xml_format)) {
        try {
            jaxbcontext jaxbcontext = jaxbcontext.newinstance(clazz);            
            unmarshaller jaxbunmarshaller = jaxbcontext.createunmarshaller();
            response = (t) jaxbunmarshaller.unmarshal(httpresponse.getentity().getcontent());
        }
        catch (exception e) {
            throw new runtimeexception("error when parsing the response xml", e);
        }           
    }       
    return response;
}

Integration

Next, we will see 2 examples of integration and some aspects to take into account when integrating Powersearch REST Webservice. The first one will search for an address (or partial address) using Global Address operation, and the second one, given a full address, will search for geocode information using Geocode operation.

Global Address Searching

Powersearch REST WebService offers the Global Address operation to find addresses. This operation accepts partial addresses so that the more accurate the address provided is the less addresses will be returned from the service. When the supplied address is accurate enough, the service will return the definitive address which can be formatted by using the format options (format parameter). The code to use Global Address Operation (through the Service Layer previously created) as follows:

private static void doglobalsearch() throws ioexception {
             
    system.out.println("enter the iso country code: ");
    string country = powersearchoperations.reader.readline().trim().touppercase();
     
    system.out.println("enter the address: ");
    string address = powersearchoperations.reader.readline().trim();
     
    system.out.println("enter the format for the returning address: ('no' to skip) ");
    string format = powersearchoperations.reader.readline().trim();
    if ("no".equalsignorecase(format)) {
        format = null;
    }
     
    clientresponse<globalresponse> clientresponse = restservice.getglobaladdress(country, address, sessionkey, format);
    globalresponse response = clientresponse.getresponse();
    if (clientresponse.getstatus() == httpstatus.sc_ok) {
        sessionkey = response.getsessiondata().getsessionkey();
        if (response.getmatches() != null && response.getmatches().size() > 0) {
            system.out.println("found results:");           
            for (string retaddress : response.getmatches()) {
                system.out.println("\t" + retaddress);
            }
        }           
    }
    else {
        processstatus(clientresponse.getstatus());
        if (response.getinformation() != null) {
            system.out.println("message: " + response.getinformation());
        }
    }       
     
}

As displayed, this is a Console based program. The three parameters to be supplied are Country Code (2 characters ISO Country Code), address or partial address to be found and the format to be applied to the returned address. Note that the format will only be applied in case the Address supplied is accurate enough so that the WebService returns a single address.

Note that the SessionKey returned by the WebService is stored in a sessionKey variable, to be used in the next Global Address request, and then used in the same session. In Powersearch REST Webservice, a Session gathers all the searches needed to find the definitive address with a maximum of 50 searches or 2 minutes.

Geocode Searching

Powersearch REST WebService offers the Geocode operation to get geographical information for an address. The Address supplied to this operation must be accurate enough to be identified unequivocally. Otherwise, the WebService will return a 404 (No Matches found). Thus, a normal process of using Powersearch WebService might be to use Global Address operation (as many times as needed) until a definitive address is found and afterwards supply this address to the Geocode operation in order to get the geographical information. The code to use Geocode Operation (through the Service Layer previously created) is as follows:

private static void dogeocodesearch() throws ioexception {
    system.out.println("enter the iso country code: ");
    string country = powersearchoperations.reader.readline().trim().touppercase();
     
    system.out.println("enter the address: ");
    string address = powersearchoperations.reader.readline().trim();
     
    clientresponse<globalresponse> clientresponse = restservice.getgeocode(country, address);
    globalresponse response = clientresponse.getresponse();
    if (clientresponse.getstatus() == httpstatus.sc_ok) {           
        system.out.println("found results:");           
        system.out.println("\taddress: " + response.getaddress().getfreeformat());
        system.out.println("\tlatitude: " + response.getaddress().getlatitude());
        system.out.println("\tlongitude: " + response.getaddress().getlongitude());
         
    }    
    else {
        processstatus(clientresponse.getstatus());
        if (response.getinformation() != null) {
            system.out.println("message: " + response.getinformation());
        }
    }
}

The two parameters to be supplied are Country Code (2 characters ISO Country Code) and the address that requires a geocode.

Authentication

Powersearch REST WebService uses HTTP Basic Authentication method. This means the client must send the credentials as a header parameter in every request to the Server (in the way the standard says).

In the code supplied, this is done by using the Apache HttpClient library, which hides the way the credentials are sent to the server so that, once the username and password are provided, the rest is done automatically.

Here is the code that uses Apache HttpClient library to provide the credentials:

private httpresponse getserverresponse(string httpgetquery,
        map<string, string> params) throws ioexception {
 
    credentialsprovider provider = new basiccredentialsprovider();
    usernamepasswordcredentials credentials = new usernamepasswordcredentials(settings.getidmusername(), settings.getidmpassword());
    provider.setcredentials(authscope.any, credentials);
    httpclient client = httpclientbuilder.create().setdefaultcredentialsprovider(provider).build();
     
    httpget request = new httpget(buildhttpgeturl(httpgetquery, params));
    request.addheader("accept", settings.getacceptformat());
 
    httpresponse response = client.execute(request);
    return response;
 
}

Http Status Codes Processing

As Powersearch is a REST WebService, the server status information after a request is provided as a HTTP Status code. The codes that could be returned by the service are:

200 - OK
404 - Address or Country not found
400 - Bad Request (something wrong in the request)
401 - Unauthorized (no credentials or bad credentials supplied)
403 - Access Denied (good credentials, but user with incorrect permissions)
500 - Internal Server Error

Thus, it's very useful for the client to process the returned status code in order to know exactly what went wrong with the request. Note that if everything is OK, and some matches for the search are returned (Global Address or Geocode), 200 status code will be returned. Also, if an error code other than 200 is returned by the server, some information will be added to the response, which can be found in the information field.

Below, the code to process the returned HTTP status codes:

private static void processstatus(int status) {     
    switch(status) {
    case httpstatus.sc_not_found:
        system.out.println("response status information: " + "address not found");
        break;
    case httpstatus.sc_bad_request:
        system.out.println("response status information: " + "invalid request");
        break;      
    case httpstatus.sc_forbidden:
        system.out.println("response status information: " + "access forbiden");
        break;
    case httpstatus.sc_unauthorized:
        system.out.println("response status information: " + "wrong user credentials");
        break;
    case httpstatus.sc_internal_server_error:
        system.out.println("response status information: " + "server error");
        break;
    }       
}

Configuration Parameters

The sample code supplied uses a configuration file to store some configuration data needed to connect to the Powersearch REST WebService. This data consist of: Service URL, returned data format (JSON or XML), IdM username and IdM password.

The class Settings stores in memory the values of the configuration file and it's used throuhgout the client application. Here is the XML configuration:

<!--?xml version="1.0" encoding="iso-8859-1"?-->
 
     
        https://idmp.gb.co.uk/idm-powersearch-rest/powersearch/global
        application/json
         
     
        myuser@mydomain.com
        myp@ssw0rd

Get started for free today

  • No credit card required
  • Cancel any time
  • 24/5 support
Get started