Click here to Skip to main content
15,878,852 members
Articles / Programming Languages / C++

Create a Web Service Client using GSoap Toolkit over HP-UX Server

Rate me:
Please Sign up or sign in to vote.
4.80/5 (6 votes)
6 Feb 2023CPOL4 min read 32K   16   2
Write a web service library for HP-UX server

Introduction

Sometimes, in our daily lives as developers, we have to integrate technology with different qualities. Sometimes, these products are expensive or some relative close to the business lines, for example, how to use an enterprise service overall the communication with legacy systems that is a tough question, so the first possibility to resolve this problem is using message queue or web service or any other component. There are many ways but the result should be measured and quantifiable for getting an approximation.

Background

I want to emphasize a scenario where you are using a HP-UX server you want to integrate with a web service, so typically, you have an interface that could be a WSDL, this legacy system can execute a library, by this way is a very fast solution but if you want to use XML on web service scenario to be communicated with a low-level system, you could use for instance a language like C (ANSI) or Python or cURL.

If you have using web service client generator like axis2 or wsdl.exe, you should be familiarized with this toolkit called GSoap which is really fast and reliable in many aspects, if you search on the internet, you will get something like:

"gSOAP is an open source C and C++ software development toolkit for SOAP/XML Web services and generic XML data bindings. ", Wikipedia

The interesting part of the toolkit is that you will get C ANSI code generated on your stub, essentially all GCC compilers will translate his code. The interesting part of the toolkit is that you will get C ANSI code generated on your stub, essentially all gcc compilers will translate his code.

Using the Code

1. Download GSOAP Toolkit

The first step is download GSoap Toolkit from the following site: http://sourceforge.net/projects/gsoap2/files/

The second step should be to install GSoap Toolkit, unzip gsoap_2.7.15.tar in a root directory for execution.

Example: C:/SOAP/ gsoap_2.7.15

There are two executable files that allow us to generate libraries for connecting to the Web Service:

  1. wsdl2h.exe
  2. soapcpp2.exe

a.1 Run wsdl2h.exe:

 wsdl2h -c -o Archivo.h http://127.0.0.1:8088/WebService01/services/Enviar?wsdl
 
-c Compilation in C
-o Output File Reference Archivo.h
   Generation Archivo.h library interface
   http://127.0.0.1:8088/WebService01/services/Enviar?wsdl Web Service

a.2 Run soapcpp2.exe:

soapcpp2-c-C-L Archivo.h
  -c Compilation in C
    Customer-C Files
  -L
  Generation Archivo.h library interface

2. Get WSDL File from Web Service Endpoint

GSoap can process the WSDL from the Web Service Endpoint only if the sitio does not have any kind of authetication that prevents direct access to web service. The most recommended option is directly get wsdl file from a web browser, taking care downloading the xsd files and change it form schemaLocation tag.

3. Generate Header File for the Stub

Generate the Header File 'ClinicService.wsdl' that has the necessary structures and procedures to generate the stub, it is important to note that the file will guide us to implement a web service client.

Example:

C:\SOAP\gsoap_2.7.15\gsoap\bin\win32>wsdl2h -c -o ClinicService.h D:\CODE\wsdl\clinic\ClinicService.wsdl

**  The gSOAP WSDL/Schema processor for C and C++, wsdl2h release 1.2.15
**  Copyright (C) 2000-2009 Robert van Engelen, Genivia Inc.
**  All Rights Reserved. This product is provided "as is", without any warranty.

**  The wsdl2h tool is released under one of the following two licenses:
**  GPL or the commercial license by Genivia Inc. Use option -l for more info.

Saving ClinicService.h

Cannot open file 'typemap.dat'
Problem reading type map file 'typemap.dat'.
Using internal type definitions for C instead.

Reading file 'D:\CODE\wsdl\clinic\ClinicService.wsdl'... done reading 
'D:\CODE\wsdl\clinic\ClinicService.wsdl'

To complete the process, compile with:
soapcpp2 ClinicService.h

If we open the file containing struct ClinicService.h, notice that they are related to the input parameters and return variables.

Example:

C++
struct _ns1__ejecutarServicio
{
    char*  tipoServicio   0;
    char*  parametro    0;
};

Another important point is that we handle struct for C (ANSI), if we had used the-c parameter in wsdlh.exe, would have generated code in C + +, and this does not benefit us in the HP-UX terminals.

4. Generate the Stub

With ClinicService.h header file, we can use the following executable:

C:\SOAP\gsoap_2.7.15\gsoap\bin\win32>soapcpp2 -c -C -L ClinicService.h

**  The gSOAP code generator for C and C++, soapcpp2 release 2.7.15
**  Copyright (C) 2000-2009, Robert van Engelen, Genivia Inc.
**  All Rights Reserved. This product is provided "as is", without any warranty.

