Sunteți pe pagina 1din 70

Extensible Messaging Gateway

– Enhanced Services

Technical Report

Elsa Estevez
Vincent Douwe
Tomasz Janowski

type Technical Report

date 14 April 2009

version 1.0

location www.egov.iist.unu.edu/outputs

UNU-IIST Center for Electronic Governance www.egov.iist.unu.edu


UNU-IIST Center for Electronic Governance

Identity: An International Center of


Excellence on research and practice
in Electronic Governance, part of
United Nations University - Interna-
tional Institute for Software Tech-
nology, located in Macao, China.

Mission: To support govern-


ments in developing countries
in strategic use of technology
to transform the working of
public organizations and their
relationships with citizens,
businesses, civil society, and
with one another.

Activities: Applied and policy research,


capacity building, and various forms of
development – strategy development,
software development, institutional
development and development of com-
munities of practice.

Copyright © 2009, UNU-IIST Center for Electronic Governance


SUMMARY i

SUMMARY guages mostly used by applications deployed in Macao


Government agencies, presents new APIs for invoking
This document provides technical documentation about the Gateway services by applications developed in Del-
enhanced functionality and new APIs for the Extensible phi, and explains the use of two executable files for
Messaging Gateway. The enhanced functionality com- sending and receiving messages that can be invoked by
prises a new release of the Encryption/Decryption ex- any legacy application able to access the command line.
tension using certificates issued by Macao Post Office Fourth, it enumerates the deployment components and
(DSC) and modified versions of existing components explains the procedure for their deployment. Fifth,
supporting the new extension. The new APIs enables some conclusions are drawn. Finally, technical artifacts –
applications developed in Delphi and any other pro- like Java classes used by the Encryption extension, de-
gramming language able to access the command line to tailed and summarized lists of government applications
invoke the Gateway services. The document first and programming languages used by government agen-
presents the scope of the Macao Data Exchange Gate- cies, Delphi APIs, Java classes for sending and receiving
way Project and the motivation for producing the deli- messages through the command line, and the new Ga-
verables presented in this report. Second, it specifies in teway configuration file; are included in the appendices.
detail the new extension for encrypting and decrypting
messages. Third, it introduces the programming lan- This work was partly funded by Macao Foundation un-
der the e-Macao Program (www.emacao.gov.mo).

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


TABLE OF CONTENTS ii

TABLE OF CONTENTS

Summary .................................................................................................................................................................................... i
Table of Contents ...................................................................................................................................................................... ii
List of Tables............................................................................................................................................................................. iii
List of Figures ........................................................................................................................................................................... iii
Abbreviations ........................................................................................................................................................................... iv
Revisions .................................................................................................................................................................................. iv
1. Introduction .......................................................................................................................................................................... 1
2. Encrypting and Decrypting Messages.................................................................................................................................... 2
2.1. Enabling Encryption/Decryption Extension .................................................................................................................. 3
2.2. Setting the PIN ............................................................................................................................................................... 4
2.3. Configuring Encryption/Decryption Extension ............................................................................................................. 4
2.4. Disabling the Encrytion/Decryption Extension ............................................................................................................. 7
2.5. Sending an Encrypted Message ..................................................................................................................................... 8
2.6. Receiving an Encrypted Message .................................................................................................................................. 9
3. New APIs for Legacy Systems .............................................................................................................................................. 10
3.1. Programming Languages used by Macao Government Agencies ............................................................................... 10
3.2. APIs for Delphi ............................................................................................................................................................. 11
3.3. APIs for Sending and Receiving Messages from the Command Line .......................................................................... 13
4. Deployment Components and Procedure .......................................................................................................................... 16
4.1. Deployment Components ............................................................................................................................................ 16
4.2. Deployment Procedure................................................................................................................................................ 17
5. Conclusions ......................................................................................................................................................................... 19
References............................................................................................................................................................................... 20
Appendices .............................................................................................................................................................................. 21
A. Java Classes Used by the Encryption Extension .............................................................................................................. 21
B. Delphi APIs...................................................................................................................................................................... 31
C. Programming Languages and Tools Used by Government Applications ........................................................................ 51
D. Java Classes for Sending and Receiving Messages through the Command Line ............................................................ 60
E. Gateway Configuration File ............................................................................................................................................ 63

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


LIST OF TABLES AND FIGURES iii

LIST OF TABLES

Table 1: Encrypting and Decrypting Messages using RSA and AES ............................................................................................ 2
Table 2: Programming Languages and Tools Mostly Used by Government Applications........................................................ 10

LIST OF FIGURES

Figure 1: Smart Card Issued by Macao Post and Smart Card Reader ........................................................................................ 2
Figure 2: Enabling Encryption/Decryption Extension ................................................................................................................ 3
Figure 3: Setting the PIN ............................................................................................................................................................ 4
Figure 4: User Interface for Setting the PIN .............................................................................................................................. 5
Figure 5: Configuring Encryption/Decryption – Owner’s Side ................................................................................................... 5
Figure 6: Configuring Encryption/Decryption – Subscriber’s Side ............................................................................................. 6
Figure 7: Disabling Encryption/Decryption – Owner s’ Side ...................................................................................................... 7
Figure 8: Disabling Encryption/Decryption – Subscriber’s Side ................................................................................................. 7
Figure 9: Sending an Encrypted Message .................................................................................................................................. 8
Figure 10: Receiving an Encrypted Message ............................................................................................................................. 9
Figure 11: Send Class - Main Method ...................................................................................................................................... 14
Figure 12: Receive Class - Main Method ................................................................................................................................. 15
Figure 13: Extensible Message Gateway – Deployment Folders ............................................................................................. 16
Figure 14: Folder Structure for Receiving and Sending Messages through the Command Line .............................................. 18

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


ABBREVIATIONS AND REVISIONS iv

ABBREVIATIONS

AES Advanced Encryption Standard


API Application Programming Interface
DSC Macao Post
EPS Electronic Public Service
RSA Encryption method proposed by R.L. Rivest, A. Shamir and L. Adleman
SAFP Public Administration and Civil Service Bureau
UNU United Nations University
UNU-IIST UNU International Institute for Software Technology
UNU-IIST-EGOV Center for Electronic Governance at UNU-IIST
XML eXtensible Markup Language

REVISIONS

DATE RESPONSIBLE SCOPE VERSION


13/02/2009 Elsa Estevez First draft version 0.95
28/02/2008 Vincent Douwe Second draft 0.96
04/03/2008 Elsa Estevez Second draft revised 0.98
14/04/2009 Tomasz Janowski Final version 1.0

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 1 – INTRODUCTION 1

1. INTRODUCTION rages the strengths of the two solutions to support inte-


gration of back-office applications, e-document ex-
The provision of Electronic Public Services (EPS) in terms change and multi-channel service delivery. For discuss-
of number, maturity and accessibility is central for mea- ing the integration of the Extensible Message Gateway
suring the progress of Electronic Government develop- and e-DocX Service, a meeting was held between SAFP,
ment. However, the rapid provision of mature EPS can- DSC and UNU-IIST representatives. As a result, it was
not be achieved following a case-by-case approach as it concluded that it would be simpler for government
requires the availability of pre-existing components, agencies to use both tools independently of the other,
tools and artifacts that can be used for rapid develop- based on specific needs. Following, the objectives of the
ment, deployment and reliable delivery. These compo- Macao Data Exchange Gateway Project were revised
nents, tools and artifacts constitute the so-called Soft- producing the following:
ware Infrastructure for Electronic Government. Such
infrastructure includes design-time artifacts – like ready- o1) In order to facilitate the use of the Messaging Ga-
to-customize domain models, guidelines and implemen- teway by Macao Government Agencies, UNU will
tation frameworks that can be used for accelerating EPS provide APIs for being able to invoke the Message
development; as well as run-time components and ser- Gateway services by software applications running
vices supporting or realizing common software functio- on the IT platforms most commonly used by Macao
nality required for the efficient and reliable delivery of Government.
services – like submission of citizen data through elec-
tronic forms, notifications to applicants, and message o2) The encryption-decryption extension of the Mes-
exchange between software applications. The availabili- saging Gateway will be re-implemented using the
ty of such infrastructure is one of the major facilitators certificates provided by Macao Post Office.
for scaling up, rapidly and efficiently, the provision of
EPS. o3) In order to facilitate the testing of the Messaging
Gateway by SAFP, UNU will submit the Message
In addition to the motivation explained above, main Gateway Quality Assurance report.
benefits that can be gained by delivering such infrastruc-
ture for Electronic Government include: providing stan- o4) To develop a pilot e-service enabling the manage-
dardized services to all agencies based on common ment of customer queues by government agencies.
technical standards; reducing the costs of developing
EPS by individual agencies; promoting the adoption of For achieving the former two objectives, a new release
standards across government; establishing a platform of the Gateway was delivered including new APIs and
for collaboration between agencies and between public enhanced services. This report constitutes the technical
and private sector on EPS and infrastructure develop- documentation of the new functionality and APIs pro-
ment; facilitating the creation of cross-agency EPS; and vided by the Gateway. For fulfilling the third objective,
enabling the integration of applications built with differ- the Extensible Messaging Gateway – Quality Assurance
ent technologies. Report [1] was delivered to SAFP. For achieving the last
objective, two services were developed – Appointment
Based on the motivation and prospective benefits of and Queuing. Therefore, in addition to the new release
providing software infrastructure, the Software Infra- of the Gateway - binary and source code; and this tech-
structure for Electronic Government Project was defined nical report, the deliverables of the Macao Data Ex-
by the UNU-IIST Center for Electronic Governance to be change Gateway Project for 2008 include the software
executed as part of the e-Macao Program during 2007. (source and binary codes) of the e-Appointment and e-
The Message Exchange Gateway (Gateway), a major Queuing services, and four technical reports – develop-
infrastructure service, was delivered by this project. The ment report and user manual for each service
Gateway enables asynchronous exchange of messages [2][3][4][5].
among registered members (e.g. software applications
or human users) through dynamically created and sub- The rest of this document is structured as follows. Sec-
scribed channels. It comprises a core framework sup- tion 2 explains the new extension for encrypting and
porting plain exchange of messages, and various exten- decrypting messages using certificates issued by Macao
sions providing enhanced functionality - such as mes- Post Office. Section 3 presents the motivation for devel-
sage logging, validation, transformation, encryp- oping the new APIs for legacy systems as well as tech-
tion/decryption, mediation, and resource discovery, nical documentation. Section 4 enumerates the deploy-
enabled on the platform. ment components and the procedure for their deploy-
ment. Section 5 draws some conclusions. Finally, a set of
In 2008, the Macao Data Exchange Gateway Project was appendices include the Java classes used by the Encryp-
carried out by UNU-IIST Center for Electronic Gover- tion extension, detailed and summarized lists of gov-
nance. The project aim was to develop a unified mes- ernment applications and programming languages used
sage infrastructure based on the UNU’s Extensible Mes- by government agencies, Delphi APIs, Java classes for
sage Gateway and DSC’s e-DocX Service – Unified Macao sending and receiving messages through the command
Government Message Gateway. This integration leve- line, and the new configuration file.

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES 2

2. ENCRYPTING AND DECRYPTING MESSAGES Figure 1: Smart Card Issued by Macao Post and Smart
Card Reader
Encryption/Decryption is one of the extensions provided
by the first release of the Extensible Messaging Gate-
way. The extension enables encoding of message con-
tents while messages are exchanged by members
through channels. In the first release, the extension
encoded messages using the RSA [6] method. The me-
thod, proposed by R.L. Rivest, A. Shamir and L. Adleman,
implements a private-public key cryptosystem enabling
exchange of ciphered messages without need to com-
municate keys along with the message. The RSA method
implemented by the Gateway extension assigned to the
Gateway Administrator – Admin member, the responsi-
bility for generating the pairs of private-public keys for
each member. Although the approach successfully
showed the behavior of the Encryption/Decryption ex-
tension, the use of these auto-generated keys should be
reviewed before adopting the Gateway in real e-
Government solutions. Following the encryption approach suggested by
eSignTrust, the new release of the Gateway extension
One of the revised objectives of the Macao Data Ex- encodes message contents using a hybrid combination
change Gateway Project for 2008 was to replace the of RSA, the method used by the first release of the Ga-
private-public keys generated by the Gateway Adminis- teway, and Advanced Encryption Standard (AES) [7]
trator, by the certificates issued by Macao Post Office. In method. The AES algorithm is a symmetric block cipher
support of the EDS Law no. 5/2005 promoting the use of for encrypting and decrypting information. The ap-
new technologies for assuring secure electronic transac- proach implemented by the Gateway extension is as
tions over open communication networks, Macao Post follows. The message content (c) and a randomly gener-
established eSignTrust – a Certification Service Provider ated key (k) are encrypted using AES, producing an en-
[8]. Among other tasks, eSignTrust is responsible for crypted content (c’). If the message is sent by a channel
issuing encipherment certificates which can be used for subscriber, the generated key (k) is encrypted with the
encrypting and decrypting data, sending encrypted mes- public key of the channel owner (PuK) using the RSA
sages, decrypting messages, and acknowledging the method producing an encoded key (k’). If the message is
receipt of an encrypted message using digital signature. sent by the channel owner, the generated key (k) is en-
Encipherment certificates and their public and private crypted with the channel owner’s private key (PrK). Fi-
keys are stored in smart cards, which can be read nally, the encoded content (c’) and the encrypted key
through a wide range of industry smart card readers, (k’) are sent. For decrypting the message, first the en-
and are also available through their website. Figure 1 crypted key (k’) is decrypted following the RSA method,
shows an example of smart card and smart card reader. and the generated key (k) is obtained.

