User Tools

Site Tools


web-integration:java-example

Java Integration Example

Example demostrates use of Web services for ADUCID (aka WSA) and Web integration API for ADUCID. Example is based on Servlet 3.0 specification and tested on Tomcat 9.0 application server.

Project Structure

Image below shows Java web application project structure:

Let's describe project files:

  • OpenCheckServlet.java - servlet running at /openCheck and processing authentication result
  • OpenServlet.java - servlet running at /open and starting authentication operation
  • ProxyServlet.java - servlet running at /proxy and checking authentication status
  • running.gif - picture representing running authentication
  • aducid-api.js - see Client API for Web Integration
  • jquery.min.js - required by aducid-api.js
  • web.xml - web application configuration file
  • index.jsp - page starting authentication operation
  • secure.jsp - page showing authentication result
  • build.bat - batch file generating WS classes and building web application
  • pom.xml - maven configuration file

Java Servlets

Use of Client API for Web Integration requires preparation of 3 servlets.

Open

First one starts authentication process:

@WebServlet("/open")
public class OpenServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        PrintWriter out = response.getWriter();

        // initialize client
        URL url = new URL(getServletContext().getInitParameter("wsUrl"));
        QName qname = new QName("http://impl.ws.sdk.aducid.com/", "AducidApiServiceImplService");
        Service service = Service.create(url, qname);
        AducidApiService client = service.getPort(AducidApiService.class);

        try {
            // generate unique browser tab identifier - necessary not to share session attributes
            String id = UUID.randomUUID().toString();

            // start operation
            RequestOperationArguments arguments = new RequestOperationArguments();
            arguments.setPeigReturnName(request.getRequestURL() + "Check?id=" + id); // required by iOS
            arguments.setGenerateQrCodePicture(true);
            arguments.setQrCodePictureWidth(300);
            arguments.setQrCodePictureHeight(300);
            RequestOperationResult result = client.startAuthenticationSession(arguments);
            result.setId(id);
            System.out.println("authId: " + result.getAuthId());

            // save authId with id prefix to session
            request.getSession().setAttribute(id + "_authId", result.getAuthId());

            // success - send JSON response to integration API
            out.print(client.toJson(result, null));
        } catch (AducidClientException exception) {
            // error - send JSON response to integration API
            out.print(client.toErrorJson(exception.getFaultInfo().getResult(), "index.jsp"));
        }

        out.flush();
        out.close();
    }

}
Some minor notes to source code:

  • way to get wsUrl is described in Web Application Configuration File chapter
  • code works with unique id, we can start authentication in more than one browser tab, then authId value in session would be overwritten by last tab authId value and authentication in previous tabs would stop working
  • value set in setPeigReturnName must be set to authentication result URL, here it is /openCheck with id query parameter

Proxy

This servlet asks for authentication operation status:

@WebServlet("/proxy")
public class ProxyServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        PrintWriter out = response.getWriter();

        // initialize client
        URL url = new URL(getServletContext().getInitParameter("wsUrl"));
        QName qname = new QName("http://impl.ws.sdk.aducid.com/", "AducidApiServiceImplService");
        Service service = Service.create(url, qname);
        AducidApiService client = service.getPort(AducidApiService.class);

        try {
            // read authId with id prefix from session
            String authId = (String) request.getSession().getAttribute(request.getParameter("id") + "_authId");

            // ask for operation status
            String status = client.getStatus(authId);
            System.out.println("status: " + status);

            // success - send JSON response to integration API
            out.print(client.toJson(status, null));
        } catch (AducidClientException exception) {
            // error - send JSON response to integration API
            out.print(client.toErrorJson(exception.getFaultInfo().getResult(), "index.jsp"));
        }

        out.flush();
        out.close();
    }

}

Notes to source code:

Open Check

Servlet evaluating authentication operation result:

@WebServlet("/openCheck")
public class OpenCheckServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        PrintWriter out = response.getWriter();

        // initialize client
        URL url = new URL(getServletContext().getInitParameter("wsUrl"));
        QName qname = new QName("http://impl.ws.sdk.aducid.com/", "AducidApiServiceImplService");
        Service service = Service.create(url, qname);
        AducidApiService client = service.getPort(AducidApiService.class);

        try {
            // read authId with id prefix from session
            String authId = (String) request.getSession().getAttribute(request.getParameter("id") + "_authId");

            // ask for operation result
            GetPSLAttributesResponse result = client.getResult(authId, request.getParameter("authKey"));
            System.out.println("status: " + result.getStatusAIM().name().toLowerCase());
            System.out.println("authentication: " + result.getStatusAuth());

            // save result to session
            request.getSession().setAttribute("result", result);

            // success - send JSON response to integration API
            out.print(client.toJson(null, "secure.jsp"));
        } catch (AducidClientException exception) {
            // error - send JSON response to integration API
            out.print(client.toErrorJson(exception.getFaultInfo().getResult(), "index.jsp"));
        }

        out.flush();
        out.close();
    }

}

