com.hiperium.commons.client.soap.AthenticationDispatcherTest.java Source code

Java tutorial

Introduction

Here is the source code for com.hiperium.commons.client.soap.AthenticationDispatcherTest.java

Source

/**
 * Product  : Hiperium Project
 * Architect: Andres Solorzano.
 * Created  : 08-05-2009 - 23:30:00
 * 
 * The contents of this file are copyrighted by Andres Solorzano 
 * and it is protected by the license: "GPL V3." You can find a copy of this 
 * license at: http://www.hiperium.com/about/licence.html
 * 
 * Copyright 2014 Andres Solorzano. All rights reserved.
 * 
 */
package com.hiperium.commons.client.soap;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;

import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.hiperium.client.soap.authentication.AuthenticationObjectFactory;
import com.hiperium.client.soap.authentication.UserAuthentication;
import com.hiperium.client.soap.authentication.UserAuthenticationResponse;
import com.hiperium.client.soap.common.ClientHandlerResolver;
import com.hiperium.client.soap.general.GeneralObjectFactory;
import com.hiperium.commons.CommonsUtil;
import com.hiperium.commons.dto.HomeSelectionDTO;
import com.hiperium.commons.dto.UserCredentialDTO;
import com.hiperium.commons.log.HiperiumLogger;

/**
 * @author Andres Solorzano
 *
 */
public class AthenticationDispatcherTest {

    /** The property LOGGER. */
    private static final HiperiumLogger LOGGER = HiperiumLogger.getLogger(AthenticationDispatcherTest.class);

    /** The property CLIENT_APPLICATION_TOKEN registered in the Cloud. */
    private static final String CLIENT_APPLICATION_TOKEN = "abc123def";

    /** The property NAMESPACE. */
    private static final String AUTH_NAMESPACE = "https://authentication.soap.web.hiperium.com/";
    /** The property AUTH_SERVICE_URL. */
    private static final String AUTH_SERVICE_URL = "https://localhost:8443/cloud/web/service/soap/authentication/UserAuthenticationWS?wsdl";
    /** The property HOME_SELECTION_SERVICE_URL. */
    private static final String HOME_SELECTION_SERVICE_URL = "https://localhost:8443/cloud/web/service/soap/authentication/HomeSelectionWS?wsdl";

    /** The property NAMESPACE. */
    private static final String GENERAL_NAMESPACE = "https://general.soap.web.hiperium.com/";
    /** The property END_SESSION_SERVICE_URL. */
    private static final String END_SESSION_SERVICE_URL = "https://localhost:8443/cloud/web/service/soap/general/MenuWS?wsdl";