Table 1: Encrypting and Decrypting Messages using RSA and AES

SENDER RECEIVER

NO ACTION NO ACTION

1 k = generateKey 1 If subscriber decryptRSA(k’, Puk) = k


encryptAES(c, k) = c’
If owner decryptRSA(k’, PrK) = k

2 If subscriber encryptRSA(k, PuK) = k’ 2 decryptAES(c’, k) = c

If owner encryptRSA(k, PrK) = k’

3 send(k’, c’) 3 receive(c)

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES 3

If the message recipient is a channel subscriber, the e) Sending an Encrypted Message – messages sent
encrypted key (k’) is decrypted using the channel own- through a channel having the Encryp-
er’s public key (PuK); while, if the recipient is the chan- tion/Decryption extension enabled and configured
nel owner, it is decrypted using its private key (PrK). are encrypted using the procedure defined in Table
Second, the encrypted message (c’) is decrypted using 1.
the generated key (k) following the AES method, pro-
ducing the plain message (c). Finally, the plain text of f) Receiving an Encrypted Message – messages re-
the message (c) is received by the recipient application. ceived through a channel having the Encryp-
Table 1 summarizes this process. tion/Decryption extension enabled and configured
are decrypted using the procedure defined in Table
Based on the motivations explained above, a new re- 1.
lease of the Encryption/Decryption extension using the
certificates issued by eSignTrust is provided. The exten- The following sections explain technical details for
sion provides the following services: enabling the extension (Section 2.1), setting the pin
(Section 2.2), configuring (Section 2.2) and disabling
a) Enabling Encryption/Decryption – after enabling the (Section 2.3) the extension, and for sending (Section 2.4)
extension for a channel, all messages sent through and receiving (Section 2.5) messages using the new ex-
the channel will be encrypted by the sender and tension release. The source code of the Java classes
decrypted by the recipients using the public and used by the extension is included in Appendix A.
private keys of the channel owner.
2.1. ENABLING ENCRYPTION/DECRYPTION
b) Setting Pin – enables to define the Personal Identi- EXTENSION
fication Number (PIN) for the member to access the
smart card for reading the private/public keys. The Encryption/Decryption extension is a channel-
oriented extension. In the new release, no changes were
c) Configuring Encryption/Decryption – involves dis- introduced for enabling a channel-oriented extension.
tributing the public key of the channel owner The process is depicted in Figure 2 and explained as
among channel subscribers. follows. The External Application requests the member
acting on its behalf to enable the extension
d) Disabling Encryption/Decryption – after disabling (1:enableExtension). The member prepares the
the extension, messages sent through the channel message to be sent to the Gateway administrator
are exchanged in plain text – they are no longer en-
crypted.

Figure 2: Enabling Encryption/Decryption Extension

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES 4

(2:msgToAdminExtension) and sends the message Figure 3 presents the sequence diagram explaining the
(3:sendMessage). The Admin member receives the implementation of the setPin operation. The external
message (4:receiveMessage) and pushes it to the application requires its member to set the PIN
application listener of the Gateway Administrator (1:setPin). The member invokes the function for
(5:receiveMessage). The administrator processes setting the PIN provided by the ExtensionsUtil
the request (6:requestExtension), which includes class (2:setPin). The utility class encrypts the PIN and
creating a new object for enabling the extension on the the member identifier using the AES method
Administrator’s side (7:create), setting the extension (3:encryptWithAES), and stores the PIN in a file
parameters (8:setParameters) – like the channel (4:storeToFile). The file is stored in the folder indi-
identifier for which the extension is enabled, storing the cated by the WorkFolder parameter of the Gateway
new enabled extension in the database configuration file. The file name starts with “PIN-“
(9:storeExtension) and replying to the member followed by the member identification, and ends with
(10:sendMessage). Upon receiving the reply mes- “.xg2g”.
sage (11:receiveMessage), the member requests
the channel owner to enable the extension In addition to the Gateway libraries, the user interface
(12:configureExtension). The channel forwards was modified to include the service for setting the PIN.
the request to the object managing all channel-oriented The interface is shown in Figure 4. The option for re-
extensions (13:configureExtension). Finally, the questing the service is at the bottom of the Exten-
member replies the result to the external application sion Menu on the left. Once selected, a window re-
(14:recChExtensionReply). In the figure, the four questing to introduce the PIN number and to confirm
objects on the left – depicted in green, are located at (Set button) is presented to the user. In the figure,
the member’s node, while the three objects on the right these features are highlighted by the ellipsis in red.
– depicted in orange are located at the Gateway admin-
istrator’s node. 2.3. CONFIGURING ENCRYPTION/DECRYPTION
EXTENSION
2.2. SETTING THE PIN
Configuring the Encryption/Decryption extensions re-
Configuring the Encryption/Decryption extension implies quires reading the channel owner’s public key stored in
distributing the public key of the channel owner to the smart card and distributing it to channel subscribers.
channel subscribers. The public and private keys issued The process is explained in two parts: i) from the chan-
by eSignTrust and used by the EncryptionDecryption nel owner’s side, and ii) from the channel subscriber’s
extension are stored in smart cards. For accessing a side.
smart card through the card reader, a PIN – Personal
Identification Number is requested. The PIN is given to Figure 5 shows the process for configuring the extension
the card holder upon issuance of the smart card. There- from the owner’s side. ExternalApplication re-
fore, if a member – owner of a channel, is willing to quests the member to configure the extension
enable the Encryption/Decryption extension on its (1:configureExtension). Five parameters are
owned channel, it needs to know its PIN to be able to required for configuring the extension. The parameters
access the public and private keys stored on the smart and their corresponding values are as follows:
card. A new operation was added to the IMember in-
terface – setPin, for addressing this need. The Mem- i) extension type – the value must be “channel”,
ber class implements this operation. since Encryption is a channel-oriented extension;

Figure 3: Setting the PIN ii) channel identifier – id of the channel for which the
extension is configured;

iii) extension name – the value must be “Message


Encryption”;

iv) parameter data – the value must be null, since the


data used for configuring the extension is the pub-
lic key of the channel owner which is read from the
smart card; and

v) parameter order – the value must be “1”, although


no data is used.

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES 5

Figure 4: User Interface for Setting the PIN

Figure 5: Configuring Encryption/Decryption – Owner’s Side

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES 6

Following the configuration request, Member asks Ex- database (10:storeParam). Finally, the Encryp-
tensionsUtil to get the public and private keys tion object requests the member to forward its public
from the smart card (2:getKeys). To fulfill the re- key to all subscribers
quest, ExtensionsUtil gets the configuration file (11:forwardToAllSubscribers). Member for-
where details of the smart card reader are stored, reads wards this message to all channel subscribers
the keys from the smart card, and returns the pair of (12:forwardMessage). And finally, the recConfigu-
keys (3:pair) to the member. Member prepares a reChExtension of the ApplicationListener is invoked.
message to the Administrator
(4:msgToAdminConfigure) and invokes the opera- Figure 6 presents the process for configuring the exten-
tion for configuring the extension in the owned channel sion on the subscriber’s side. Upon receiving the mes-
object (5:configureExtension). In this particular sage (1:receive), the member identifies the message
case, the message prepared to the Administrator is used was received by a subscribed channel and invokes the
but not really sent since all parameters required to con- method of this class (2:receive). Since it is a for-
figure the extension are locally available on the smart warded message, it is passed to the member for
card. Following the request from Member, Owned- processing (3:recForwardReply). After identifying
Channel requests ChAllExtMgr to configure the the type of message, the member’s enableSubsEx-
extension (6:configureExtension). ChAl- tension method is invoked
lExtMgr invokes its method for getting the object for (4:enableSubsExtension). The method requests
the specific extension (7:getExtension). Following to the ChExtensionParam class to add the parame-
the request, an instance of Encryption is returned, and ter received – the channel owner’s public key (5:add),
ChAllExtMgr invokes the configureExtension and to the ChExtManager to store the parameter in
operation in this object (8:configureExtension). the database (6:store). After storing the parameter,
For fulfilling the request, the Encryption object re- the member requests the subscribed channel to enable
quests its super class (ChAllExtension) to configure the extension (7:enableExtension). The channel
the extension (9:configureExtension). This me- forwards the message to the ChAllExtMgr
thod request the object managing the extension para- (8:enableExtension), which creates an instance of
meters in the databae – ChExtParamManager, to the Encryption object (9:get) and adds it as an exten-
store the configuration parameters – public key – in the sion of the channel (10:put).

Figure 6: Configuring Encryption/Decryption – Subscriber’s Side

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES 7

2.4. DISABLING THE ENCRYTION/DECRYPTION prepares the message to be sent to the Gateway admin-
EXTENSION istrator (3:msgToAdminExtension) and sends the
message (4:send). The Admin member receives the
Disabling the Encryption/Decryption extension requires message (5:receiveMessage) and pushes the mes-
some processing at the channel owner’s side and also at sage to the Admin application (6:receiveMessage).
the subscribers’ side. The administrator processes the request
(7:removeExtension), which includes removing
Figure 7 shows the process executed at the owner’s side data about the disabled channel extension in the data-
including the one executed by the Administrator’s side. base (8:removeExtension) and replying to the
The External Application requests its member to disable member confirming the extension was disabled
the extension (1:disableExtension). The member (9:sendMessage). Upon receiving the reply message
identifies it as a channel-oriented extension and invokes (10:receiveMessage), and identifying the message
the method for disabling this type of extension type, the Administrator’s reply is processed
(2:disableChannelExtension). This method (11:disableChExtension).

Figure 7: Disabling Encryption/Decryption – Owner s’ Side

Figure 8: Disabling Encryption/Decryption – Subscriber’s Side

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES 8

The request for disabling the extension is forwarded to tabase (5:remove), and requesting the subscribed
the channel owned (12:disableExtension), who channel to disable the extension
passes the request to the ChAllExtMgr (6:disableExtension). The subscribed channel
(13:disableExtension). ChAllExtMgr requests forwards the message to the ChAllExtMgr
the ChannelExtensionManager to remove the (7:disableExtension), which deletes the Encryp-
extension (14:removeExtension). Removing the tion/Decryption extension from the array of extensions
extension comprises removing the channel extension- enabled for the channel.
related information from the database and from the
array of channel extensions. Finally, a message is sent 2.5. SENDING AN ENCRYPTED MESSAGE
to all channel subscribers
(15:forwardToAllSubscribers) requesting to The process for sending a message is the same as in the
disable the extension. first release. The difference is only in the process-
Message method of the Encryption class.
Figure 8 presents the process for disabling the extension
on the subscriber’s side. Upon receiving the message Figure 9 presents the sequence diagram for sending an
(1:receiveMessage), the member identifies the encrypted message. The channel – may be owned or
message was received by a subscribed channel and in- subscribed, requests the ChAllExtMgr to process the
vokes the method of this class (2:receiveMessage). outgoing messages
Since it is a forwarded message, it is passed to the (1:processOutgoingMessage). This method looks
member for processing (3:recForwardReply). After for the corresponding extension – Encryption, and
identifying the type of message, the member’s method requests the object to process the message
for disabling the extension is invoked (2:processMessage). First, the extension gets the
(4:disableSubsExtension). The later method encryption key (key); if the sender is the channel own-
comprises requesting the ChannelExtensionMa- er, by getting its private key (3:getPrivateKey);
nager to remove the channel extension from the da-

Figure 9: Sending an Encrypted Message

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES 9

otherwise, by getting the public key of the channel subscribed, requests the ChAllExtMgr to process the
owner (4:getPublicKey). Second, it requests the incoming messages
ExtensionsUtil class to encrypt the message pro- (1:processIncomingMessage). This method looks
viding the message content (content) and the encryp- for the corresponding extension – Encryption, and
tion key (key). For encrypting the message, Exten- requests the object to process the message
sionsUtil executes the following: i) generates an (2:processMessage). First, the extension gets the
AES session key (6:createAESKey) – generated- encryption key (key); if the sender is the channel own-
Key; ii) encrypts, using the AES algorithm, the message er, by getting its private key (3:getPrivateKey);
content (content) using generatedKey otherwise, by getting the public key of the channel
(7:encryptAES); iii) encrypts, following the RSA me- owner (4:getPublicKey). Second, it requests the
thod, generatedKey using the encryption key – key ExtensionsUtil class to decrypt the message pro-
(8:encryptRSA); and builds the reply by returning viding the encrypted message (encMsg) and the en-
the encrypted generated key – the result of 8, and the cryption key (key). For decrypting the message, Ex-
encrypted content – the result of 7. Finally, the en- tensionsUtil executes the following: i) gets the
crypted message is returned to the channel encrypted generated key (encKey) from the encrypted
(10,11,12:encryptedMsg). message (6:getEncryptedKey); ii) gets the en-
crypted content (encContent) from the encrypted
2.6. RECEIVING AN ENCRYPTED MESSAGE message (7:getEncryptedContent); iii) decrypts,
following the RSA method, the encrypted generated key
The process for receiving a message is the same as in (encKey – obtained in 6) using the encryption key –
the previous release. The difference is only in the pro- key (8:decryptRSA); and iv) decrypts, following
cessIncomingMessage method of the Encryp- the AES method, the encrypted content – the result of 7,
tion class. using the decrypted generated key – the result of 8
(9:decryptAES). Finally, the decrypted message is
Figure 10 presents the sequence diagram for receiving returned to the channel
an encrypted message. The channel – may be owned or (10,11,12:decryptedMsg).