Some notes to source code:

Web Integration

Start Page

Servlets described earlier are used in index.jsp page:

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">

<head>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/aducid-api.js"></script>

<script type="text/javascript">
	var aducid = new ADUCID();
	$(document).ready(function() {
		aducid.setAuthentication();

		aducid.setStartOperationUrl("open");
		aducid.setResultOperationUrl("openCheck");
		aducid.setProxyUrl("proxy");

		aducid.processResult = function(result) {
			if (result.status == "OK") {
				alert("Success - status: " + result.status);
				location.href = result.redirect;
			} else {
				alert("Error - status: " + result.status + ", message: " + result.data.message);
				location.href = result.redirect;
			}
		}

		// handle PEIG not installed error
		aducid.showPeigError = function() {
			alert("PEIG not found or other error");
		}

		// handle communication or other error
		aducid.handleError = function(e) {
			alert(e.data.message);
		}

		aducid.showQRHint = function(param) {
			$('#qr-code-hint').html("Scan QR or click button to authenticate");
		}

		aducid.showRunningHint = function(param) {
			$('#qr-code-hint').html("Operation is running");
		};
		
		aducid.startAnimation = function() {
            $("#qr-code").attr("src", "img/running.gif");
        };

        aducid.stopRunningAnimation = function() {
			$("#qr-code").hide();
		};

		// GUI mapping
		aducid.setButton($("#main-button"));
		aducid.setQrCode($("#qr-code"));
		aducid.setQrHint($("#qr-code-hint"));

		// start
		aducid.init();
	});
</script>
</head>
<body>

	<h1>LOGIN PAGE</h1>
	<div>
		<button id="main-button">Login using local PEIG</button>
	</div>
	<img id="qr-code" alt=""></img>
	<div id="qr-code-hint"></div>

</body>
</html>

Result Page

After successful authentication, UDI value is printed at result.jsp page:

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">

<head>
</head>
<body>

	<h1>SECURE PAGE</h1>
	UDI: ${result.userDatabaseIndex}
	<br></br>
	<a href="index.jsp">Try again</a>

</body>
</html>
</code>
===== Web Application Configuration File =====
This file is required by Servlet API. File provides ''wsUrl'' configuration value:

<code xml>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0">

    <display-name>Example WS</display-name>

    <context-param>
        <param-name>wsUrl</param-name>
        <param-value>${ws.url}/aducid-client-api-ws/wsa</param-value> 
    </context-param>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

Value ${ws.url} is replaced at application building phase. See Building Application chapter.

Maven Configuration File

Maven configuration file contents definition of plugin to generate WS classes and instruction to filter ${ws.url} value:

<?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.aducid</groupId>
    <version>1.DEV-SNAPSHOT</version>
    <packaging>war</packaging>
    <artifactId>example_ws</artifactId>
    <name>demo: example ws</name>
    <build>
        <finalName>example-ws</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <debug>true</debug>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.jvnet.jax-ws-commons</groupId>
                <artifactId>jaxws-maven-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <execution>
                        <id>client</id>
                        <configuration>
                            <wsdlUrls>
                                <wsdlUrl>${ws.url}/aducid-client-api-ws/wsa?wsdl</wsdlUrl>
                            </wsdlUrls>
                            <vmArgs>
                                <vmArg>-Djavax.xml.accessExternalSchema=all</vmArg>
                            </vmArgs>
                            <encoding>UTF-8</encoding>
                        </configuration>
                        <goals>
                            <goal>wsimport</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
                <configuration>
                    <webResources>
                        <resource>
                            <filtering>true</filtering>
                            <directory>src/main/webapp</directory>
                            <includes>
                                <include>WEB-INF/web.xml</include>
                            </includes>
                        </resource>
                        <resource>
                            <directory>${project.build.sourceDirectory}</directory>
                            <targetPath>sources</targetPath>
                        </resource>
                    </webResources>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

Building Application

There is prepared batch file build.bat to build application. It is neccessary to define right ws.url value as an address to AIM server:

set MAVEN_OPTS="-Xmx512m"
mvn -Dws.url=https://myaim.aducid.com -Dfile.encoding=UTF-8 clean install

web-integration/java-example.txt · Last modified: 2020/02/29 10:52 by mpospisek