    /**
     * This class authenticates with the Hiperium Platform using JAXBContext and the selects user's home and
     * profile to access the system functions, and finally end the session. For all this lasts functions
     * we use SOAP messages with dispatchers and not JAXBContext.
     * 
     * We need to recall, that for JAXBContext we could not add a handler to add header security parameters that need
     * to be verified in every service call in the Hiperium Platform, and for that reason, we only use JAXBContext in
     * the authentication process that do not need this header validation in the SOAP message header.
     * 
     * @param args
     */
    public static void main(String[] args) {
        try {
            URL authURL = new URL(AUTH_SERVICE_URL);
            // The NAMESPACE must be http://authentication.soap.web.hiperium.com/ and must not begin
            // with http://SEI.authentication.soap.web.hiperium.com. Furthermore, the service name
            // and service port name must end WSService and WSPort respectively in order to call the service.
            QName authServiceQName = new QName(AUTH_NAMESPACE, "UserAuthenticationWSService");
            QName authPortQName = new QName(AUTH_NAMESPACE, "UserAuthenticationWSPort");
            // The parameter class must be annotated with @XmlRootElement in order to function
            JAXBContext jaxbContext = JAXBContext.newInstance(UserAuthentication.class,
                    UserAuthenticationResponse.class);
            Service authService = Service.create(authURL, authServiceQName);
            // When we use JAXBContext the dispatcher mode must be PAYLOAD and NOT MESSAGE mode
            Dispatch<Object> dispatch = authService.createDispatch(authPortQName, jaxbContext,
                    Service.Mode.PAYLOAD);
            UserCredentialDTO credentialsDTO = new UserCredentialDTO("andres_solorzano85@hotmail.com", "andres123");
            UserAuthentication authenticateRequest = new UserAuthentication();
            authenticateRequest.setArg0(credentialsDTO);
            UserAuthenticationResponse authenticateResponse = (UserAuthenticationResponse) dispatch
                    .invoke(authenticateRequest);
            String sessionId = authenticateResponse.getReturn();
            LOGGER.debug("SESSION ID: " + sessionId);

            // Verify if session ID exists
            if (StringUtils.isNotBlank(sessionId)) {
                // Select home and profile
                URL selectHomeURL = new URL(HOME_SELECTION_SERVICE_URL);
                Service selectHomeService = Service.create(selectHomeURL,
                        new QName(AUTH_NAMESPACE, "HomeSelectionWSService"));
                selectHomeService.setHandlerResolver(new ClientHandlerResolver(credentialsDTO.getEmail(),
                        CLIENT_APPLICATION_TOKEN, AuthenticationObjectFactory._SelectHome_QNAME));
                Dispatch<SOAPMessage> selectHomeDispatch = selectHomeService.createDispatch(
                        new QName(AUTH_NAMESPACE, "HomeSelectionWSPort"), SOAPMessage.class, Service.Mode.MESSAGE);
                CommonsUtil.addSessionHeaderParms(selectHomeDispatch, sessionId);
                HomeSelectionDTO homeSelectionDTO = new HomeSelectionDTO(1L, 1L);
                SOAPMessage response = selectHomeDispatch.invoke(createSelectHomeSOAPMessage(homeSelectionDTO));
                readSOAPMessageResponse(response);

                // End Session
                URL endSessionURL = new URL(END_SESSION_SERVICE_URL);
                QName endSessionServiceQName = new QName(GENERAL_NAMESPACE, "MenuWSService");
                QName endSessionPortQName = new QName(GENERAL_NAMESPACE, "MenuWSPort");
                Service endSessionService = Service.create(endSessionURL, endSessionServiceQName);
                endSessionService.setHandlerResolver(new ClientHandlerResolver(credentialsDTO.getEmail(),
                        CLIENT_APPLICATION_TOKEN, GeneralObjectFactory._EndSession_QNAME));
                Dispatch<SOAPMessage> endSessionDispatch = endSessionService.createDispatch(endSessionPortQName,
                        SOAPMessage.class, Service.Mode.MESSAGE);
                CommonsUtil.addSessionHeaderParms(endSessionDispatch, sessionId);
                response = endSessionDispatch.invoke(createEndSessionSOAPMessage());
                readSOAPMessageResponse(response);
            }
        } catch (MalformedURLException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (JAXBException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    /**
     * 
     * @param response
     */
    public static void readSOAPMessageResponse(SOAPMessage response) {
        SOAPBody authBodyResponse;
        try {
            authBodyResponse = response.getSOAPBody();
            Node authNode = authBodyResponse.getFirstChild();
            NodeList authNodeList = authNode.getChildNodes();
            String responseString = authNodeList.item(0).getFirstChild().getNodeValue();
            LOGGER.debug("RESPONSE: " + responseString);
        } catch (SOAPException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    /**
     * 
     * @return
     */
    public static SOAPMessage createAuthSOAPMessage(UserCredentialDTO dto) {
        SOAPMessage soapMessage = null;
        try {
            soapMessage = MessageFactory.newInstance().createMessage();
            SOAPPart soapPart = soapMessage.getSOAPPart();
            SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

            // Add message body parameters
            SOAPBody soapBody = soapEnvelope.getBody();
            SOAPElement method = soapBody.addChildElement("userAuthentication", "ns2",
                    "https://sei.authentication.soap.web.hiperium.com/");
            SOAPElement argument = method.addChildElement("arg0");
            argument.addChildElement("email").addTextNode(dto.getEmail());
            argument.addChildElement("password").addTextNode(dto.getPassword());

            // Check the input
            System.out.println("REQUEST:");
            soapMessage.writeTo(System.out);
            System.out.println();

        } catch (SOAPException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return soapMessage;
    }

    /**
     * 
     * @return
     */
    public static SOAPMessage createSelectHomeSOAPMessage(HomeSelectionDTO dto) {
        SOAPMessage soapMessage = null;
        try {
            soapMessage = MessageFactory.newInstance().createMessage();
            SOAPPart soapPart = soapMessage.getSOAPPart();
            SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

            // Add message body parameters
            SOAPBody soapBody = soapEnvelope.getBody();
            SOAPElement method = soapBody.addChildElement("selectHome", "ns2",
                    "https://sei.authentication.soap.web.hiperium.com/");
            SOAPElement argument = method.addChildElement("arg0");
            argument.addChildElement("homeId").addTextNode(dto.getHomeId().toString());
            argument.addChildElement("profileId").addTextNode(dto.getProfileId().toString());

            // Check the input
            System.out.println("REQUEST:");
            soapMessage.writeTo(System.out);
            System.out.println();

        } catch (SOAPException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return soapMessage;
    }

    /**
     * 
     * @return
     */
    public static SOAPMessage createEndSessionSOAPMessage() {
        SOAPMessage soapMessage = null;
        try {
            soapMessage = MessageFactory.newInstance().createMessage();
            SOAPPart soapPart = soapMessage.getSOAPPart();
            SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

            // Add message body parameters
            SOAPBody soapBody = soapEnvelope.getBody();
            soapBody.addChildElement("endSession", "ns2", "https://sei.general.soap.web.hiperium.com/");

            // Check the input
            System.out.println("REQUEST:");
            soapMessage.writeTo(System.out);
            System.out.println();

        } catch (SOAPException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return soapMessage;
    }

}