Figure 10: Receiving an Encrypted Message

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 3 – NEW APIS FOR LEGACY SYSTEMS 10

3. NEW APIS FOR LEGACY SYSTEMS mostly used by Macao SAR Government Agencies (Sec-
tion 3.1), the set of APIs developed for Delphi applica-
One of the revised objectives of the Macao Data Ex- tions (Section 3.2), and the executable files and Java
change Gateway Project was to provide APIs for invok- classes for sending and receiving messages through the
ing the Gateway services by non-Java applications. For command line (Section 3.3).
specifying the required APIs, programming languages
and tools used by legacy applications deployed in Gov- 3.1. PROGRAMMING LANGUAGES USED BY
ernment Agencies were retrieved from the survey car- MACAO GOVERNMENT AGENCIES
ried out as part of e-Macao Phase I [10]. The results
shown Delphi, Visual Basic, Visual FoxPro and FoxPro, Based on the information gathered during e-Macao
Access and COBOL are the languages and tools mostly Phase I – Agency Survey [10], a detailed list of the appli-
used. Following the results, since Delphi was largely the cations used by Macao Government Agencies is pre-
most used language, APIs for Delphi applications was sented in Appendix C.1. The list specifies the agency
developed. In addition, two executable files that can be code, the application name, and the programming lan-
invoked from the command line are provided for send- guage or tool used for application development. Based
ing and receiving messages. These files aim at providing on the detailed list, a summarized list was prepared
a general solution for sending and receiving messages by indicating the total number of applications using each of
any legacy application able to access the command line, the programming languages and/or tools. The list is
regardless of the programming language used. The fol- presented in Appendix C.2. Finally, the latter list was
lowing three sections present the results about the pro- consolidated and the result is presented in Table 2.
gramming languages and development environments

Table 2: Programming Languages and Tools Mostly Used by Government Applications

PROGRAMMING LANGUAGE / TOOL TOTAL

Delphi 71

Visual Basic 26

Visual FoxPro and FoxPro 23

Access 21

COBOL 21

AS/400 RPG 11

Borland C++ Builder 10

PowerBuilder 9

ASP 8

AS/400 Application development tools 4

Oracle tools 3

C 1

Clipper 1

DBASE 1

ESRI ArcIMS 1

Fortran 1

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 3 – NEW APIS FOR LEGACY SYSTEMS 11

The consolidation presented in the above table was a) function registerMemb-


done based on the following criteria: i) the total number er(name:string; description-
of applications was calculated based on the program- file:string):JObject –for registering a
ming language regardless of the specific version – for new member given the member’s name (name pa-
instance, Access, Access 2000/97 and MS Access are rameter) and the name of the file (descrip-
summarized under Access; ii) the first language was tionfile parameter) describing the required
considered in those cases where more than one lan- attributes for registering a member. The file is
guage was enumerated - for instance, an application stored in the Gateway working directory. If the op-
deployed in DSSOPT, “Professionals/Companies Regis- eration is executed successfully, a pointer to the
tration System”, specifies Delphi, Delphi 400 and COBOL newly registered member is returned.
as programming language; this application was consoli-
dated under the Delphi category; and iii) FoxPro was b) function getMemb-
consolidated with Visual FoxPro, and ASP with ASP.Net. er(memberId:string):JObject – for res-
tarting a Member given the member’s identifier
The results shows 71 applications were developed in (memberId). Like registerMember, it returns a
Delphi; 26 in Visual Basic; 23 in Visual FoxPro and Fox- pointer to the restarted member, if the operation is
Pro; 21 in Access and in COBOL; 11 in AS/400 RPG; 10 in executed succefully.
Borland C++ Builder; 9 in PowerBuilder; 8 in ASP; 4 in
AS/400 Application Development tools; 3 in Oracle c) procedure sendMes-
tools; and 1 in C, Clipper, DBASE, ESRI ArcIMS and For- sage(member:JObject;chId:string;msg
tran. Based on these results, APIs for invoking the Gate- :string) – for sending a message. Three para-
way services by Delphi applications were developed, meters are required: i) the member object (mem-
and are explained in the following section. ber), the channel identifier through which the
message will be sent (chId); and the message it-
3.2. APIS FOR DELPHI self (msg).

As shown in the previous section, Delphi is the pro- d) procedure receiveMes-


gramming language largely used by Government appli- sage(member:JObject;msg:string) – for
cations. Therefore, a set of APIs enabling Delphi applica- receiving a message. The procedure requires two
tions to use the Messaging Gateway services shall be parameters – the member object (member), and
provided. Different approaches can be followed to ena- the message to be received (msg). This method
ble communications between Delphi and Java applica- was defined in the IMember interface to provide
tions – like through the use of intermediate files, the use the pull behavior for receiving messages from a
of sockets or web services. Since, a more direct commu- member – regardless of the channel. However, the
nication is required between Delphi applications and the current implementation of the member follows a
Gateway services; the use of Java Native Interface (JNI) push mechanism. Therefore, it is unlikey that any
[14] was adopted. message will be received by invoking this opera-
tion, unless the member’s behavior is modified.
JNI allows bi-directional invocations between Java and Delphi applications will receive messages which are
native languages, like Delphi. JNI enables a native code pushed by the Gateway through the DelphiImpl
to create, inspect, and update java objects, as well as operation receiveMessage (msg:
call methods within Java classes. In addition, Java excep- string). This procedure was implemented only
tions can be captured and processed in the native code to conform to all operations offered by the IM-
and in some cases, exceptions can be generated back to ember interface. See also n) getMessage be-
the Java runtime environment. The behavior provided low.
by JNI precisely satisfies the requirements for enabling
Delphi applications invoke the Messaging services writ- e) procedure createChan-
ten in Java. In summary, the proposed approach in- nel(member:JObject;chName:string –
cludes: the Gateway services in Java shall invoke call- for creating a channel. Two parameters are re-
back methods in external applications written in Delphi, quired: i) the member object (member) and ii) the
and the different Gateway services shall be exposed as channel name (chName).
Delphi services.
f) procedure destroyChan-
The Delphi API comprises two components:
nel(member:JObject;chId:string) – for
destroying a channel. Two parameters are re-
1) XG2GWrapper class – It is available in the quired: i) the member object (member) and ii) the
XWrapper unit and exposes the operations in- channel identifier (chId).
cluded in the Gateway IMember and IVisitor inter-
faces to Delphi applications. Therefore, Delphi ap-
g) procedure subscribeChan-
plications can invoke the following functions: nel(member:JObject;chId:string;oId:

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 3 – NEW APIS FOR LEGACY SYSTEMS 12

string) – for subscribing the member acting on be configured with one parameter – the name of
behalf of the Delphi application to a channel. Three the XML Schema used for validating messages.
parameters are required: i) the member object Suppose, the XML Schema is a Gateway resource
(member), ii) the channel identifier to which the called XML-Food-License, then the data para-
subscription is requested (chId), and iii) the chan- meter should be precisely that name (XML-Food-
nel owner identifier (oId). License), and the order should be 1.

h) procedure unsubscribeChan- m) procedure forwardMes-


nel(member:JObject;chId:string;oId: sage(member:JObject;chId:string;msg
string) – for unsubscribing the member acting :string) – for forwarding a message through a
on behalf of the Delphi application from a channel. channel. Three parameters are required: the mem-
Three parameters are required: i) the member ob- ber object (member); ii) the channel identifier
ject (member), ii) the channel identifier to which through which the message will be sent (chId);
the unsubscription is requested (chId), and iii) the and iii) the message to be forwarded (msg).
channel owner identifier (oId).
n) getMessage(member:JObject;
i) procedure unregisterMember(member: chId:string):string – for pulling a re-
JObject) – for unregistering the member acting ceived message from a particular channel. Two pa-
on behalf of the Delphi application. The required rameters are required: i) the member object (mem-
parameter is the member object (member). ber); and ii) the channel identifier through which
the message was received (chId). The operation
j) procedure enableExten- assumes messages are received by the member
sion(member:JObject;extType:string; and are stored in the local database. This operation
chId:string; extName:string) – for pulls a message that was received through a given
enabling an extension. Four parameters are re- channel, and stored by the member in the local da-
quired: i) the member object (member), ii) the type tabase.
of extension to be enabled (extType) – possible
values are: Channel if it is a channel-oriented ex- o) procedure setPin(member:JObject;
tension, and Member if it is a member-oriented ex- pin:string) – for setting the member’s PIN to
tension; iii) channel identifier to which the channel- be used for reading the certificates stored in smart
oriented extension will be enabled (chId) – this cards issued by Macao Post. This operation is re-
parameter should be null if a member-oriented ex- quired if Message Encryption is used. It should be
tension is enabled; and iv) the extension name executed after enabling the extension to a channel,
(extName) – possible values are: Message and before its configuration. Two parameters are
Logging (channel-oriented); Message Syntax required: i) the member object (member) and ii)
(channel-oriented); Message Transforma- the PIN to be used (pin).
tion (channel-oriented); Message Semantics
(channel-oriented); Message Mediation 2) DelphiApplicationListener class – It is
(channel-oriented); Message Encryption an implementation of the Gateway Applica-
(channel-oriented); and Message Discovery tionListener interface. It is used internally as a
(member-oriented). parameter to register and to restart a member. The
class does not provide implementation for the dif-
k) procedure disableExten- ferent methods. Instead, it declares them as native
sion(member:JObject;extType:string; and the implementation should be provided in an
chId:string; external library (dll file). The DelphiImpl library
defines the skeleton of such methods. In the cur-
extName:string) – for disabling an extension. rent release, a default implementation is provided
The four required parameters are the same as for these methods, comprising the print out of re-
those required for enabling the extension. ceived messages to the console. A customized be-
havior of these methods can be provided by im-
l) procedure configureExten- plementing the following operations: receive-
sion(member:JObject;extType:string; Message(msg: string), recSendMessa-
chId:string geReply(msg: string), recRegister-
;extName:string;data:string;order:I Reply(msg: string), recUnRegister-
nteger) – for configuring an extension. Six para- Reply(msg: string), recCreateChanne-
meters are required. The first four are the same as lReply(msg: string), recDestroyChan-
those required for enabling an extension. The last nelReply(msg: string), recSubscribe-
two comprises: i) the name of the resource in the ChannelReply(msg: string), recUnsub-
Gateway central repository to be used as an exten- scribeChannelReply(msg: string),
sion parameter (data); and ii) the parameter order recChExtensionReply(msg: string),
(order). For example, Message Syntax requires to

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 3 – NEW APIS FOR LEGACY SYSTEMS 13