**  The soapcpp2 tool is released under one of the following three licenses:
**  GPL, the gSOAP public license, or the commercial license by Genivia Inc.

Saving soapStub.h annotated copy of the input definitions
Saving soapH.h serializers
Saving soapC.c serializers
Saving soapClient.c client calling stubs
Using ns3 service name: ClinicServiceSoap11Binding
Using ns3 service style: document
Using ns3 service encoding: literal
Using ns3 service location: http://127.0.0.1:80/ClinicService/services/ClinicServiceHttpSoap11Endpoint/
Using ns3 schema namespace: http://clinic.com/ClinicServiceSoap11Binding

....

Compilation successful

If we observe the command line, are generated 4 files extension *.c

Files generated need the following:

  Archivo Definición
1. soapH.h Main Header File
2. soapC.c File with Data Structures
3. soapClient.c File with the implementation of the methods in C Web Service
4.

ClinicService Soap12Binding.nsmap 

ClinicServiceSoap11Binding.nsmap

Struct with corresponding namespaces Soap versions 1.1 and 1.2, this according to the version you wish to use.

5. Header File for the Library

We continue to write the library in first generating Header File (ClinicServiceWS.h).

C++
#if defined(__cplusplus)
    extern "C" {
#endif
#ifdef WIN32
    __declspec( dllexport )
#endif
void ejecutarServicio(char *endpoint, char *usuario, char *contrasenya,
char *tipoServicio, char *parametro, char *respuesta, char *error, char *llave);
#if defined(__cplusplus)
#endif

This file contains the public firm library SL / DLL.

6. Main File With the Implementation of the Library

We continue to write the call to the Web Service method according to this signature on file ClinicService.h:

C++
#include "soapH.h" // Archivo cabecera con las variables y procedimientos para enviar 
                   // y recibir mensajes SOAP
#include "ClinicServiceWS.h" // Archivo cabecera  con el procedimiento de la libreria SL/DLL
#include <stdio.h>
//No se empleo ClinicServiceSoap12Binding.nsmap directamente para descartar problemas 
//de lectura del tipo del archivo
/**
 * Namespace Web Service
 * Mapa Obtenido del Archivo <stdio.h>ClinicServiceSoap12Binding.nsmap
 * Se elige la version 1.2 para resolver la implementacion sobre la plataform NET 3.5 / WIN32
 */
struct Namespace namespaces[] =
{       //Namespaces autogenerados del WSDL
…
};
/*
….
*/
void ejecutarServicio(char *endpoint, char *usuario, 
  char *contrasenya,char *tipoServicio,char *parametro, char *respuesta, char *error)
{
 const char *mensaje=""; //variable temporal para almacenar mensajes
 //VERIFICANDO SI ENDPOINT NO ES NULO O SI NO ESTA VACIO
 if(!endpoint || strlen(endpoint)==0){
  ...
 }
 //VERIFICANDO SI USUARIO Y/O CONTRASENYA NO ES NULO O SI NO ESTAN VACIOS
 if(!(usuario&&contrasenya)|| strlen(usuario)==0|| strlen(contrasenya)==0){
  ...
 }
 //VERIFICANDO SI TIPO DE SERVICIO Y/O PARAMETRO DE SERVICIO NO ES NULO O SI NO ESTAN VACIOS
 if(!tipoServicio||!parametro|| strlen(tipoServicio)==0|| strlen(parametro)==0){
  ...
 }
 struct soap msoap;
 soap_init (&msoap); //inicializar el contexto del mensaje soap
 msoap.userid = usuario; //usuario para http-basic autenticacion
 msoap.passwd = contrasenya; //contrasenia para http-basic autenticacion
 msoap.send_timeout = 1500;  
 msoap.recv_timeout = 1500;
 soap_set_namespaces(&msoap, namespaces); // cargando namespaces en el mensaje soap
//verificar si el servicio web esta activo
 if ( soap_connect_command(&msoap, SOAP_GET, endpoint,"") || 
      soap_end_send(&msoap) ) { //abrimos y cerramos una conexión temporal
    ...
 }
 struct _ns1__ejecutarServicio inputMensaje; // struct mensaje SOAP de entrada
 struct _ns1__ejecutarServicioResponse responseMensaje; // struct mensaje SOAP de respuesta
 inputMensaje.tipoServicio = tipoServicio; 
 inputMensaje.parametro = parametro; 
 int temporal_respuesta=-1; // valor obtenido del procedimiento del mensaje soap
 /*
 * Procedimiento declarado en soapClient.cpp
 * @param (1) msoap; mensaje SOAP inicializado para el envio del mensaje
 * @param (2) endpoint: URL del Servicio Web
 * @param (3) action: Accion a tomar en el Servicio Web
 * @param (4) inputMensaje: SOAP struct entrada
 * @param (5) responseMensaje: SOAP struct respuesta 
 */
 temporal_respuesta=soap_call___ns4__ejecutarServicio(&msoap,
         endpoint, 0, &inputMensaje, &responseMensaje);
  if(!msoap.status){
       ...
  }
  //Variable SOAP_OK, se localiza en el archivo strsoap2.h
  //Evalua que el mensaje llego correctamente
  if(temporal_respuesta==SOAP_OK)
    {
      if(!responseMensaje.return_){ //SI EL MENSAJE ES NULO LA RESPUESTA ES UN MENSAJE VACIO
        ...
      }else{ //Respuesta recibida exitosamente
        ...
	  }
	  error=NULL;
    }else if(temporal_respuesta==12){
    // Consultar archivo stdsoap2.h para obtener mas detalle del error obtenido
           ...
    }else if(temporal_respuesta==404){
           ...
    }else if(temporal_respuesta==401){
           ...
    }else{
           ...
    }
     soap_end(&msoap);
     soap_done(&msoap);
     soap_free(&msoap); //liberar recursos del mensaje SOAP
}

7. Compilation Shell

The next thing is to compile the component on a HP-UX Terminal, so we need to ask the following fact:

When HP-UX compile, our programs must be generated in 64bit for other programs running on the server can open the library and their corresponding links, the common misconception regarding compilation this program is on the library dld.sl.

Finally, this is shell you could run on HP-UX Terminal, the reason is to compile all your source and get a library with *.sl extension.

Bash
#!/bin/sh
#******************************************************************************
#* Archivo:      compilarClinicServiceLib.sh                                   *
#*                                                                            *
#* Autor:        Sanchez Huerta Octavio 
#* F. Creación:  17/may/2010                                                  *
#* Plataforma:   HP-UX 11.1                                                   *
#******************************************************************************
#*                                                                            *
#* Shell de compilacion para la ClinicService                                  *
#*                                                                            *
#*****************************************************************************/
 
echo 0 Proceso Inicio  
date #Mostrando Fecha de Inicio
echo 1 Asignando Permisos
#Permisos para compilar los archivos
chmod 755 *

echo 2 ClinicServiceLIB CONFIGURANDO
#Renombrando archivos de compilacion, por cambio de nombre al momento de la tranferencia
mv soapc.c soapC.c
mv soaph.h soapH.h
mv soapstub.h soapStub.h
mv wsbup.h WSBup.h
mv wsbupmain.c WSBupMain.c
echo 3 ClinicService LIB BORRANDO ARCHIVO O Y SL
#removiendo archivos objecto y librerias sl en caso anteriores
rm -f *.o
rm -f *.sl

echo PASO 4 ClinicSERVICELIB COMPILANDO WS Clinic
#IMPORTANTE(!): Compilacion en 64bits, flag de nonamespaces debido a que no empleamos el archivo *.nsmap
cc +z +DD64 -c -DWITH_NONAMESPACES WSBupLib.c soapC.c soapClient.c stdsoap2.c

echo PASO 5 ClinicSERVICELIB COMPILANDO LIBRERIA
#Cargando Librerias OpenSSL a la libreria
cc -b -o libClinicServiceHTTP.sl ClinicServiceLib.o soapC.o 
   soapClient.o stdsoap2.o -I/usr/lib/pa20_64 -L/usr/lib/pa20_64 -lxnet -lnsl -ldl -lpthread

echo PASO 6 ClinicSERVICELIB GENERANDO PROGRAMA PRUEBA
#Programa de prueba
cc +DD64 -o ClinicServiceMain ClinicServiceMain.c -L. -libClinicServiceHTTP

echo PASO 7 ClinicSERVICELIB REMOVIENDO ARCHIVOS OBJETO
rm -f *.o

echo PASO 8 FINALIZO
date #Mostrando Fecha de Fin

An important point during compilation is to include operating system libraries needed for compilation as in the case of lxnet, lnsl, ldl, lpthread.

Points of Interest

We can create web service clients running as a C++ library for a system that works under low-level, we essentially create a stub of web service interface to communicate under TCP with web service deployed in any technology.

History

  • 14/07/2013: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Banco Monex
Mexico Mexico
My interest is in academic research and trying to keep me in the field to obtain a PhD degree, welling on the way to combine a job in a company with the activity I enjoy.

Comments and Discussions

 
QuestionHTTP POST Pin
soho15-Jul-13 3:15
soho15-Jul-13 3:15 
AnswerRe: HTTP POST Pin
Octavio Sanchez Huerta15-Jul-13 7:24
professionalOctavio Sanchez Huerta15-Jul-13 7:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.