recReceiveMessageReply(msg: er>> + <<File.separator>> + “send”. The two


string), recManageReply(msg: variables indicated within angle brackets (<< >>) are
string), recForwardReply(msg: replaced by the first parameter – the member identifier;
string), recGetMemberReply(msg: and by the system-dependent default name-separator
string), recConfigureChExtensionRep- character – for instance, “\”; respectively. This sub-
ly(msg: string) and recMemberUnsub- folder should be located in the folder indicated by the
scribe(msg: string). These methods cor- WorkFolder parameter of the Gateway configuration
respond to the ones defined in the Applica- file.
tionListener interface of the Gateway,
For example, an application running on a Windows envi-
3.3. APIS FOR SENDING AND RECEIVING ronment will have the “\” as the name separator charac-
MESSAGES FROM THE COMMAND LINE ter; the value of the WorkFolder parameter in the
Gateway configuration files is “D:\Gateway\tmp”, if
The previous section described a set of APIs for invoking the following command is invoked:
the Gateway services from applications developed in
Delphi programming language. This set of APIs can be Send 100010 500037
taken as example, for developing APIs for any given ”F2009022416553001.xml”
”D\attach\A2009022416553001.pdf”
language. However, aiming at providing a more general
solution, two executable files are provided for enabling
applications, written in any programming language or it means that the member 100010 is requesting to
tool to invoke the command line, to send and receive send a message, through the channel 500037; the
messages using the Gateway. message content is stored in the file
“D:\Gateway\tmp\100010\send\F200902241
The two executable files are: Send.bat – enabling an 6553001.xml”, and the file
application to send a message; and Receive.bat – “D:\attach\A2009022416553001.pdf”
should be attached.
allowing an application to receive a message. Both files
comprise the enumeration of all Java libraries used by
the Gateway and the invocation of the main method of To receive a message, an application needs to invoke
the corresponding Java classes – Send and Receive, the “Receive” command from the command line. One
respectively. The main methods of these classes are parameter is required for invoking the command: the
explained in the following sections; while the procedure identifier of the member who is receiving the message.
for invoking the executable files are presented below. When the command is executed, the first message re-
ceived is stored in a file in the local subfolder labeled as
<<memberIdentifier>> +
For sending a message an application needs to invoke
<<File.separator>> + “receive”. The variables
the “Send” command from the command line. At least,
indicated within angle brackets (<< >>) are replaced as
three parameters are required for invoking this com-
explained above for the Send command. The name of
mand:
the file storing the received message is <<memberI-
dentifier>> + <<date>> + “.xml”.
1) identifier of the member who is sending the mes-
sage;
For example, following the same assumptions described
for illustrating the Send command, if the following
2) identifier of the channel used for sending the mes-
command is executed:
sage;
Receive 100010
3) name of the file containing the message content to
be sent.
It means that the first message received for the member
100010, regardless of the channel, is saved in the file:
The rest of the parameters correspond to the names of
the files which should be sent as message attachments.
D:\Gateway\tmp\100010\receive\10001
These file names must include the complete path to the
0022520090142551.xml”
files.
assuming the request for receiving the message was
Files containing the message contents should be placed
executed on 25 February 2009 at 01:42:55 pm.
in a local sub-folder labeled as: <<memberIdentifi-

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 3 – NEW APIS FOR LEGACY SYSTEMS 14

Figure 11: Send Class - Main Method

3.3.1. SEND CLASS – MAIN METHOD 3.3.2. RECEIVE CLASS – MAIN METHOD

The behavior of the Send class main method is de- The main method of the Receive class requires the
picted in Figure 11 and explained below. same parameters as those used for invoking the Re-
ceive command. Its behavior is depicted in Figure 12,
The main method requires the same parameters as and its source code is included in Appendix D.2.
those used for invoking the Send command. The me-
thod validates that the number of parameters is correct The method validates that the number of parameters is
(1:validatesParametersNumber) and that the correct (1:validatesParametersNumber). This
filename indicated as the third parameter exists in the function is not implemented as a separate method, but
corresponding folder (2:verifiesFileExist). as part of the method logic. After validating the parame-
These two functions are not implemented as separate ter, a new instance of LegacyApplicationLis-
methods, but as part of the method logic. After validat- tener object is created (2:new) and as a result, the
ing the parameters, a new instance of LegacyAppli- listener object is returned (3:listener). A new
cationListener object is created (3:new) and as a instance of the Anon member is instantiated (4:new),
result, the listener object is returned to whom the request for getting the member is sent
(4:listener). A new instance of the Anon member is (5:getMember). The parameters for getting the mem-
instantiated (5:new), to whom the request for getting ber include the member identifier – the first argument
the member is sent (6:getMember). The parameters of the main method (args[0]), and the application
for getting the member include the member identifier – listener recently created (listener). The Anon
the first argument of the main method (args[0]), and Member instantiates the Member object (6:new) and
the application listener recently created (listener). the object is returned as result (7:Member). Finally, a
The Anon Member instantiates the Member object thread is started for 10 seconds. While the member is
(7:new) and the object is returned as result active, the first message received triggers the invocation
(8:Member). The message to be sent is read from the of the method for receiving a message in the Application
file (9:readsFile) - this function is implemented Listener (9:receiveMessage), and the listener
within the method logic. After reading the message, the writes the message to a fie (10:writesFile).
member is requested to format it
(10:formatMessage), returning the message to be
sent (11:msg); and to send it (12:sendMessage).

The method source code is included in Appendix D.1.

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 3 – NEW APIS FOR LEGACY SYSTEMS 15

Figure 12: Receive Class - Main Method

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 4 – DEPLOYMENT COMPONENTS AND PROCEDURE 16

4. DEPLOYMENT COMPONENTS AND 2) xg2g-Repository – includes the web applica-


PROCEDURE tion supporting the Gateway Administrator func-
tion and managing the Gateway central repository.
The following two sections explain the deployment
components of the new release, as well as new required 3) xg2g-Services – includes the software applica-
steps for the deployment procedure. tion providing the user interface for invoking the
Gateway services.
4.1. DEPLOYMENT COMPONENTS
4) xg2g-Delphi – includes the APIs for invoking
the Gateway services from applications developed
The current release of the Extensible Message Gateway
in Delphi programming language.
delivers the software components structured in five
main folders, as presented in Figure 13. The content of
5) xg2g-OtherLegacy – includes the library and
each of these folders is described below:
executable files enabling sending and receiving
messages from the command line.
1) xg2g – includes four subfolders: i) xg2g-Admin -
contains libraries implementing the Gateway Ad-
The first three sub-folders were included in the previous
ministrator member, ii) xg2g-Communication
release and their content is explained in details in [11].
services – includes the Gateway APIs providing
An explanation of the modified components and the
core and extended messaging services, iii) xg2g-
reasons for their modification follows. The last two sub-
Configuration file – contains the file for
folders are included in this release and their content is
configuring the Gateway, and iv) xg2g-Web
explained below.
services – includes the two web services used
by the Gateway for implementing the communica-
tion layer and the semantic extensions.

Figure 13: Extensible Message Gateway – Deployment Folders

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 4 – DEPLOYMENT COMPONENTS AND PROCEDURE 17

The components highlighted in red in Figure 13 are the o JNIUtils.dcu – is required by JNI-
modified components in the new release. The justifica- Utils.pas;
tion for their modifications follows.
o XWrapper.pas – is responsible for invoking the
o xg2g-Admin – i) removing the functions for ge- Gateway methods;
nerating the public and private keys required by the
previous release of the Encryption/Decryption ex- o XWrapper.dcu – is required by XWrap-
tension; per.pas.

o xg2g-Communication services – i) replac- Similar structure as the one provided for xg2g-
ing the Encryption/Decryption extension with the Delphi is followed for xg2g-OtherLegacy. The
new release; and ii) adding the new service for set- content of the two subfolders is as follows.
ting the PIN – part of the Extended Services.
The bin folder contains:
o xg2g-Configuration file – a new parame-
ter – CardReaderConfigFile, was added for o lib – a folder containing all the libraries used by
specifying the location of the configuration file for the Gateway;
the card reader used by the new extension release.
o logs – a folder for storing the log files;
o xg2g-Services – adding the new service for
setting the PIN.
o Send.bat – the executable file for sending mes-
sages;
The xg2g-Delphi folder includes two subfolders: i)
bin – containing the binary code; and ii) src – contain- o Receive.bat – the executable file for receiving
ing the source files. The content of these folders follows. messages.

The bin folder contains: The src folder contains the source code of the three
Java classes – Send, Receive and LegacyAppli-
o libs – a folder containing all the libraries used cationListener.
by the Gateway;
4.2. DEPLOYMENT PROCEDURE
o logs – a folder for storing the log files;
The deployment procedure for the application imple-
o config – contains the config.properties file for menting the Gateway Administrator member (xg2g-
specifying the path to the Java Virtual Machine li- Admin), the Gateway APIs (xg2g-Communication
brary and the name of the library to be loaded by Services), the web services responsible for exchang-
DelphiApplicationListener; ing messages and providing the semantic extensions
(xg2g-Web Services), the Administrator repository
o DelphiImpl.dll – is the default implementa- (xg2g-Repository), and the User Interface (xg2g-
tion of the Gateway Application Listener. User Interface) were not changed with respect to
the previous release and are explained in details in the
The src folder contains: Extensible Message Gateway - User Manual [11], Chap-
ter 4.
o DelphiApplicationListener.java – is
the implementation of the Gateway Application Lis- Compared with the previous release, only one change
teener that will be used by Delphi applications; was introduced to the procedure for deploying the Ga-
teway configuration file (xg2g-Configuration
o DelphiImpl.dpr – is the default implementa- File). For the previous release, a detailed description
tion of DelphiImpl library; for the procedure was provided in [11]. In the new re-
lease, there is one more parameter in the file requiring
o JNI.pas – is a Delphi implementation of JNI; personalization – CardReaderConfigFile. If the
Encryption/Decryption extension will be used in a node,
o JNI.dcu – is required by JNI.pas; the configuration file of the smart card reader shall be
stored in a local folder. The value of the CardReader-
o JNI_MD.INC – is required by JNI.pas; ConfigFile parameter shall be the full path plus the
name of this file. For example, the default value of the
o JNIUtils.pas – is a collection of utility methods parameter is C:\\config\\pkcs11.cfg. It means
for using JNI.pas; that the folder config exists on drive C: and the file
pkcs11.cfg placed in that folder is the configuration

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 4 – DEPLOYMENT COMPONENTS AND PROCEDURE 18

file of the smart card reader to be used by the Encryp- cated by the WorkFolder parameter of
tion/Decryption extension. the configuration file.

The deployment of the Dephi APIs is as follows: b. Create the sub-folders send and re-
ceive within the member’s folder.
1) Copy the bin folder to the desired library;

Figure 14: Folder Structure for Receiving and Sending


2) Modify the DelphiImpl library by providing suit-
Messages through the Command Line
able implementations for the different methods;

3) Generate the library (dll file);

4) Edit the config.properties file of the con-


fig folder. Two parameters shall be personalized:

a. jvm.path - specifying the path to the


jvm.dll file of the JRE;

b. library.name - defining the name of


the library used by DelphiApplica-
tionListener;

5) Add a reference to the unit XWrapper.pas in


your Delphi project.

In order to successfully run your code, the generated


library, the config and libs folders should be in the
same folder as your project (or executable).

The deployment of the executable files for sending and For example, assuming the working folder of the Gate-
receiving messages from the command line requires: way is D:\Gateway\tmp, and three members –
100007, 100014, and 100062; are registered in the
1) copy the content of the bin folder to the folder node and are willing to use the executable files, Figure
in which the executable files will be executed; 14 shows the folders that are required, according to the
above procedure. In the case of the folders for receiving
files, if the folders do not exist, they are created at run-
2) For each member using these files:
time.
a. Create a folder labeled with the member
identifier within the folder used as the
working folder of the Gateway – indi-

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


SECTION 5 – CONCLUSIONS 19

5. CONCLUSIONS guages mostly used by applications deployed in Macao


Government agencies, a set of Delphi-APIS and two ex-
This report presents technical details of the new release ecutable files are provided. The Delphi-APIs enable ap-
of the Extensible Messaging Gateway implementing a plication written in Delphi to invoke the Gateway servic-
new version of the Message Encryption extension, as es. The two executable files enable any application writ-
well as the new sets of APIs provided for facilitating the ten in any language able to invoke the command line to
use of the Gateway by legacy applications. The software send and receive messages through the Gateway. Other
developed was produced by the UNU-IIST Center for services offered by the Gateway, like those configuring
Electronic Government during 2008 for the Government the communication structures – register and unregister
of Macao SAR, under the Macao Data Exchange Gate- member, create and destroy channel, subscribe and
way Project, part of the e-Macao Program. unsubscribe member to/from a channel, enable, confi-
gure and disable an extension; can be requested
through the user interface.
The new release of the Gateway provides a new version
of the Encryption/Decryption extension which uses the
certificates issued by Macao Post Office. The certificates This report presented the following sequence of topics.
are provided in a smart card, and a PIN is required for An introduction to the project scope, its aim and objec-
accessing them. The new extension defines a new ser- tives were presented in Section 1. Section 2 introduced
vice (setting PIN) enabling the member to store this technical details for the new release of the Encryp-
information. Replacing the Encryption/Decryption ex- tion/Decryption extension – the provided services and
tension involved modifying the following Gateway com- their implementation. Section 3 presented the study
ponents: i) the Administrator application for eliminating about the programming languages mostly used by Ma-
the generation of the keys used by the previous release cao government applications, new APIs developed for
of the extension, and adding the reply to the message requesting the services by Delphi applications – the
requesting to set the member’s PIN; ii) the Gateway APIs programming language mostly used; and executable
for including the new service (set PIN); iii) the user inter- files for sending and receiving messages from the com-
face for invoking the service for setting the PIN; and iv) mand line. These files can be invoked by any legacy ap-
the configuration file for adding a parameter indicating plication, able to access the command line, regardless of
the location and name of the configuration file for the the programming language in which it was developed.
smart card reader. Section 4 explains the deployment components, the
modified components compared with the previous re-
A new set of APIs and executable files are provided lease, and the modifications to the deployment proce-
dure. Finally, the following appendices present some of
enabling legacy applications to invoke the Gateway ser-
vices. Based on the analysis of the programming lan- the technical artifacts used by the new Gateway release
and set of APIs.

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


REFERENCES 20

REFERENCES ios/12_2t/12 _2t13/feature/guide/ft_aes.html, vi-


sited on February 16, 2009.
[1] Elsa Estevez, Vincent Douwe and Tomasz Janowski, [10] Tomasz Janowski, Adegboyega Ojo and Elsa Estevez
Extensible Messaging Gateway – Quality Assurance (Eds), The State of Electronic Government in Macao,
Report, UNU-IIST-EGOV, September 2008. Volume 2 Agencies, e-Macao Project, available at
[2] Elsa Estevez, Vincent Douwe and Tomasz Janowski, www.emacao.gov.mo, Deliverables - Survey, report
e-Appointment Service – Development Report, Ma- 2, visited on 25 January 2009.
cao Data Exchange Gateway Project, UNU-IIST- [11] Elsa Estevez, Vincent Douwe and Tomasz Janowski,
EGOV, February 2009. Extensible Message Gateway, User Manual, Soft-
[3] Elsa Estevez, Vincent Douwe and Tomasz Janowski, ware Infrastructure for Electronic Government
e-Appointment Service – User Manual, Macao Data Project, e-Macao Program, 2007.
Exchange Gateway Project, UNU-IIST-EGOV, Febru- [12] SUN MicroSystems, Java Cryptography Architecture
ary 2009. reference guide, available at
[4] Elsa Estevez, Vincent Douwe and Tomasz Janowski, http://java.sun.com/javase/6/docs/technotes/guid
Queuing Service – Development Report, Macao Da- es/security/crypto/CryptoSpec.html, visited on
ta Exchange Gateway Project, UNU-IIST-EGOV, Feb- February 16, 2009.
ruary 2009. [13] SUN MicroSystems, Java PKCS#11 Reference Guide,
[5] Elsa Estevez, Vincent Douwe and Tomasz Janowski, available at
Queuing Service – User Manual, Macao Data Ex- http://java.sun.com/javase/6/docs/technotes/guid
change Gateway Project, UNU-IIST-EGOV, February es/security/crypto/CryptoSpec.html, visited on
2009. February 16, 2009
[6] R.L. Rivest, A. Shamir, and L. Adleman, A Method [14] Sheng Liang, The Java Native Interface Program-
for Obtaining Digital Signatures and Public-Key mer’s Guide and Specification, Addison-Wesley,
Cryptosystems, available at February 2009. June 1999, also available at
[7] National Institute of Standards and Technology http://java.sun.com/docs/books/jni/
(NIST), Announcing the Advanced Encryption Stan- [15] Matthew Mead, Using the Java Native Interface
dard (AES), November 2001, available at with Delphi, available at
http://csrc.nist.gov/publications/fips/fips197/fips- http://www.pacifier.com/~mmead/jni/delphi, vi-
197.pdf, visited on 26 February 2009. sited on February 16, 2009.
[8] eSignTrust, About eSignTrust, available at [16] Keith Wood, Go Native, available at
http://www.esigntrust.com/en/m1.php?pageID=1, http://www.pacifier.com/~mmead/jni/delphi/infor
last visited February 16,2009. mant/ di200309kw.htm, visited on Febraury 16,
[9] Cisco, Advanced Encryption Standard (AES), availa- 2009.
ble at http://www.cisco.com/en/US/docs/

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 21

APPENDICES

A. JAVA CLASSES USED BY THE ENCRYPTION EXTENSION

A.1. ENCRYPTION CLASS

Java Class 1: Encryption

package edu.unu.iist.emacao.xg2g.extensions;

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.codec.binary.Hex;
import org.apache.log4j.Logger;
import org.apache.xmlbeans.XmlObject;

import edu.unu.iist.emacao.gateway.xmlUtil.ExtAction;
import edu.unu.iist.emacao.gateway.xmlUtil.ForwardMessage;
import edu.unu.iist.emacao.gateway.xmlUtil.UserMessage;
import edu.unu.iist.emacao.xg2g.core.Member;
import edu.unu.iist.emacao.xg2g.core.Message;
import edu.unu.iist.emacao.xg2g.database.ChExtensionParam;
import edu.unu.iist.emacao.xg2g.database.ChannelExtension;
import edu.unu.iist.emacao.xg2g.database.ChannelExtensionManager;
import edu.unu.iist.emacao.xg2g.util.ExtensionsUtil;

public class Encryption extends ChAllExtension {

private static final Logger logger = Logger.getLogger(Encryption.class);


private ExtensionsUtil util;
private KeyPair pair;

public Encryption(ChannelExtension extension, Member member) {


super(extension, ChAllExtensionFactory.encryption, member);
util = new ExtensionsUtil();
}

@Override
public String processIncomingMessage(String message) throws Exception {
// This method is used for processing incoming messages.

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 22

// This consists typically to getting the key and decrypting the message
String msgToReturn = null;
try {
// Saves the user message to a file
Message msgAux = new Message(message);
UserMessage usrMsg = UserMessage.Factory.parse(msgAux
.getUserDefinedMessage());
String pp = XmlObject.Factory.parse(usrMsg.getContent().toString())
.xmlText();
logger.info("Encrypting the message : " + pp);
// gets the schema
Key val = null;
if (isOwner)
val = getPrivateKey();
else {
String encoded = getEncodedPublicKey();
if (encoded == null)
throw new Exception(
"The encryption extension is not properly confi-
gured");
val = getPublicKey(Hex.decodeHex(encoded.toCharArray()));
}
String text = util.decrypt(pp, val);
usrMsg.setContent(XmlObject.Factory.parse(text));
msgToReturn = msgAux.setUserDefinedMessage(usrMsg.toString());

} catch (Exception e) {
logger.error("Exception ", e);
}
return msgToReturn;
}

private String getEncodedPublicKey() throws Exception {

if (isOwner) {
return new String(Hex.encodeHex(getPublicKey().getEncoded()));
} else {
ChannelExtensionManager chMgr = new ChannelExtensionManager();
Collection<ChExtensionParam> listParam = chMgr
.getParameter(extension);
if (listParam == null || listParam.size() == 0)
throw new Exception("Unable to find the key for encryption");
for (ChExtensionParam ts : listParam) {
return ts.getChExtParam();
}
}

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 23

return null;

@Override
public String processMessage(String message) throws Exception {
// This method is used for processing outgoing messages
// This typically consists to getting the key and encrypting the message
String msgToReturn = null;
try {
// Saves the user message to a file
Message msgAux = new Message(message);
UserMessage usrMsg = UserMessage.Factory.parse(msgAux
.getUserDefinedMessage());
String pp = XmlObject.Factory.parse(usrMsg.getContent().toString())
.xmlText();
logger.info("Encrypting the message : " + pp);
Key val = null;
if (isOwner)
val = getPrivateKey();
else {
String encoded = getEncodedPublicKey();
if (encoded == null)
throw new Exception(
"The encryption extension is not properly confi-
gured");
val = getPublicKey(Hex.decodeHex(encoded.toCharArray()));
}
String text = util.encrypt(pp, val);
usrMsg.setContent(XmlObject.Factory.parse(text));
msgToReturn = msgAux.setUserDefinedMessage(usrMsg.toString());

} catch (Exception e) {
logger.error("Exception ", e);
}
return msgToReturn;
}

@Override
public void configureExtension(Map<Integer, String> msg) throws Exception {
super.configureExtension(msg);
String data = msg.get(1);
member.forwardToAllSubscribers(ExtAction.ENABLE, extension.getChannel()
.getChannelId(), name, data);
}

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 24

private PrivateKey getPrivateKey() throws Exception {


if (isOwner)
return getPair().getPrivate();
throw new Exception("Member is not the owner of the channel");
}

private PublicKey getPublicKey() throws Exception {


if (isOwner) {
return getPair().getPublic();
}
throw new Exception("Member is not the owner of the channel");

private PublicKey getPublicKey(byte[] encoded) throws Exception {


KeyFactory kfactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keys = new X509EncodedKeySpec(encoded);
PublicKey keyp = kfactory.generatePublic(keys);
return keyp;
}

@Override
public void newSubscriber(String mId) throws Exception {
// String data = getChExtParam(PRIVATE_KEY).getChExtParam();
String data = getEncodedPublicKey();
ForwardMessage fm = ForwardMessage.Factory.newInstance();
fm.setAction(ExtAction.ENABLE);
fm.setChannelId(extension.getChannel().getChannelId());
fm.setData(data);
fm.setMemberId(mId);
fm.setExtName(name);
member.forwardMessage(mId, fm.toString());

private KeyPair getPair() throws Exception {


if (pair == null)
pair = new ExtensionsUtil().getKeys(member.getMemberId());
return pair;
}
}

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 25

A.2. EXTENSIONSUTIL CLASS

Java Class 2: ExtensionsUtil

package edu.unu.iist.emacao.xg2g.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.util.Enumeration;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.security.pkcs11.SunPKCS11;

public class ExtensionsUtil {

public String Transforme(String doc, String xlst) {


return null;

public String validate(String doc, String schema) {


return null;
}

private MessageDigest createDigest() throws Exception {


return MessageDigest.getInstance("MD5");
}

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 26

private byte[] getDigest(byte[] data) throws Exception {


if (data == null)
throw new Exception("The data can not be null");
byte[] result = null;
MessageDigest d = createDigest();
int length = d.getDigestLength();
result = new byte[length];
d.update(data);
d.update(result, 0, length);
return result;
}

public String encrypt(String plainText, Key key) throws Exception {


byte[] textToEncrypt = plainText.getBytes();
// generate the session key
SecretKey aesKey = createAESKey();
// encrypt the plaintext using this session key
byte[] encryptedBytes = encryptAES(textToEncrypt, aesKey);
byte[] keyBytes = aesKey.getEncoded();
// System.out.println("The size of the key is "+keyBytes.length);
byte[] encryptedKey = encryptRSA(keyBytes, key);
StringBuilder builder = new StringBuilder("<value>");
builder.append("<a>");
builder.append(stringFromBytes(encryptedKey));
builder.append("</a>");
builder.append("<b>");
builder.append(stringFromBytes(encryptedBytes));
builder.append("</b>");
builder.append("</value>");
return builder.toString();

// use a combinaison of RSA and AES to provide decryption functionalities


public String decrypt(String cipherText, Key key) throws Exception {
// get the aes key
String aesKey = getA(cipherText);
// get the encrypted content
String encrypted = getB(cipherText);
// get the aes key
byte[] aesByteKey = bytesFromString(aesKey);
// Generate the key
byte[] res = decryptRSA(aesByteKey, key);
SecretKeySpec skeySpec = new SecretKeySpec(res, "AES");
// compute the content

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 27

return new String(decryptAES(bytesFromString(encrypted), skeySpec));

private Cipher createRSACipher() throws Exception {


return Cipher.getInstance("RSA/ECB/PKCS1Padding");
}

private Cipher createAESCipher() throws Exception {


return Cipher.getInstance("AES/ECB/PKCS5Padding");
}

private SecretKey createAESKey() throws Exception {


KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
return kgen.generateKey();
}

private byte[] encryptRSA(byte[] text, Key key) throws Exception {


Cipher cipher = createRSACipher();
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(text);
}

private byte[] encryptAES(byte[] text, Key key) throws Exception {


Cipher cipher = createAESCipher();
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(text);
}

private byte[] decryptRSA(byte[] text, Key key) throws Exception {


Cipher cipher = createRSACipher();
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(text);
}

private byte[] decryptAES(byte[] text, Key key) throws Exception {


Cipher cipher = createAESCipher();
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(text);
}

public String stringFromBytes(byte[] value) throws Exception {


BASE64Encoder b64 = new BASE64Encoder();
return b64.encode(value);

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 28

public byte[] bytesFromString(String text) throws Exception {


BASE64Decoder b64 = new BASE64Decoder();
return b64.decodeBuffer(text);
}

private String getA(String text) throws Exception {


int index1 = text.indexOf("<a>");
int index2 = text.indexOf("</a>");
if ((index1 > -1) && ((index2 > -1)))
return text.substring(index1 + 3, index2);
return null;
}

private String getB(String text) throws Exception {


int index1 = text.indexOf("<b>");
int index2 = text.indexOf("</b>");
if ((index1 > -1) && ((index2 > -1)))
return text.substring(index1 + 3, index2);
return null;
}

public KeyPair getPairKey() throws Exception {


KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1026);
return keyGen.generateKeyPair();
}

public String encryptWithAES(String plainText, String password)


throws Exception {
byte[] plainBytes = plainText.getBytes();
byte[] key = getDigest(password.getBytes());
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(key);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] result = cipher.doFinal(plainBytes);
return stringFromBytes(result);

public String decryptWithAES(String cipherText, String password)


throws Exception {
byte[] plainBytes = bytesFromString(cipherText);

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 29

byte[] key = getDigest(password.getBytes());


SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(key);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] result = cipher.doFinal(plainBytes);
return new String(result).trim();
}

public String readPin(String memberId) throws Exception {


File f = new File(GlobalVariables.getWorkFolder()
+ java.io.File.separator + "PIN-" + memberId + ".xg2g");
if (!f.exists())
throw new Exception("The PIN is not available. Set the PIN first");
FileInputStream stream = new FileInputStream(f);
byte[] result = new byte[stream.available()];
stream.read(result);
String val = new String(result);
return decryptWithAES(val, memberId);
}

public void setPin(String memberId, String pin) throws Exception {


// Create encrypted file containing the pin
ExtensionsUtil util = new ExtensionsUtil();
// Encrypt the pin
String encryptedPin = util.encryptWithAES(pin, memberId);
// Store it in a file name PIN-MEMBERID.xg2g
File f = new File(GlobalVariables.getWorkFolder()
+ java.io.File.separator + "PIN-" + memberId + ".xg2g");
FileOutputStream stream = new FileOutputStream(f);
stream.write(encryptedPin.getBytes());
stream.close();
}

public KeyPair getKeys(String memberId) throws Exception {


KeyPair pair = null;
String configName = GlobalVariables.getCardReaderConfigFileName();
if (configName != null) {
Provider provider = new SunPKCS11(configName);
Security.addProvider(provider);
char[] pin = new ExtensionsUtil().readPin(memberId).toCharArray();
KeyStore store = KeyStore.getInstance("PKCS11");
store.load(null, pin);
Enumeration<String> values = store.aliases();
// KeyPair pair = null;

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 30

while (values.hasMoreElements()) {
String value = values.nextElement();
Key key = store.getKey(value, pin);
if (key instanceof PrivateKey) {
Certificate cert = store.getCertificate(value);
PublicKey publicKey = cert.getPublicKey();
pair = new KeyPair(publicKey, (PrivateKey) key);
}
}
}
return pair;
}

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 31

B. DELPHI APIS

B.1. JAVA DELPHIAPPLICATIONLISTENER CLASS

Java Class 1: DelphiApplicationListener

package edu.unu.iist.emacao.xg2g.delphi;

import java.io.FileInputStream;
import java.util.Properties;

import edu.unu.iist.emacao.xg2g.core.ApplicationListener;

public class DelphiApplicationListener implements ApplicationListener{


static {
//System.out.println("Library Path :
"+System.getProperty("java.library.path"));
Properties prop=new Properties();
String lib="DelphiImpl";
try {
prop.load(new FileInput-
Stream("./config/config.properties"));
lib=prop.getProperty("library.name");
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
System.loadLibrary(lib);
}
public DelphiApplicationListener(){

}
native public void recChExtensionReply(String arg0);

native public void recConfigureChExtensionReply(String arg0);

native public void recCreateChannelReply(String arg0);

native public void recDestroyChannelReply(String arg0) ;

native public void recForwardReply(String arg0) ;

native public void recGetMemberReply(String arg0) ;

native public void recManageReply(String arg0) ;

native public void recMemberUnsubscribe(String arg0) ;

native public void recReceiveMessageReply(String arg0) ;

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 32

native public void recRegisterReply(String arg0) ;

native public void recSendMessageReply(String arg0) ;

native public void recSubscribeChannelReply(String arg0) ;

native public void recUnRegisterReply(String arg0) ;

native public void recUnsubscribeChannelReply(String arg0) ;

native public void receiveMessage(String arg0) ;

B.2. DELPHIIMPL LIBRARY

Delphi unit 1: DelphiImpl

library DelphiImpl;

uses
SysUtils,
Classes,
JNI in 'JNI.pas',
JNIUtils in 'JNIUtils.pas',
xg2g in 'xg2g.pas',
XWrapper in 'XWrapper.pas';

{*IMPLEMENTATION OF PROTECTED METHODS*}


procedure receiveMessage(msg: string);
begin
// This is a minimal implementation. It just print out the message to the screen
Writeln(msg);
end;

procedure recSendMessageReply(msg: string);


begin
// This is a minimal implementation. It just print out the message to the screen
Writeln(msg);
end;

procedure recRegisterReply(msg: string);


begin
// This is a minimal implementation. It just print out the message to the screen

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 33

Writeln(msg);
end;

procedure recUnRegisterReply(msg: string);


begin
// This is a minimal implementation. It just print out the message to the screen
Writeln(msg);
end;

procedure recCreateChannelReply(msg: string);


begin
// This is a minimal implementation. It just print out the message to the screen
Writeln(msg);
end;

procedure recDestroyChannelReply(msg: string);


begin
// This is a minimal implementation. It just print out the message to the screen
Writeln(msg);
end;

procedure recSubscribeChannelReply(msg: string);


begin
// This is a minimal implementation. It just print out the message to the screen
Writeln(msg);
end;

procedure recUnsubscribeChannelReply(msg: string);


begin
// This is a minimal implementation. It just print out the message to the screen
Writeln(msg);
end;

procedure recChExtensionReply(msg: string);


begin
// This is a minimal implementation. It just print out the message to the screen
Writeln(msg);
end;

procedure recReceiveMessageReply(msg: string);


begin
// This is a minimal implementation. It just print out the message to the screen

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 34

Writeln(msg);
end;

procedure recManageReply(msg: string);


begin
// This is a minimal implementation. It just print out the message to the screen
Writeln(msg);
end;

procedure recForwardReply(msg: string);


begin
// This is a minimal implementation. It just print out the message to the screen
Writeln(msg);
end;

procedure recGetMemberReply(msg: string);


begin
// This is a minimal implementation. It just print out the message to the screen
Writeln(msg);
end;

procedure recConfigureChExtensionReply(msg: string);


begin
// This is a minimal implementation. It just print out the message to the screen
Writeln(msg);
end;
procedure recMemberUnsubscribe(msg: string);
begin
// This is a minimal implementation. It just print out the message to the screen
Writeln(msg);
end;
{$R *.res}
procedure Ja-
va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recChExtensionReply(PEnv: PJNIEnv;
Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 35

recChExtensionReply(value);
end;

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener
* Method: recConfigureChExtensionReply
* Signature: (Ljava/lang/String;)V
*)
procedure Ja-
va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recConfigureChExtensionReply(PEnv:
PJNIEnv; Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
recConfigureChExtensionReply(value);
end;

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener
* Method: recCreateChannelReply
* Signature: (Ljava/lang/String;)V
*)
procedure Ja-
va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recCreateChannelReply(PEnv: PJNIEnv;
Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
recCreateChannelReply(value);
end;

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener
* Method: recDestroyChannelReply
* Signature: (Ljava/lang/String;)V

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 36

*)
procedure Ja-
va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recDestroyChannelReply(PEnv: PJNIEnv;
Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
recDestroyChannelReply(value);
end;

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener
* Method: recForwardReply
* Signature: (Ljava/lang/String;)V
*)
procedure Ja-va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recForwardReply(PEnv:
PJNIEnv; Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
recForwardReply(value);
end;

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener
* Method: recGetMemberReply
* Signature: (Ljava/lang/String;)V
*)
procedure Ja-
va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recGetMemberReply(PEnv: PJNIEnv;
Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 37

begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
recGetMemberReply(value);
end;

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener
* Method: recManageReply
* Signature: (Ljava/lang/String;)V
*)
procedure Ja-va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recManageReply(PEnv:
PJNIEnv; Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
recManageReply(value);
end;

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener
* Method: recMemberUnsubscribe
* Signature: (Ljava/lang/String;)V
*)
procedure Ja-
va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recMemberUnsubscribe(PEnv: PJNIEnv;
Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
recMemberUnsubscribe(value);
end;

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 38

* Method: recReceiveMessageReply
* Signature: (Ljava/lang/String;)V
*)
procedure Ja-
va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recReceiveMessageReply(PEnv: PJNIEnv;
Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
recReceiveMessageReply(value);
end;

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener
* Method: recRegisterReply
* Signature: (Ljava/lang/String;)V
*)
procedure Ja-va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recRegisterReply(PEnv:
PJNIEnv; Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
recRegisterReply(value);
end;

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener
* Method: recSendMessageReply
* Signature: (Ljava/lang/String;)V
*)
procedure Ja-
va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recSendMessageReply(PEnv: PJNIEnv;
Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 39

FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
recSendMessageReply(value);
end;

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener
* Method: recSubscribeChannelReply
* Signature: (Ljava/lang/String;)V
*)
procedure Ja-
va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recSubscribeChannelReply(PEnv:
PJNIEnv; Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
recSubscribeChannelReply(value);
end;

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener
* Method: recUnRegisterReply
* Signature: (Ljava/lang/String;)V
*)
procedure Ja-
va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recUnRegisterReply(PEnv: PJNIEnv; Obj:
JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
recUnRegisterReply(value);
end;

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 40

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener
* Method: recUnsubscribeChannelReply
* Signature: (Ljava/lang/String;)V
*)
procedure Ja-
va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recUnsubscribeChannelReply(PEnv:
PJNIEnv; Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
recUnsubscribeChannelReply(value);
end;

(*
* Class: edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener
* Method: receiveMessage
* Signature: (Ljava/lang/String;)V
*)
procedure Ja-va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_receiveMessage(PEnv:
PJNIEnv; Obj: JObject; Arg1: JString);
{$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
FJNIEnv: TJNIEnv;
value: String;
begin
FJNIEnv:=TJNIEnv.Create(PEnv);
value:=FJNIEnv.JStringToString(Arg1);
receiveMessage(value);
end;
exports
Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recChExtensionReply,
Ja-va_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recConfigureChExtensionReply,
Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recCreateChannelReply,
Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recDestroyChannelReply,
Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recForwardReply,
Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recGetMemberReply,
Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recManageReply,

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 41

Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recMemberUnsubscribe,
Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recReceiveMessageReply,
Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recRegisterReply,
Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recSendMessageReply,
Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recSubscribeChannelReply,
Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recUnRegisterReply,
Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_recUnsubscribeChannelReply,
Java_edu_unu_iist_emacao_xg2g_delphi_DelphiApplicationListener_receiveMessage;
begin
end.

B.3. XWRAPPER UNIT

Delphi Unit 1: XWrapper.pas

unit XWrapper;
interface
uses
ShareMem,
SysUtils,
Classes,
JNI,
JNIUtils;

Type XG2GWrapper = class(TObject)


private
cls:JClass;
apListClass:JClass;
anonObject:JObject;
apListObject: JObject;
mId:JMethodID;
Options: array[0..4] of JavaVMOption;
VM_args:JavaVMInitArgs;
JavaVM: TJavaVM;
JNIEnv: TJNIEnv;
Errcode: Integer;
function CreateJavaObject(const ClassName: string; var AClass: JClass): JObject;
procedure callMethod(member: JObject; method: string;sig:string;params:array of JValue);
function getExtensionType(const extType:string):JObject;
function getJVMPath():string;
function formatMessage(member: JObject;chId:string;msg:string;attachment:array of string):string;
protected
{ déclarations protected }

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 42

public
{I need to comment these methods}
constructor Create();
// These two methods are used by Anon
function registerMember(name: string;descriptionfile:string): JObject;
function getMember(memberId:string):JObject;
// These methods are used by member
procedure sendMessage(member:JObject;chId:string;msg:string);
procedure receiveMessage(member:JObject;msg:string);
procedure createChannel(member:JObject;chName:string);
procedure destroyChannel(member:JObject;chId:string);
procedure subscribeChannel(member:JObject;chId:string;oId:string);
procedure unsubscribeChannel(member:JObject;chId:string;oId:string);
procedure unregisterMember(member: JObject);
procedure enableExtension(member:JObject;extType:string;chId:string;extName:string);
procedure disableExtension(member:JObject;extType:string;chId:string;extName:string);
procedure configureExten-sion(member:JObject;extType:string;chId:string;extName:string;data:string;order:Integer);
procedure forwardMessage(member:JObject;chId:string;msg:string);
function getMessage(member:JObject; chId:string):string;
procedure setPin(member:JObject; pin:string);
published
{ déclarations published }
end;

implementation
{Used to create a new instance of the XG2GWrapper class}
// Maybe in the future this constructor will take at least two parameters
// The path to the jvm.dll file and the classpath variable. Another solution will be
// the use of a configuration file
constructor XG2GWrapper.Create();
begin
try
// Create the JVM using a wrapper class. It instantiate the JVM machine and the JRE variable
// The best way will be to take this value as a parameter or read it from a configuration file
JavaVM:=TJavaVM.Create(JNI_VERSION_1_4, getJVMPath());
// set the options for the VM. Probably instead of hard-coding this value I just derive as a parameter
Options[0].optionString:='-Djava.class.path=.;.\libs';
VM_args.version:=JNI_VERSION_1_4;
VM_args.options:=@Options;
VM_args.nOptions:=1;

// Load the VM
Errcode:=JavaVM.LoadVM(VM_args);
if Errcode<0 then
Begin

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 43

Writeln(Format('Error loading JavaVM, error code =%d',[Errcode]));


Exit;
End;
// Create a Java environment from the JVM's Env (another wrapper class)
JNIEnv:=TJNIEnv.Create(JavaVM.Env);
except
on E: Exception do
Writeln('Error: '+e.Message);
end;
end;
function XG2GWrapper.getJVMPath():string;
var F: TextFile;
S: string;
ind: integer;
begin
Result:='';
if FileExists('.\config\config.properties') then begin
AssignFile(F, '.\config\config.properties');
Reset(F);
while not Eoln(F) do
begin
Readln(F, S);
S:=Trim(S);
ind:= Pos('jvm.path',S);
if ind>0 then
begin
ind:=Pos('=',S);
if ((ind>0) and (ind<length(S))) then
Result:=trim(copy(S,ind+1,length(S)));
break;
end;

end;

end
else
begin
Writeln('Configuration file not found');
Exit;
end;
end;
procedure XG2GWrapper.callMethod(member: JObject; method: string; sig: string; params: array of JValue);
var Cls:JClass;
mId: JMethodID;
begin

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 44

// get the object class name


Cls:=JNIEnv.GetObjectClass(member);
if Cls=nil then
begin
Writeln('Unable to find the class of the object');
exit ;
end;
// find the method with name method
mId:=JNIEnv.GetMethodID(Cls,PansiChar(method),PansiChar(sig));
if mId=nil then
begin
Writeln('Unable to find the method '+method);
exit;
end;
// call the method
JNIEnv.CallObjectMethodA(member,mId,@params);

end;

{*Section reserved to XG2GWrapper an helper class used by Anon and Member*}


function XG2GWrapper.CreateJavaObject(const ClassName: string; var AClass: JOb-ject):JObject;
var
Mid: JMethodID;
begin
Result := nil;

// Find the class


try
AClass := JNIEnv.FindClass(PChar(ClassName));
if AClass = nil then
begin
Writeln('Unable to find the class '+ClassName);
Exit;
end;

// Get its default constructor


Mid := JNIEnv.GetMethodID(AClass, '<init>', '()V');
if Mid = nil then
begin
Writeln('Unable to find the constructor of the class '+ClassName);
exit;
end;
// Create the object
Result := JNIEnv.NewObjectA(AClass, Mid, nil);

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 45

except
on E: Exception do
writeln('Error: ' + E.Message);
end;
end;

{*Get The ExtType.Enum based on its String description*}


function XG2GWrapper.getExtensionType(const extType:string):JObject;
var ags:array[1..1] of JValue;
begin
Result:=nil;
// Get the type of the exttype
Cls:=JNIEnv.FindClass('edu/unu/iist/emacao/gateway/xmlUtil/ExtType$Enum');
if cls=nil then
Begin
Writeln('Can''t find class : edu/unu/iist/emacao/gateway/xmlUtil/ExtType$Enum');
Exit;
End;
// Get the method forString

mId:=JNIEnv.GetStaticMethodID(cls,'forString','(Ljava/lang/String;)Ledu/unu/iist/emacao/gateway/xmlUtil/ExtType$Enu
m;');
if mId=nil then
Begin
Writeln('Can''t method forString of the class : edu/unu/iist/emacao/gateway/xmlUtil/ExtType$Enum');
Exit;
End;

ags[1].l:=JNIEnv.StringToJString(pansichar(extType));
Result:=JNIEnv.CallStaticObjectMethodA(cls,mId,@ags);
end;
{*format a message according to the destination channel*}
function XG2GWrapper.formatMessage(member: JObject;chId: string; msg: string; attachment: array of string):string;
var params:array[1..3] of JValue;
begin
Cls:=JNIEnv.GetObjectClass(member);
if Cls=nil then
begin
Writeln('Unable to find the class of the object');
exit ;
end;
// find the method with name method

mId:=JNIEnv.GetMethodID(Cls,'formatMessage','(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/String;
');
if mId=nil then

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 46

begin
Writeln('Unable to find the method formatMessage of class Member');
exit;
end;
// Prepapre the parameters
params[1].l:=JNienv.StringToJString(PansiChar(chId));
params[2].l:=JNienv.StringToJString(PansiChar(msg));
params[3].l:=nil;
// call the method
Result:=JNIEnv.JStringToString(JNIEnv.CallObjectMethodA(member,mId,@params));
end;
{*Implementation of the register method*}
function XG2GWrapper.registerMember(name: string; descriptionfile: string):JObject;
var
arg0: JString;
arg1: JString;
ARGS:array[0..2] of JValue;
begin
Result:=nil;
try

//Cls:=JNIEnv.FindClass('edu/unu/iist/emacao/xg2g/core/Anon');
apListObject:= CreateJavaOb-ject('edu/unu/iist/emacao/xg2g/delphi/DelphiApplicationListener',apListClass);

// Call the anon constructor


AnonObject:=CreateJavaObject('edu/unu/iist/emacao/xg2g/core/Anon',Cls);
if AnonObject=nil then
begin
Writeln('Unable to create an instance of Anon class');
Exit;
end;
//Find the method 'registerMember' of the Anon class

Mid:=JNIEnv.GetMethodID(cls,'registerMember','(Ljava/lang/String;Ljava/lang/String;Ledu/unu/iist/emacao/xg2g/core/A
pplicationListener;)Ledu/unu/iist/emacao/xg2g/core/Member;');
if Mid= nil then
begin
Writeln('Can''t find method registerMember');
Exit;
end;
// Call the method with the giving parameters
arg0:=JNIEnv.StringToJString(PAnsiChar(name));
arg1:=JNIEnv.StringToJString(PAnsiChar(descriptionFile));
ARGS[0].l:=arg0;
ARGS[1].l:=arg1;
ARGS[2].l:=apListObject;

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 47

Result:=JNIEnv.CallObjectMethodA(AnonObject,Mid,@ARGS);
except
on E: Exception do
Writeln('Error: '+e.Message);
end;
end;

{*
* The implementation of Anon's getMember
*}
function XG2GWrapper.getMember(memberId: string) :JObject;
var
args:array[1..2] of JValue;
begin

// Create an instance of the Anon object


anonObject:=CreateJavaObject('edu/unu/iist/emacao/xg2g/core/Anon',Cls);
// Find the getMember method

Mid:=JNIEnv.GetMethodID(Cls,'getMember','(Ljava/lang/String;Ledu/unu/iist/emacao/xg2g/core/ApplicationListener;)Le
du/unu/iist/emacao/xg2g/core/Member;');
// Create an instance of the DelphiApplicationListener
apListOb-ject:=CreateJavaObject('edu/unu/iist/emacao/xg2g/delphi/DelphiApplicationListener',apListClass);
// create the argument
//JNIEnv.StringToJString(PAnsiChar(memberId));
args[1].l:=JNIEnv.StringToJString(PAnsiChar(memberId));
args[2].l:=apListObject;
// invoke the method with the giving parameters
Result:=JNIEnv.CallObjectMethodA(anonObject,mId,@args);

end;
procedure XG2GWrapper.sendMessage(member: JObject; chId: string; msg: string);
var args: array[1..2] of JValue;
ms:string;
begin
ms:=formatMessage(member,chId,msg,[]);
args[1].l:=JNIEnv.StringToJString(PAnsiChar(chId));
args[2].l:=JNIEnv.StringToJString(PAnsiChar(ms));

callMethod(member,'sendMessage','(Ljava/lang/String;Ljava/lang/String;)V',args);
end;
{I need to provide an implementation for this method}
procedure XG2GWrapper.receiveMessage(member: JObject; msg: string);
var args: array[1..1] of JValue;
begin
args[1].l:=JNIEnv.StringToJString(PAnsiChar(msg));;

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 48

callMethod(member,'receiveMessage','(Ljava/lang/String;)V', args);
end;

{I need to provide an implementation for this method}


procedure XG2GWrapper.createChannel(member: JObject; chName: string);
var args: array[1..1] of JValue;
begin
args[1].l:=JNIEnv.StringToJString(PAnsiChar(chName));
//args[2].l:=JNIEnv.StringToJString(PAnsiChar(chName));
callMethod(member,'createChannel','(Ljava/lang/String;)V',args);
end;
{I need to provide an implementation for this method}
procedure XG2GWrapper.destroyChannel(member: JObject; chId: string);
var args: array[1..1] of JValue;
begin
args[1].l:=JNIEnv.StringToJString(PAnsiChar(chId));
//args[2].l:=JNIEnv.StringToJString(PAnsiChar(chName));
callMethod(member,'destroyChannel','(Ljava/lang/String;)V',args);
end;
{I need to provide an implementation for this method}
procedure XG2GWrapper.subscribeChannel(member: JObject; chId:string; oId: string);
var args: array[1..2] of JValue;
begin
args[1].l:=JNIEnv.StringToJString(PAnsiChar(chId));
args[2].l:=JNIEnv.StringToJString(PAnsiChar(oId));
callMethod(member,'subscribeChannel','(Ljava/lang/String;Ljava/lang/String;)V',args);
end;
{I need to provide an implementation for this method}
procedure XG2GWrapper.unsubscribeChannel(member: JObject; chId: string; oId: string);
var args: array[1..2] of JValue;
begin
args[1].l:=JNIEnv.StringToJString(PAnsiChar(chId));
args[2].l:=JNIEnv.StringToJString(PAnsiChar(oId));
callMethod(member,'unsubscribeChannel','(Ljava/lang/String;Ljava/lang/String;)V',args);
end;
{I need to provide an implementation for this method}
procedure XG2GWrapper.unregisterMember(member: JObject);
begin
callMethod(member,'unregisterMember','()V',[]);
end;
{I need to provide an implementation for this method}
procedure XG2GWrapper.enableExtension(member: JObject; extType: string; chId: string; extName: string);
var args:array[1..3] of JValue;
ext:JObject;
begin

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 49

ext:=getExtensionType(extType);
if ext=nil then
Begin
Writeln('Unknown ExtensionType '+extType);
Exit;
end;
args[1].l:=ext;
args[2].l:=JNIEnv.StringToJString(PansiChar(chId));
args[3].l:=JNIEnv.StringToJString(PansiChar(extName));
callMe-
thod(member,'enableExtension','(Ledu/unu/iist/emacao/gateway/xmlUtil/ExtType$Enum;Ljava/lang/String;Ljava/lang/St
ring;)V',args);
end;
{I need to provide an implementation for this method}
procedure XG2GWrapper.disableExtension(member: JObject; extType: string; chId: string; extName: string);
var args:array[1..3] of JValue;
ext:JObject;
begin
ext:=getExtensionType(extType);
if ext=nil then
Begin
Writeln('Unknown ExtensionType '+extType);
Exit;
end;
args[1].l:=ext;
args[2].l:=JNIEnv.StringToJString(PansiChar(chId));
args[3].l:=JNIEnv.StringToJString(PansiChar(extName));
callMe-
thod(member,'disableExtension','(Ledu/unu/iist/emacao/gateway/xmlUtil/ExtType$Enum;Ljava/lang/String;Ljava/lang/St
ring;)V',args);
end;
{I need to provide an implementation for this method}
procedure XG2GWrapper.configureExtension(member: JObject; extType: string; chId: string; extName: string; data:
string; order: Integer);
var args:array[1..5] of JValue;
ext:JObject;
begin
ext:=getExtensionType(extType);
if ext=nil then
Begin
Writeln('Unknown ExtensionType '+extType);
Exit;
end;
args[1].l:=ext;
args[2].l:=JNIEnv.StringToJString(PansiChar(chId));
args[3].l:=JNIEnv.StringToJString(PansiChar(extName));
args[4].l:=JNIEnv.StringToJString(PansiChar(data));

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 50

args[5].i:=order;
callMe-
thod(member,'configureExtension','(Ledu/unu/iist/emacao/gateway/xmlUtil/ExtType$Enum;Ljava/lang/String;Ljava/lang
/String;Ljava/lang/String;I)V',args);
end;
{I need to provide an implementation for this method}
procedure XG2GWrapper.forwardMessage(member: JObject; chId: string; msg: string);
var args: array[1..2] of JValue;
begin
args[1].l:=JNIEnv.StringToJString(PAnsiChar(chId));
args[2].l:=JNIEnv.StringToJString(PAnsiChar(msg));
callMethod(member,'forwardMessage','(Ljava/lang/String;Ljava/lang/String;)V',args);
end;
{*the setPin method*}
procedure XG2GWrapper.setPin(member: JObject; pin: string);
var args: array[1..1] of JValue;
begin
args[1].l:=JNIEnv.StringToJString(PAnsiChar(pin));
callMethod(member,'setPin','(Ljava/lang/String;)V',args);
end;
{*The getMessage*}
function XG2GWrapper.getMessage(member: JObject; chId: string):string;
var args:array[1..1] of JValue;
begin
args[1].l:=JNIEnv.StringToJString(PansiChar(chId));
Result:='welcome';
end;
end.

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 51

C. PROGRAMMING LANGUAGES AND TOOLS USED BY GOVERNMENT APPLICATIONS

C.1. DETAILED LIST

AGENCY APPLICATION PROGRAMMING LANGUAGE / TOOL

AMCM Accounting System COBOL

AMCM HR System COBOL

AMCM Insurance Intermediaries COBOL

AMCM Liquidity System COBOL

AMCM Treasury System COBOL

CCC Fix Asset Management System Visual Basic

CCC Online Questionnaire ASP

CGPM Document Management System Delphi

CP Account System Visual Basic

CP Application Form System ASP.net

CP Document Flow System ASP

CP Personel System FoxPro

CP Support User Application ASP.net

DICJ Gaming income control system VB.Net

DSC Atendimento System Powerbuilder

DSC CEP Loan System Powerbuilder

DSC Cofre 2000 Powerbuilder

DSC EMS 2000 Powerbuilder

DSC Loja Powerbuilder

DSC MPost System Powerbuilder

DSC Pessoal System Powerbuilder

DSC Registro System Powerbuilder

DSC Subscription System Powerbuilder

DSCC Cadastre IS Delphi

DSCC Finanças Access

DSCC GDT Visual Basic

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 52

DSCC Road and Building Search System ESRI ArcIMS

DSCC PMS Oracle Developer 2000

DSCC SAB Access

DSE CA COBOL

DSE CEPA Delphi

DSE CO COBOL

DSE DETRI Delphi

DSE ID COBOL

DSE LC COBOL

DSE LI Delphi, COBOL

DSE PCU Delphi

DSE PI Delphi

DSE QT COBOL

DSEC A1CP Delphi

DSEC A1OR Delphi

DSEC A2RH Delphi

DSEC Statistical Information Processing System Delphi

DSEJ Accounting Visual FoxPro

DSEJ Asset Visual FoxPro

DSEJ Educational Information Visual FoxPro

DSEJ Financial Aids to Students Visual FoxPro

DSEJ Financial Grants to University Student Clipper

DSEJ Personnel Information System Visual FoxPro

DSF COB AS/400 RPG programming tools

DSF COM AS/400 RPG programming tools

DSF ConcPub AS/400 RPG programming tools

DSF GCO Delphi

DSF GPV Visual Foxpro

DSF IND AS/400 RPG programming tools

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 53

DSF IPR AS/400 RPG programming tools

DSF IVM AS/400 RPG programming tools

DSF Moveis Delphi

DSF OR AS/400 RPG programming tools

DSF Pat98 Delphi

DSF PRE AS/400 RPG programming tools

DSF REN AS/400 RPG programming tools

DSF SEL AS/400 RPG programming tools

DSF SOT AS/400 RPG programming tools

DSFSM Assets Management System Delphi

DSFSM Border Control System COBOL

DSFSM Budget Management system Delphi

DSFSM Enter and Exit Macao Inquiry system Delphi

House Allowance and Family Allowance Management


DSFSM System Delphi

DSFSM Human Resource Management System Delphi

DSFSM Immigration Management System COBOL

DSFSM Recruitment System COBOL

DSFSM Traffic Violation Record Management System Delphi

DSFSM Vehicle Lost and Found System Delphi

DSI Association Program Borland C++ Builder

DSI BIR Application Forms Printing Borland C++ Builder, C for AS400

DSI Counter Enrollment Program Borland C++ Builder, C for AS400

DSI Data Entry for Criminal Record and other Certificates Cobol for VSE(S/390)

DSI Data Entry Program for ID Card System Cobol for VSE(S/390)

DSI Data Entry Program for Travel Documents Cobol for VSE(S/390)

DSI Enrollment Report Printing Borland C++ Builder

DSI ID Card Data Checking Borland C++ Builder

DSI Print Address Borland C++ Builder

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 54

DSI Print RCR Cert Borland C++ Builder

DSI SMS Program Borland C++ Builder

DSI Stock Control of DSI Documents Borland C++ Builder

DSI Ticketing and Reservation System Borland C++ Builder

Acquisition of Public Works, Goods and Services Man-


DSSOPT agement System Delphi & Delphi 400

DSSOPT Construction Licensing System Delphi & Delphi 400

DSSOPT Document Register System COBOL

DSSOPT Electricity Licensing System Delphi & Delphi 400

DSSOPT Illegal Works Management System COBOL

DSSOPT Internal Web Page ASP.net

DSSOPT Inventory System Delphi & Delphi 400

DSSOPT Land Management System COBOL

DSSOPT Ordinary Budget Control System Delphi & Delphi 400

DSSOPT Personnel Management System COBOL

DSSOPT Pidda Budget Control System COBOL

DSSOPT Professionals/Companies Registration System Delphi & Delphi 400, COBOL

DSSOPT Purchasing System Delphi & Delphi 400

DSSOPT Staff Attendance System Delphi & Delphi 400

DSSOPT Suggestion, Complaint and Claim System Delphi & Delphi 400

DST Activities Calendar Visual FoxPro 6

DST Assiduidade Visual FoxPro 6

DST Consumable Delphi 6

DST Emissao de Recibo ASP

DST Emissao de Recibo Delphi 6

DST Fundo de Turismo Visual FoxPro 6

DST Horas Extraordinario Visual FoxPro 6

DST Intranet Consultation Visual FoxPro 6

DST Inventario Visual FoxPro 6

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 55

DST License Status System Delphi 7

DST Lista telefonica Visual FoxPro 6

DST Mailing List Visual FoxPro 6

DST Orcamento Regiao Visual FoxPro 6

DST Pessoal Visual FoxPro 6

DST Processo de Licenciamento Delphi 6

DST Visitor statistics Visual FoxPro 6

DSTE ACID FoxPro

DSTE BARCODE Delphi

DSTE COURSE Delphi

DSTE IMOSYS Delphi

DSTE ONSHIFT Delphi

DSTE PROCESSO FoxPro

FP DMS Access v.97/2000

FP Inventory Access v.97/2000

FSS Benefit Application Processing AS/400 Application development tools

FSS Contribution Processing AS/400 Application development tools

FSS Payroll AS/400 Application development tools

FSS Unemployment Allowance Application Processing AS/400 Application development tools

GAES Accounting System Access

GAES Book Management System Access

GAES Counseling Team Organizer Access

GAES CourseDB Access

GAES Higher Education (Macao) Database Access

GAES Job Management System ASP

GAES Student Counseling Database Access

GAES Student Enrollment Database Access

GDTTI Distribuicao de Documentos Delphi

GDTTI Ferias Delphi

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 56

GDTTI Geracao de Oficios Delphi

GDTTI GIS Delphi

GDTTI Impressao de Licencas Delphi

GDTTI Oficios Delphi

GDTTI Pesquisa de Documentos Delphi

GDTTI Requisicao Delphi

IACM Document Flow and Tracking System Delphi

IACM Driving License Management Sys Delphi

IACM Finance Management System Delphi

IACM Inventory Management of Museum Collection Delphi

IACM Movable Assets Management System Delphi

IACM Personnel Management System Delphi

IACM Project Management System Delphi

IACM Vehicle Management System Delphi

IAS Payroll Oracle Form, Report

IC Books Store Control System Access 2000/97

IC Budget System Access 2000/97

IC Cultural Association Register and Mngmt. Access 2000/97

IC Films Register System Access 2000/97

IC Intranet Data Maintenance System ASP .net

IC IT Equipment Control System Access 2000/97

IC Mailing Address control system VB.Net

IC Property Control System Access 2000/97

ID Finance System Delphi

ID Sport for all applications program Visual Basic

ID Venci DBASE

ID Venue Management System Visual Basic

IFT Accounting system VB.Net

IFT Inventory System VB.Net

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 57

IFT Mailing List System Visual Foxpro 3.0

IFT Newspaper Clipping System Visual Foxpro 3.0, ASP 2.0

IFT Personnel System Visual Foxpro 3.0

IFT SI System VB.Net

IH CU Delphi

IH FN Delphi

IH NR Delphi

IH US Delphi

ON Salario Access

ON Sinfon Access

ON Verbas Access

PJ Criminal Investigation Information System Oracle Developer, Delphi, VB

SA EDI Delphi

SA IPI Delphi

SA MIC Delphi

SA SUB Delphi

SAFP Car Management Delphi

SAFP Document Management Delphi

SAFP Electors Registration Delphi

SAFP Human Resource Statistics Delphi

SAFP Legal Document Achieving Access

SAFP Legislation Database (LegisMac) Delphi

SAFP Personnel Management Delphi

SAFP Post Registration Delphi

SAFP Profession Certification Delphi

SMG Modeling program C

SMG Obsmain Fortran

SMG Reporting Visual Basic

SMG Typhoon program Visual Basic

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 58

SS Accounting System Visual Basic

SS Archive Visual Basic

SS Document System Visual Basic

SS E.R. Visual Basic

SS Engineering Project , Management System Visual Basic

SS Equipment and New Inventory System Visual Basic

SS In-patients Visual Basic

SS Inventory Control System Visual Basic

SS Operation Visual Basic

SS Out-patients Visual Basic

SS Personnel & Payroll System Visual Basic

SS Pharmaceutical Affair Visual Basic

SS Primary Health Care Visual Basic

SS Property System Visual Basic

C.2. SUMMARIZED LIST

PROGRAMMING LANGUAGE / TOOL TOTAL

Access 13

Access 2000/97 6

Access v.97/2000 2

AS/400 Application development tools 4

AS/400 RPG 11

ASP 4

ASP .net 1

ASP.net 3

Borland C++ Builder 8

Borland C++ Builder, C for AS400 2

C 1

Clipper 1

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 59

COBOL 18

Cobol for VSE(S/390) 3

DBASE 1

Delphi 57

Delphi & Delphi 400 Count 8

Delphi & Delphi 400, COBOL Count 1

Delphi 6 Count 3

Delphi 7 Count 1

Delphi, COBOL Count 1

ESRI ArcIMS Count 1

Fortran Count 1

FoxPro Count 3

Oracle Developer 2000 Count 1

Oracle Developer, Delphi, VB Count 1

Oracle Form, Report Count 1

Powerbuilder Count 9

VB.Net Count 5

Visual Basic Count 21

Visual FoxPro Count 6

Visual Foxpro 3.0 Count 2

Visual Foxpro 3.0, ASP 2.0 Count 1

Visual FoxPro 6 Count 11

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 60

D. JAVA CLASSES FOR SENDING AND RECEIVING MESSAGES THROUGH THE COMMAND LINE

D.1. SEND CLASS

Java Class 1: Send

package edu.unu.iist.emacao.xg2g.legacy;

import java.io.File;
import java.io.FileInputStream;

import edu.unu.iist.emacao.xg2g.core.Anon;
import edu.unu.iist.emacao.xg2g.core.ApplicationListener;
import edu.unu.iist.emacao.xg2g.core.Member;
import edu.unu.iist.emacao.xg2g.util.GlobalVariables;

public class Send {

public static void main(String[] args) {


if (args == null || (args.length < 3)) {
System.out
.println("Error. You need to provide the id of the member and the name of the
file to send");
return;
}
// Get the member

File f = new File(GlobalVariables.getWorkFolder() + File.separator


+ args[0] + File.separator + "send" + File.separator + args[2]);
if (!f.exists()) {
System.out.println("Error. The file you provide doesn't exist");
// listener.recSendMessageReply(
// "Error. The file you provide doesn't exist");
System.exit(1);
}
ApplicationListener listener = new LegacyApplicationListenener();
Anon anon = new Anon();
Member m = anon.getMember(args[0], listener);
if (m != null) {
try {
FileInputStream stream = new FileInputStream(f);
byte[] result = new byte[stream.available()];
stream.read(result);
stream.close();

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 61

String message = new String(result);


// TODO I need to change this to add the possibility to add
// attachments
String[] attachment=null;
if(args.length>3){
attachment=new String[args.length-3];
for(int i=3;i<args.length; i++){
attachment[i-3]=args[i];
}
}
m.sendMessage(args[1], m.formatMessage(args[1], message, attach-ment));
System.exit(1);
} catch (Exception e) {
System.out.println("Error while sending your message "
+ e.getMessage());
}
}

D.2. RECEIVE CLASS

Java Class 1: Receive

package edu.unu.iist.emacao.xg2g.legacy;

import edu.unu.iist.emacao.xg2g.core.Anon;
import edu.unu.iist.emacao.xg2g.core.ApplicationListener;
import edu.unu.iist.emacao.xg2g.core.Member;

public class Receive {

public static void main(String[] args) {


if(args==null||(args.length==0)){
System.out.println("You should specify the id of the member ");
return;
}
ApplicationListener listener=new LegacyApplicationListenener();
Anon anon=new Anon();
Member m=anon.getMember(args[0],listener);
if(m!=null){
try {
Thread.sleep(10000);

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 62

System.exit(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

D.3. LEGACY APPLICATION LISTENER CLASS

Java Class 3: Legacy Application Listener - Receive Method

public void receiveMessage(String message) {


try {
Message m=new Message(message);
String memberId=m.getReceiverId();
// Verify if the directory for this member exists in the working directory of the application

File f=new
File(GlobalVariables.getWorkFolder()+File.separator+memberId+File.separator+"receive");
if((!f.exists())||(!f.isDirectory())){
// create the directory first
f.mkdirs();
}

File realFile=new File(f,memberId+df.format(new Date())+".xml");


FileOutputStream stream=new FileOutputStream(realFile);
stream.write(m.getUserDefinedMessage().getBytes());
stream.flush();
stream.close();
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
}
}

UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu


APPENDICES 63

E. GATEWAY CONFIGURATION FILE

E.1. GATEWAY CONFIGURATION FILE

Configuration File 1: Gateway Configuration File


64

UNU-IIST Center for Electronic Governance

S-ar putea să vă placă și