session-based web service programming for business...

86
Session-Based Web Service Programming for Business Protocols Project Final Report Michael Emmanuel Supervisor: Nobuko Yoshida

Upload: others

Post on 01-Oct-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Session-Based Web ServiceProgramming for Business

Protocols

Project Final Report

Michael Emmanuel

Supervisor: Nobuko Yoshida

Page 2: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Abstract

Session-based programming uses a type discipline to guarantee the correctnessof interactions taking place between communicating processes. Session-Java isa language under development, integrating object-orientated programming andsession types. In this project we will attempt to use the language to imple-ment several Business Protocols dealing with Web Services. Our goal is to testthe language and identify its properties relative to other approaches such asRMI, socket programming and COBRA. We want to rate it’s suitability in pro-gramming business interactions and it’s applicability to the increasingly populardomain of Web Services. The end product of our efforts will be our documentedimplementations of the business protocols including the implementation of acomplicated scenario taken from the paper “Web Services Choreography Re-quirements”[2].

Page 3: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Acknowledgements

I would like to thank a few people for their contributions to this project:

• Nobuko Yoshida for her precious guidance and support throughout theproject

• Raymond Hu for introducing me to SJ, putting up with me and for hiscontinuous support and encouragement

• Susan Eisenbach for her valuable advice, feedback and support.

Page 4: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Contents

1 Overview 11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.3 Structure of Report . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2 Background 42.1 Session Programming . . . . . . . . . . . . . . . . . . . . . . . . . 42.2 Merging Object Orientated with Session-Typed programming . . 62.3 Session-Java (SJ) . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.3.1 Main Properties . . . . . . . . . . . . . . . . . . . . . . . 72.3.2 Using SJ . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3 The two SJ versions used in this project 143.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.2 Quickstart Scenario . . . . . . . . . . . . . . . . . . . . . . . . . . 143.3 The differences in the two versions . . . . . . . . . . . . . . . . . 15

4 The TicketAgency Scenario 194.1 Variation 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

4.1.1 Description . . . . . . . . . . . . . . . . . . . . . . . . . . 194.1.3 Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . 204.1.2 Interactions . . . . . . . . . . . . . . . . . . . . . . . . . . 214.1.4 Implementation . . . . . . . . . . . . . . . . . . . . . . . . 214.1.5 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

4.2 Variation 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234.2.1 Description . . . . . . . . . . . . . . . . . . . . . . . . . . 234.2.3 Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . 234.2.2 Interactions . . . . . . . . . . . . . . . . . . . . . . . . . . 244.2.4 Implementation . . . . . . . . . . . . . . . . . . . . . . . . 264.2.5 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

4.3 Variation 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.3.1 Description . . . . . . . . . . . . . . . . . . . . . . . . . . 284.3.3 Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.3.2 Interactions . . . . . . . . . . . . . . . . . . . . . . . . . . 294.3.4 Implementation . . . . . . . . . . . . . . . . . . . . . . . . 304.3.5 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

4.4 Variation 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324.4.1 Description . . . . . . . . . . . . . . . . . . . . . . . . . . 32

Page 5: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

4.4.3 Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . 324.4.2 Interactions . . . . . . . . . . . . . . . . . . . . . . . . . . 334.4.4 Implementation . . . . . . . . . . . . . . . . . . . . . . . . 354.4.5 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

4.5 Variation 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384.5.1 Description . . . . . . . . . . . . . . . . . . . . . . . . . . 384.5.3 Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . 384.5.2 Interactions . . . . . . . . . . . . . . . . . . . . . . . . . . 394.5.4 Implementation . . . . . . . . . . . . . . . . . . . . . . . . 414.5.5 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

4.6 Scenario Review . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

5 Quote Request Scenario 455.1 Original Requirements . . . . . . . . . . . . . . . . . . . . . . . . 455.2 Design Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465.3 Specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

5.3.1 Buyer - Supplier Interactions . . . . . . . . . . . . . . . . 475.3.2 Supplier - Manufacturer Interactions . . . . . . . . . . . . 48

5.4 Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495.4.1 Buyer - Supplier . . . . . . . . . . . . . . . . . . . . . . 505.4.2 Supplier - Manufacturer . . . . . . . . . . . . . . . . . . . 51

5.5 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525.5.1 Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525.5.2 Location . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525.5.3 Supplier . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525.5.4 Buyer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605.5.5 Manufacturer . . . . . . . . . . . . . . . . . . . . . . . . . 64

5.6 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655.7 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

6 Evaluation 706.1 SJ Comparative Evaluation . . . . . . . . . . . . . . . . . . . . . 70

6.1.1 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . 706.1.2 Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . 716.1.3 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

6.2 SJ Protocols Evaluation . . . . . . . . . . . . . . . . . . . . . . . 726.2.1 Correctness . . . . . . . . . . . . . . . . . . . . . . . . . . 726.2.2 Scalability . . . . . . . . . . . . . . . . . . . . . . . . . . . 726.2.3 Difficulty . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

6.3 Project Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . 73

7 Conclusions and Future Work 757.1 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757.2 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

A Methods 78A.1 Buyer’s Sort Method . . . . . . . . . . . . . . . . . . . . . . . . . 79A.2 Buyer’s amendLists Method . . . . . . . . . . . . . . . . . . . . . 80

Page 6: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Chapter 1

Overview

1.1 Introduction

Web Services are rapidly increasing in complexity and range due to their wideapplicability to internet users and businesses, and the use of XML (ExtensiveMarkup Language) formalizing the description of data exchange. Recently, aneffort has been made to control communication between web services with theintroduction of new methods such as standardised Business Transaction Proto-cols. Session-Based programming uses a typing language to achieve that controland is said to be highly suitable for programming web service communication.This project aims to explore the concept through the language Session-Java.

Business transactions in traditional software engineering are understood tobe entities with a short life spam operating in a closely coupled context. Theyare designed for successful completions, without complications such as loss ofdata arising during exchange. Hence, with minimal control, thousands of trans-parent transactions can occur within a system every second without troublingthe programmer. The smooth operation of interaction between web services is,however, much harder to achieve. The reason behind that is that when we try toextend the concept of traditional transactions to a loosely coupled environmentsuch as the web we find that they’re unsuitable.

The situation becomes even harder if we’re dealing with applications of along life spam, running for hours or even days and almost inevitably resultingin a deadlock. Business to business interactions often require such long-livedtransactions. A need arises for new transaction implementations, more suitablefor the web. Protocols already exist but the recent blossoming of web services,combining more and more distributed services makes this a very important topicin today’s industrial world.

In this project we will be focusing on Session-Based Programming, a methodof controlling process interactions (represented by sessions). It works by speci-fying the intended process transaction protocol using session types and imple-menting the interaction using session operations. The session implementationswill then be verified with the session specifications to guarantee a correct imple-

1

Page 7: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

mentation and secure communication between web services. Session-Java (SJ) isan extension to Java implementing Session-Based Programming. The languageis still under development but a stable version of it exists and by programmingin it we’re planning to create several real life scenarios of web businesses in-teracting. Those scenarios can be used by the SJ designers as programmingparadigms or compared with similar implementations in other languages suchas for example the Java RMI.

We will focus on business scenarios but this should be a wide enough subspaceto allow us to test different aspects of the language. This will be the first timethat business communication of a sufficient depth will be implemented in SJ,so our scenarios aim to test multiple aspects of the language and enable us toidentify its pros and cons. Our priority is that by the end of the project wewill have produced complicated programs in SJ. Through these we’re aimingto confirm the suitability of Session-Java as an implementation of business tobusiness transactions. We want to explore the robustness of the language andthe scalability as scenarios vary in size but also complexity. In addition we willbe looking for things such as ease of programming in SJ, any limitations, bugsor non-implementable scenarios.

In fact, SJ is closely tied to the Web Services Choreography Working group[3],currently designing the Web Services Choreography Description Language[1](WS-CDL) aimed specifically at interactions amongst web services. The plan isthat SJ will be used as part of the implementation technologies for the language.Like UML with Java, this could possibly be directly translated to SJ code, andhence generate code skeletons. If, however, there exist any non-implementablescenarios in SJ then they will have to be overcome before that stage is reached.Results produced through this project could possibly have a direct impact onthe future development of SJ.

1.2 Contributions

• Through our project we have provided with some interesting documentedscenario variations (Chapter 4) to the TicketAgency example found in the“Web Services Choreography Description Language: Primer 1.0”[1] paper.We have shown how they are implemented using session programming andSJ. An analysis of the tradeoffs in design choices for the scenarios and theirimplementations in SJ is also included.

• We have also provided an implementation of the quote request use casefound in “Section[3.1.2] C-UC-002 - Quote Request” in the “Web ServicesChoreography Requirements”[2] paper (Chapter 5).

• Finally we hope that this report will provide some useful feedback to theSJ designers from a users viewpoint.

2

Page 8: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

1.3 Structure of Report

• We will first analyze the key work that this project is based upon in Chap-ter 2. This includes the key concepts of Session Programming (Section2.1) and the core language MOOSE (Section 2.2). We will then introduceSession-Java and explain the main syntax and session types (Section 2.3).

• An introductory example will follow where we will also exhibit the newadditions to SJ that have happened either just before, or during the courseof this project (Chapter 3).

• We will then move to implement variations to a “TicketAgency” Businessscenario, including a step-by-step analysis of the process of transformingeach scenario into an SJ protocol and then using SJ types to implementit (Chapter 4).

• The main deliverable of the project is the implementation of the “Sec-tion[3.1.2] C-UC-002 - Quote Request” use case in paper “Web ServicesChoreography Requirements”[2] in SJ (Chapter 5).

• An evaluation of both SJ and the project (Chapter 6) and conclusions andpotential further work (Chapter 7) conclude the report.

3

Page 9: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Chapter 2

Background

One of the main challenges of concurrent programming is the communication be-tween different computational processes. This holds regardless of whether we’redealing with concurrent processes executed sequentially on a single processor orprocesses exchanging information through the web as part of a business trans-action. To begin to understand Session-Java, we have to explore the theoreticalworks that are fundamental to its implementation.

2.1 Session Programming

In the “Language Primitives and Type discipline for structured communication-based programming”[5] paper the authors introduce a structuring method forcommunication-based concurrent programming. What is characteristic aboutthis method is the use of a type discipline as an fundamental tool used toensure compatibility of interaction patterns between processes throughout com-munication. Following is an overview of the main ideas of the paper proposal:

• The definition of a session as a chain of dual interactions. The collectionof sessions is a program. A session would be allocated a particular privateport called a channel, and all interactions belonging to the session wouldoccur within that channel.

• Value passing, label branching and delegation as communication primitives.

– Value Passing is synchronous message passing (standard as in otherprocess calculi)

– Label branching is a “purified” form of method invocation (not in-cluding value passing)

– Delegation is dynamic channel passing from one process to another,allowing for the structured distribution of a single session amongdifferent processes.

• The type discipline for the above communication primitives.

Remarks The regular constructs in concurrent programming (parallel compo-sition, name hiding, conditional and recursion) are also provided in the proposal

4

Page 10: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

without any noted alterations. Note that the channel is different from the usualport number and this was a conscious design decision by the authors to makethe programs have an explicit logical structure.

This proposal aims to take advantage of the fact that most errors in communication-based programming could be caught using this type discipline and this is theessential argument for using Session-based Programming, as we will see later.

Even though the typability of our programs might give an overhead compu-tational cost in implementation, by comparing interaction patterns of processeswe can detect potential incompatibility before we even engage in a transaction.Also, an additional high-level layer of protection is automatically created.

Enforcing types in program interactions introduces the concept of dual com-munication patterns. These are simply compatible patterns of data exchangebetween the programs. For example, the dual of a procedural call pattern of(input string - output double) would be (output string - input double).

In the paper the authors note that in it’s implementation, the proposal shouldbe used by embedding the communication constructs in the various program-ming languages used over the web to ensuring the different languages are com-patible. To this day, however, the concept has not reached that stage.

5

Page 11: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

2.2 Merging Object Orientated with Session-Typedprogramming

MOOSE, “a multi-threaded object oriented core language augmented with ses-sion types, which supports thread spawning, iterative sessions, and higher-ordersessions”, is a language proposed in the paper “Session Types for Object-Orientated Languages”[4]. The authors analyze how the concept of Session-typed programming can be incorporated to object orientated languages andproduce a complete design of a language that incorporates the concept, in-cluding its syntax, operational semantics and type system. Here are the maincharacteristics of MOOSE briefly described:

• The MOOSE programming style is similar to popular object orientatedlanguages

• Thread spawning, higher-order, conditional and iterative sessions are allsupported in order to provide the expressivity of common scenarios fromconcurrent programming, session type, and W3C[3] (Web ChoreographyGroup) environments.

• Special attention was given to guarantee type preservation. Linear usageof channels was enforced

• Threads never starve or deadlock during sessions, and the liveness propertyis maintained

Remarks As we discussed earlier, deadlocks are an important considerationwhen dealing with long-lived transactions that occur through the web. Theliveness property in threads is a remarkable aspect of MOOSE, that eliminatesthe deadlock possibility.For that property to hold, however, linear usage of channels has to be enforcedA critical issue for a full implementation of MOOSE would be the range ofscenarios programmable in it, i.e. whether the enforcement of linear usageof channels would result in a substantial sacrifice of implementable scenarios.This is going to be something we will be thoroughly examining in this projectin Session-Java.

6

Page 12: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

2.3 Session-Java (SJ)

2.3.1 Main Properties

We have seen the fundamentals of Session-Typed programming as well as themajor reasons behind it’s suitability. We have briefly seen that there have beenefforts to incorporate this to Object Orientated programming and the maindesirable properties that would arise from this merge. Session-Java is the firstfull implementation of a language for session-based distributed programming.The essential aims of MOOSE such as linear usage of channels and liveness aremaintained in Session-Java. Here are the main properties of SJ:

• Interaction patterns called protocols are specified in the using the typinglanguage and implemented using session operations

• Runtime validation of protocols using the typing language at method ini-tialization. This means that for any interacting programs SJ ensures thattheir protocols are dual, according to the concept of dual communicationpatterns described above.

• Verification between the specified protocols with the implementation of theprotocols. The specification of the protocols uses the session typing lan-guage and is written prior to the implementation uses session operations.The compiler framework compares the specification with the implementa-tion statically and programs only compile if the two are consistent.

• Support of session abstraction over TCP. Session operations are mapped tolower level communication primitives by the compilation-runtime frame-work.

SJ programs have a .sj extension. SJ includes it’s own compiler frameworkwhich means that producing a program in SJ would be compiled using the SJ(Polygon) compiler to create a class file like traditional Java but also the Javafile.Although a paper on SJ has already been published, the language is still underresearch and development.

2.3.2 Using SJ

Like the authors in “Session-Based Distributed Programming in Java”[6], we willillustrate the SJ syntax using the WS-CDL[3] use case found in “Web ServicesChoreography Requirements”[2]. This is an example of a Customer, Agency,Service scenario described below:

1. Customer begins an order session (s) with Agency specifying a desiredjourney and receiving a price for it from Agency. The customer can repeatthis interaction indefinitely for different journeys.

2. Customer either accepts or rejects price from agency

3. If customer accepts price

(a) The agency has to communicate with service and confirm the trans-action.

7

Page 13: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

(b) Service opens a session (s’) with customer and receives his addressto return a date of dispatch for the travel tickets. The customer isunaware that agency has delegated the session as he’s using the samesession channel.

4. If customer rejects price then the order session finishes

As the paper gives a very analytical view of the language and is the only sourceof documentation for programming in SJ, we will follow the approach of theauthors, and provide a more stripped down description of the major attributesof SJ.The protocols for the order session (between Customer and Agency) are specifiedbelow as placeOrder, which describes the interactions from Customer’s side, andacceptOrder, from Agency.

protocol placeOrder {

cbegin.

// client begins session.

![ // can iterate:

!<String>. // send String

?(Double) // receive Double

]*.

!{ // Select one of:

ACCEPT: !<Address>.?(Date),

REJECT:

}

}

(A) Order protocol: Customer side.

protocol acceptOrder {

sbegin.

//server begins session

?[

?(String).

!<Double>

]*.

?{

ACCEPT: ?(Address).!<Date>,

REJECT:

}

}

(B) Order protocol: Agency side.

• To begin with, the !<..> indicates sending something so in this case !<

String> in (A) means that that the customer would have to send a string.

• The ?(...) indicates receiving something and in this case ?(Double) in(B) means that the service would receive the string.

• [..]* indicates iteration.

• ![..]* in A indicates that the iteration occurs under the customer’s initia-tive while ?[..]* in B indicates that the iteration is not under the agency’sinitiative.

• !{...} in A means that the customer has a decision to make while ?{...} inB shows agency that the other party will decide which branch to choose.In our examples the customer’s options are ACCEPT and REJECT. In caseACCEPT is chosen the customer sends an address, receives a date and thesession terminates, while in case of REJECT the session terminates there.

Notes The two protocols are dual as is the spirit of Session-Typed program-ming. Also, there is no keyword for the ending of the session, but that is estab-lished implicitly. The different inputs are separated by dots except in the caseof branching where the options are separated by commas. The specification ofthe protocols will be followed by their implementation using session operations.

8

Page 14: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

begin c.request(), ss.accept() // Session initiation.

!<C> s.send(obj) // Object ‘obj’ is of type C.

!<S> s1.send(s2) // ‘s2’ has remaining contract S.

?(T) s.receive() // Type inferred from protocol.

!{L:T,..} s.outbranch(L){...} // Body of case L has type T, etc.

?{L:T,..} s.inbranch(){...} // Body of case L has type T, etc.

![T]* s.outwhile(boolean expr){...} // Outwhile body has type T.

?[T]* s.inwhile(){...} // Inwhile body has type T.

Figure 2.1: Session operations and their types (Copy from SJ paper[6])

Session sockets After declaring the protocols for the intended interactions,the next step is to create session sockets for initiating sessions and performingsession operations. There are three main entities:

• Session server socket of class SJServerSocket, which listens for sessionrequests, accepting those compatible with the specified protocol.

• Session Service of class SJService, which specifies the address of a sessionserver socket and the type of session it accepts; and

• Session socket of class SJSocket, which represents the endpoint (client orserver) of a session channel, through which communication actions withina session are performed. A session socket is used by a client to request theestablishment of a session to a server.

The session sockets and session server sockets correspond to standard socketprogramming equivalents, but include their associated session types and henceprovide different properties.In the first version of SJ, client sockets were tied to a session server-address atcreation, and could only make requests to that server. Now, however, the SJsocket is not required to be final and can be passed to someone else, as longas it loses its value when it does. This will be analysed further later. What isof great significance is that there do not exist multiple occurrences of the samesocket, as this would infringe the linearity property.Session server sockets accept server requests only if the requesting client’s pro-tocol is compatible to the server. Upon acceptance, the server will spawn it’sown session socket that will correspond to the opposing endpoint of the request-ing client socket, thus initiating the session. Any messages passed during thesession will have to be typed as per the protocols of the session.

Session server sockets Programs that offer session services, like Agency, usea session server socket to accept session requests:

SJServerSocket ss_ac = SJServerSocketImpl.create(acceptOrder,port);

Once the server socket is opened, the server can accept a session request by,

s_ac = ss_ac.accept();

where s ac is an uninitialized SJSocket variable. The accept operation blocksuntil a session request is received. The server then validates that the protocolrequested by the client is compatible with that offered by the server and returnsa new session socket, i.e. the server-side endpoint.

9

Page 15: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Session services and session sockets.

A session service identifies a server by its IP address and TCP port. At theCustomer, we set:

SJService c_ca = SJService.create(placeOrder, host, port);

A service inherits the type of the client side, in this case placeOrder. Servicescan be communicated to other parties, allowing them to request sessions withthe same server. Hence, inheritance can occur from both the server and theclient. Customer uses c ca to create a session socket:

SJSocket s_ca = SJSocketImpl.create(c_ca);

and request a session with Agency:

s_ca.request();

Assuming the server socket identified by c ca is open, request blocks untilAgency performs the corresponding accept. Then the requesting and accept-ing sides exchange session types, independently validate compatibility, and ifsuccessful the session between Customer and Agency is established. If incom-patible, an exception is raised at both parties (see ‘Session failure’ below).

Send and receive operations

After the session has been successfully established, the session socket s ca be-longing to Customer (respectively s ac for Agency) is used to perform the ac-tual session operations according to the protocol placeOrder. Static session typechecking ensures that this contract is obeyed.The basic message passing operations, performed by send and receive, asyn-chronously communicate typed objects. This mean that there are no restrictionson the sequence of operations. For example, we can have several sends before areceive and vice versa.

s_ca.send("London to Paris"); // !<String>.

Double cost = s_ca.receive(); // ?(Double)

Iteration

Iteration is abstracted by the two mutually dual types written ![...]* and?[...]*. [...]* expresses that sequence of interactions in [...] may be iter-ated zero or more times. These types are implemented using the outwhile andinwhile operations, which can together be considered a distributed version ofthe standard while-loop. In our example, placeOrder, ![!<String>.?(Double)]*,and its dual type at Agency is implemented as follows.

10

Page 16: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

boolean decided = false;

... // Set journey details.

s_ca.outwhile(!decided) {

s_ca.send(journeyDetails);

Double cost = agency.receive()

;

... // Make decision or

... // retry with different

details

}

s_ac.inwhile() {

String journeyDetails

= s_ac.receive();

... // Calculate cost.

s_ac.send(price);

}

Like the standard while-statement, the outwhile operation evaluates the booleancondition for iteration (!decided) to determine whether the loop continues orterminates. This decision is communicated to the program running the inwhile

(in this case, from Customer to Agency), synchronising the control flow betweentwo programs. This is why the inwhile loop has no condition. In chapter ?? wewe also introduce recursion in SJ.

Branching

In placeOrder, Customer’s protocol dictates !{ACCEPT: !<Address>.?(Date), REJECT:

}, with ! meaning that customer is the program making the decision. Customereither selects ACCEPT, leading into a (send address - receive data), or selectsREJECT which terminates the session.The branching happens using outbranch and inbranch. These, like the iterationcase with while loop, can be considered a distributed switch-statement. Here isthe implementation in our example:

if(want to place an order) {

s_ca.outbranch(ACCEPT) {

s_ca.send(address);

Date dispatchDate = s_ca.receive()

;

}

} else { // Don’t want to order.

s_ca.outbranch(REJECT) { }

}

s_ac.inbranch() {

case ACCEPT: {

...

}

case REJECT: { }

}

The condition of the if-statement in Customer (whether or not Customer wishesto purchase tickets) determines which branch will be selected at runtime. Thebody of ACCEPT in Agency is completed in ‘Session delegation’ below.

Session fail Sessions are implemented within session-try constructs:

try (s_ac, ...) {

... // Implementation of session ‘s_ac’ and others.

} catch (SJIncompatibleSessionException ise) {

... // One of the above sessions could not be initiated.

} catch (SJIOException ioe) {

... // I/O error on any of the above sessions.

} finally { ... } // Optional.

11

Page 17: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

This results in graceful failure if a run-time error occurs, and results in usefulinput from the compiler.

Session delegation.

If Customer is happy with one of Agency’s quotes, it will select ACCEPT. Thiscauses Agency to open a second session with Service, over which Agency dele-gates to Service the remainder of the conversation with Customer, as specified inacceptOffer. After the delegation, Agency relinquishes the session and Servicewill complete it. Since this ensures that the contract of the original order sessionwill be fulfilled, Agency need not perform any further action for the delegatedsession; indeed, Agency’s work is finished after delegation.At the application-level, the delegation is exposed to only Agency and Service;Customer will proceed to interact with Service unaware that Agency has leftthe session, which is evidenced by the absence of any such action in placeOrder.The session between Agency and Service is specified by the following mutuallydual protocols:

protocol delegateOrderSession {

begin.!<?(Address).!<Date>>

}

protocol receiveOrderSession {

begin.?(?(Address).!<Date>)

}

Delegation is abstracted by higher-order session types where the specified mes-sage type is itself a session type; in this example, ?(Address).!<Date>. Themessage type denotes the unfinished part of the protocol of the session beingdelegated; the party that receives the session will resume the conversation, ac-cording to this partial protocol.In terms of implementation, delegation is naturally represented by sending thesession socket of the session to be delegated. Continuing our example, Agencycan delegate the order session with Customer to Service by

case ACCEPT: {

SJService c_as = ... // delegateOrderSession.

SJSocket s_as = SJSocketImpl.create(c_as);

s_as.request();

s_as.send(s_ac); // Delegation: Agency has finished with s_ac.

}

and Service receives the delegated session from Agency by

SJServerSocket ss_sa = SJServerSocketImpl.create(..., port)

SJSocket s_sa = ss_sa.accept();

SJSocket s_sc = s_sa.receive(); // Receive the delegated session.

Service then completes the session with Customer.

Address custAddr = s_sc.receive();

Date dispatchDate = ... // Calculate dispatch date.

s_sc.send(dispatchDate);

As SJ is a project that is still under development, it is continuously beingchanged. Some notable changes at the time of writing is the renaming of theServerAddress into SJService. Also, in protocol definition, begin has been re-placed by sbegin for server protocols and cbegin for client protocols. Anotherchange in SJ is the introduction of the term noalias.

12

Page 18: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Noalias Objects

If an object is defined as noalias, it only has one reference to it. This wouldmean that no pointers for that object can exist.

public void passing {

noalias String m = ‘‘Legal

operation’’;

String n;

n = m; // m is now null

}

Correctly passing a noalias object

public void illegal {

final noalias String m = ‘‘

Illegal operation’’;

String n;

n=m;

}

Illegal operation

We see from the above example that passing the noalias object from variablem to n would make m null. final noalias objects behave as final objects regularlydo; their value cannot be altered. Note that protocol and SJService objects canonly be declared as final noalias. SJSocket objects on the other hand have tobe declared as noalias, but not necessarily final. These restrictions have beenset to ensure that the linearity of channel usage, the advantages of which werebriefly discussed in the MOOSE language section.

Protocol Reference

A completely new element is the ability to refer to protocols from within otherprotocols. This protocol can now be referred to from within another protocolusing the operator @. Also, the dual of the protocol can be automatically becalculated and referred to using the ˆ operator. Here is an illustration of thisconcept.

final noalias protocol rp

{

sbegin.?(@(p)).?(String)

}

Receiving protocol

final noalias protocol rdp

{

sbegin.?(^(p)).?(String)

}

Receiving dual of protocol

Note that the ?(String) operation has only been included to illustrate how SJprovides the functionality to extend the called protocol p. We can also seethat p is used in the example in high order message passing i.e. to describe adelegation. Since the protocol p is received in both examples here, protocolsrp and rdp would be inside programs that inherit the session as opposed to aprogram that delegates it. These changes to SJ will be further analysed in theupcoming sections.

13

Page 19: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Chapter 3

The two SJ versions used inthis project

3.1 Overview

My first encounter with SJ was via the quickstart scenario created by Ray-mond Hu[7]. In this scenario we have a server program called Alice and a clientprogram called Bob that establish a session and interact by sending a String toeach other.

The version of SJ used to construct these two programs was a more stableversion that the one now under development. This was also the version that Ioriginally used to program in SJ, as the stability it provided me gave me theopportunity to familiarize myself with the fundamental concepts of the languageand make my own mistakes, without having to worry that a bug in the languagewas responsible for any problems with the programs.e.g. an error message from the compiler.

Note however, that this stable version had limitations in the programs whichcould be created in it as some language constructs had not been implementedin it. This was the reason why when the scenarios I was to implement be-gan to get more complicated, I had to switch between the two versions. I willbe illustrating the differences between the two versions through the quickstartscenario.

3.2 Quickstart Scenario

This scenario is very basic but once again illustrates the duality of two protocols:

protocol BobToAlice {

begin.?(String).!<String>

}

Quickstart protocol: Client side.

protocol AliceToBob {

begin.!<String>.?(String)

}

Quickstart protocol: Server side.

14

Page 20: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

3.3 The differences in the two versions

In this version of SJ, we notice that both protocols are initiated with a begin.

command. However, it was later decided by the programmers that the protocolsfor the client and server programs should be distinguished and this was imple-mented by using:sbegin. //server protocol

cbegin. //client protocol

to initialise the two protocols respectively (as described before). Another pointis that while the protocol used to be defined as: protocol p

we now define it as: final noalias protocol p

The final keyword is the same as the regular JAVA final and simply meansthat the protocol can never be re-defined at any point throughout the program.The noalias keyword has been created by the SJ developers and it means that“there can never exist more than one” versions of the protocol, as shown insubsection (2.3.2).These two keywords ensure that the only operators which can be used to passa reference to a protocol are @ and ^ and that the protocol cannot be passedto a variable by value (noalias keyword), and also that once a reference to aprotocol exists, the protocol cannot change, which would create discrepanciesbetween different references (final keyword).

It is also clear to see that for any protocol, the client side of the protocol isfully defined by the server side and vice versa. In the new version of SJ, we canhence only define one side of the protocol in a specified class (in this case I havearbitrarily chosen the server side) and use the @ and ^ operators (Subsection2.3.2, Protocol Reference) to define both protocols in their respective classeswithout ever having to exclusively define the dual of the protocol.As an implemented illustration:

public final noalias protocol

AliceToBob {

sbegin.!<String>.?(String)

}

Quickstart protocol: Server side.located in class Protocols

We define a new class Protocols and insert one of our protocols in there. Wecan now define the two protocols as follows:

final noalias protocol

BobToAlice {

^(Protocols.AliceToBob)

//dual reference to AliceToBob

//equivalent to BobToAlice

}

Quickstart protocol: Client side.

final noalias protocol

AliceToBob {

@(Protocols.AliceToBob)

//direct reference to

AliceToBob

}

Quickstart protocol: Server side.

Even though the quickstart is quite a basic protocol, one can see the benefitsthis would bring about:

15

Page 21: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

• This would save a programmer a lot of time from defining the dual of aprotocol, which would be unnecessary.

• During development, in a big program which includes complicated inter-actions it would be much easier for a programmer to alter the protocolsonce from a central class (such as Protocols), rather than have to changethem both at the client and the server classes.

• Finally, it is quite intuitive in terms of object-orientated programmingto have the full protocols in a separate class, which also rids the clientand server classes of big bunches of code that do not form part of themainstream code of the programs, making them easier to scan throughand disambiguous.

Moving on to the implementation of the protocol, and starting with the serverside, we have:

SJServerSocket ss = null;

The definition of the SJServerSocket remains as it was previously shown (Sec-tion: 2.3.2, Session Server Sockets), however the implementation has beenchanged to:

final noalias SJServerSocket ss;

Just like with the protocols, the server socket cannot be altered or referenced to.This makes sense, we wouldn’t want two server sockets listening for the samesession request. Also, changing the server socket at any point throughout ourprogram could bring up many undesired complications.In Alice, we proceed with setting up the server socket to listen for potentialincoming sessions at a specified port (say 1234), using the AliceToBob protocol:

try {

ss = SJFServerSocket.create(AliceToBob, 1234);

...

There used to be two ways in which the server socket could be created, using

ss = SJFServerSocket.create(AliceToBob, 1234); or

ss = SJRServerSocket.create(AliceToBob, 1234);

These two differ only in how they handle delegation. Suppose a session existsbetween party S1 and C, and we delegate the session from party S1 to S2. TheSJF uses the forwarding protocol in which any lost messages from C are receivedby S1, they are forwarded to S2 before the connection C-S1 is substituted byC-S2. The SJR uses the resending protocol in which lost messages are cachedby C and resent to S2 after the new connection C-S2 is established.

However, we no longer need to worry about these two types. The details ofthe delegation are now being modularised within the SJ Runtime in a waytransparent to the programmer. Once again the syntax has now changed to :

try (ss){ //try(ss) as opposed to a regular try statement

ss = SJServerSocketImpl.create(AliceToBob, 1234);

...

16

Page 22: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Up to this point, Alice (our server) has created a server socket and is ready tolisten to any incoming requests. The way we proceed is by creating an SJsocket,which, as described in (subsection 2.3.2, Session sockets) represents an endpointof the session channel:

SJSocket s = null;

try (s) {

s = ss.accept();

...

Now Alice is listening on the port 1234 and is ready to proceed with the protocol,which is implemented much as explained in subsection 2.3.2. The new imple-mentation of the SJSocket is almost the same for the server with the exclusionof the = null part, and including final noalias:

final noalias SJSocket s;

try (s) {

s = ss.accept();

...

I will now proceed to analyse key points in Bob (our client). Firstly, the clientmust create an SJService taking parameters the protocol, host and port:

SJServerAddress c =

SJServerAddress.create(BobToAlice, "localhost", 1234);

This has now been changed to:

final noalias SJService c =

SJService.create(BobToAlice, "localhost", 1234);

//SJService = SJServerAddress

We note that other than the renaming of SJServerAddress to SJService, thereare no differences to the properties of the two at least as far as the programmeris concerned. The reasons for requiring SJService to be final noalias are thesame for SJServerSocket.Bob would then proceed to create an SJSocket, the opposing endpoint to thesession channel with respect to the SJSocket in Alice:

SJSocket s = SJFSocket.create(c);

try (s) {

s.request();

...

Bob is now ready to proceed with the protocol implementation just as describedin the background section (2.3.2). The s.request(); has been slightly alteredand in the new version it would be created as follows:

final noalias SJSocket s; // no .create(c) command

try (s) {

s = c.request(); // define which service c we

... // are using by c.request()

where c was the SJService created before. This change is because, just like theSJServerSocket, there is only one type of SJSocket now.A few minor changes were also made to the names of the SJ packages and thecommands to compile and run SJ programs, as illustrated below:

17

Page 23: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

//To compile a program:

bin/sjc ...

//To run a program:

bin/sj ...

//Imported libraries

import sj.runtime.*;

import sj.runtime.net.*;

Old Version

//To compile a program:

bin/sessionjc ...

//To run a program:

bin/sessionj ...

//Imported libraries

import sessionj.runtime.*;

import sessionj.runtime.net.*;

New Version

18

Page 24: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Chapter 4

The TicketAgency Scenario

The TicketAgency Scenario, as described in section (2.3.2), covers a lot of cen-tral aspects of SJ, as well as Session-Based Programming. The scenario has aprotocol very common for business interactions and so we decided to producea number of variations to the scenario, increasing in complexity and more andmore diverging from the original scenario, in order to test different propertiesof SJ.

4.1 Variation 1

In words the first variation is as follows:

4.1.1 Description

1. Customer begins an order session (s) with Agency specifying a desiredjourney and receiving a price for it from Agency.

(a) The customer can repeat this interaction indefinitely for differentjourneys.

(b) Customer identifies which journey is desired through the use of out-branch

2. Customer either accepts or rejects price from agency

3. If customer accepts price

(a) The agency has to communicate with service and confirm the trans-action.

(b) Service opens a session (s’) with customer and receives his addressto return a date of dispatch for the travel tickets. The customer isunaware that agency has delegated the session as he’s using the samesession channel.

4. If customer rejects price then the order session finishes

What has been altered from the original scenario is that the customer nowselects a journey, whereas in the original code the same interaction took place

19

Page 25: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

regardless of what the first !<String> sent was. In a different language, theprogrammers first response could be to program Agency to receive the desiredjourney from the customer and then depending on what was received, send acorresponding price. i.e.

String travDetails = s_ac.receive();

Double cost = getPrice(travDetails);

//Method getPrice(String d) determines value to be sent

s_ac.send(cost);

Protocol implementation

We would then have multiple if statements to branch between the different typesof travel methods:

private Double getPrice(String travelMethod)

{

...

if(travelMethod.startsWith("Bus")){

...

}

else if(travelMethod.startsWith("Train")){

...

}

else if(travelMethod.startsWith("Plane")){

...

}

Function getPrice(String t)

4.1.3 Protocols

We can however incorporate this decision in our protocol through the use ofoutbranch. We would then alter the scenario to:

protocol p_ac

{

begin.

?[

?(String).

!<Double>

]*.

?{

ACCEPT: ?(Address).!<Date

>,

REJECT:

}

}

Original scenario for Agency

protocol p_ac

{

begin.

?[

?{

TRAIN:

BUS:

PLANE:

}.!<Double>

]*.

?{

ACCEPT: ?(Address).!<

Date>,

REJECT:

}

}

New scenario for Agency

20

Page 26: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

4.1.2 Interactions

Customer Agency Service

s

Double

accept

Repeat

until

Customer

is satisfied

Address

s’

?(Address).!(Date)

Date

s

reject

s

Customer Agency

T

s

lab

s

A B

A B

A B

A B

A

A requests session s with B

A sends type T to B

A can choose to repeat this

part of the session

A selects lab at B

A and B close s

s’

1a

2

3a

3b

4

2

Train

Plane

Bus 1b

Figure 4.1: Overview of interactions for variation 1

An equivalent change, omitted here would happen to the scenario for the cus-tomer. The delegation pattern has not been altered in any way and so delegationfrom Agency to Service remains the same, both in protocol and implementation,as the original scenario.Although there aren’t any real benefits of this change in protocol, the situationwould be quite different if different interactions took place depending on thetype of ticket. This would be quite likely if we were dealing with a real lifesituation. For example, if we were to include a discount to the customer pro-vided he is eligible for it, a train ticket might require a Railcard Identificationnumber while an aeroplane ticket might require a frequent flyers card. The useof inbranch - outbranch provides a synchronized decision by the two parties tofollow a specified set of interactions and saves a lot of work.

Figure 4.2 illustrates the interactions that would possibly have to take placein a different language in order to achieve the same effect. We note that de-pending on the underlying transport mechanism the final confirmation messagemight not be required.

4.1.4 Implementation

Changes in implementation for this variation would only occur in Customer andAgency. We enter the String order as an argument to the class Customer whothen decides how to outbranch. This was programmed on the first version of SJ.Here are the outbranch statements below:

21

Page 27: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Customer Agency

String

Receive and decipher Agency’s

choice

Boolean

Integer

Receive and decipher

acknowledgement message

Prepare for upcomming

collaboration and send boolean to

confirm

Send method of travelReceive method of travel

and choose how to proceed

Send Integer corresponding

to choice

Figure 4.2: Potential message exchanges in a different language

if(travelMethod.startsWith("Bus"))

{

s_ca.outbranch(BUS)

{

System.out.println(‘‘Requested

Bus Service’’);

}

}

else

if(travelMethod.startsWith("Train"))

{

s_ca.outbranch(TRAIN)

{

System.out.println(‘‘Requested

Train Service’’);

}

}

else

if(travelMethod.startsWith("Plane"))

{

s_ca.outbranch(PLANE)

{

System.out.println(‘‘Requested

Plane Service’’);

}

}

Double cost = s_ca.receive();

//In new version:

//Double cost=(Double) s_ca.receive();

Customer choice reflected through outbranchcase

Double cost;

s_ac.inbranch()

{

case(BUS):

{

cost =

getCost(‘‘Bus’’);

}

case(TRAIN):

{

cost =

getCost(‘‘Train’’);

}

case(PLANE):

{

cost =

getCost(‘‘Plane’’);

}

}

s_ac.send(cost);

Agency receives customer choiceand acts accordingly

While in the old SJ version casting of the receiving attribute was not obligatory,in the new version it is and so the statement in Customer would have to be:

Double cost = (Double) s_ca.receive();

22

Page 28: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

4.1.5 Comments

This program is an example of nested branch statements, as the customer out-branches within the [...]* loop. SJ can cope with this and no errors werebrought up during the compilation of Agency and Customer, which means thatthe compiler correctly opted that the two protocols and their implementationsmatch.

4.2 Variation 2

4.2.1 Description

1. Customer begins an order session (s) with Agency specifying a desiredjourney and receiving a price for it from Agency. The customer can requesta train or aeroplane journey.

2. Agency opens the session s1 with service (either train, or aeroplane agent)and delegates to sub-agent through s1 the interactions with Customerremaining for s. Service then sends the price for the journey to Customer.

3. Customer either accepts or rejects price from Service

4. If an offer is accepted, Customer sends a delivery address, and Servicereplies with the dispatch date for the purchased tickets. The transactionis now complete.

5. Customer cancels the transaction if no quotes were suitable and the sessionterminates.

Our second variation is regarding the session delegation from the Agency to theService. In this case the Agency receives the journey type from the Customerand instead of replying with a price, it delegates the session to the correspondingService straight away. The responsibility of sending the Customer a price is nowupon the service.In this situation and unlike the first variation, we will not be using inbranch

- outbranch for this choice by the Agency. The Agency will instead keep thedecision transparent to the customer, which is perhaps more appropriate as thecustomer should not be concerned with the inner workings of Agency. Thiscapability is provided by SJ.

4.2.3 Protocols

To exhibit this property, we have chosen to keep the protocols between Customerand Agency the same as the original scenario. The only difference will be in theCustomer-Service protocol:

23

Page 29: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

4.2.2 Interactions

Customer Agency Service A

s

String

Double

accept

Address

[airoplane] s’

Date

s

reject

s

T

s

d

s

A B

A B

A B

A B

A

A requests session s with B

A sends type T to B

A can choose to repeat this

part of the session

A selects d at B

A and B close s

4

Identify request

type (Airoplane/

Train/Bus)

1

2

P(A) =

!<Double>.

?{

accept: ?(Address).!<Date>,

reject:

}

Service T

[train] s’

CustomerService

(A|T)

String.P(A)

Session s’

[o] s’ If o then A requests

session s with BA B

3

3

5

Figure 4.3: Overview of interactions for Variation 2

24

Page 30: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

//implemented in new SJ version

final noalias protocol p_as

{

//Send remaining scenario

//between Customer and Agency

cbegin.

!< !<Double>

.?{

ACCEPT:

?(Address).!<Date>,

REJECT:

} >

//Then send customer order

.!<String>

};

(AS) Agency - Service Protocol

//First define the

//high order message

final noalias protocol p

{

!<Double>.

?{

ACCEPT:

?(Address).!<Date>,

REJECT:

}

}

//Then include it

//in the scenario

final noalias protocol p_sa

{

sbegin.?(@(p)).?(String)

}

(SA) Service - Agency Protocol

In fact the !<String> corresponding to passing the customer order is only re-quired in case the order contained any additional information other than thetype of journey, that the Service requires in order to reply with a price. As areminder to the reader we note that the

!< !<Double>

.?{

ACCEPT: ?(Address).!<Date>,

REJECT:

}

>

in (AS) corresponds to a high order message. The !<...> means that it is theAgency that is passing the high order message and everything inside it is theprotocol of the session that the Service should establish with the Customer. In(SA) we see a subtle way of defining a protocol containing high order messagesby first defining them and then including them in the protocol.The Service - Agency protocol is in this case included in both the ServiceT andServiceA classes (Train and Aeroplane services respectively) but just as in theQuickstart scenario (section 3.2), it can be included in a class Protocols andaccessed by all Service classes that would use it.

25

Page 31: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

4.2.4 Implementation

noalias SJSocket s_ac;

//SJSockets don’t always have to be final

try (s_ac)

{

...

if(travDetails.startsWith("Train"))

{//delegate to train service that has addr_s, port_s

final noalias SJService c_as = SJService.create(p_as,

addr_s, port_s);

final noalias SJSocket s_as;

try (s_as)

{

s_as = c_as.request();

s_as.send(s_ac); //Pass Remaining Protocol

//No more operations on s_ac allowed.

s_as.send(travDetails); //!<String>

}

...

}

Session Delegation Implementation

Despite the fact that session delegation takes place, the program still remainsvery simple. Actually delegating the protocol is straightforward and only con-sists of passing the socket to service:

s_as.send(s_ac);

We have included the whole segment of code to illustrate the following point.The code below is almost identical to the if statement above, with the exceptionof the address (or host) and the port parameters of the Aeroplane Service whichare of course different than the ones for the Train Service.

else

{

final noalias SJService c_asa = SJService.create(p_as,

addr_sa, port_sa);

final noalias SJSocket s_asa;

try ( s_asa)

{

s_asa = c_asa.request();

s_asa.send(s_ac);

s_asa.send(travDetails);

}

...

}

Delegating session to Aeroplane Service

However, trying to reuse code by only defining the SJService c_as in the if andelse statements, will not work. We illustrate below to attempts to save havingto rewrite the same chunk of code.If one attempts to define SJService first and then allocate it’s value like so:

26

Page 32: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

final noalias SJService c_as;

if (...) {c_as = SJService.create(p_as, addr_s, port_s);}

else { c_as = SJService.create(p_as, addr_sa, port_sa);}

...

then the program will not compile and the compiler will bring the followingerror:

tests\src\michael\scenario1a\Agency.sj:67: Local variable "c_as"

multiply

defined. Previous definition at ...

because c_as was declared final. If one attempts to define c_as inside theif/else statement:

if (...) {

final noalias c_as = SJService.create(p_as, addr_s, port_s);}

else {

final noalias c_as = SJService.create(p_as, addr_sa, port_sa);}

...

the program will still not compile, this time with a different error:

tests\src\michael\scenario1a\Agency.sj:80: Could not find type,

field, or

local variable "c_as".

s_as = c_as.request();

^--^

Despite the fact that c_as is created in both the if and else statements (andhence any channel up to line 80), the compiler does not accept that c_as hasbeen created.The conclusion is that there’s no easy way out, the same chunk of code has tobe repeated, when we’re dealing with final noalias SJ types.There’s not a lot of interest worth noting in service other than the fact thatwhen receiving a high order type casting must take place and in the case of aprotocol, the type of protocol must be explicitly defined:

s_sc = (@(p)) s_sa.receive();

Where p is as defined in the protocols section (SA). This is another reason whyit is good practice to first exclusively write the protocol to be delegated andthen include it in the final protocol.

4.2.5 Comments

This variation to the scenario lets Agency simply act as a coordinator class,responsible for channelling the incoming session requests. This is common inmany business collaborations where the different services provided by a businessare all available to customers through a centralised access point.A peculiar bug existed in class Agency and this actually happened again in afew programs later on. The class Address, which is a serializable class (usedby the Customer to send his address to Service), is passed by the Agency toService, as part of the protocol delegation. At first it seemed that an entry ofAddress such as:

private Address a = new Address("dummy");

27

Page 33: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

must exist in Agency, in order for the compiler to recognise that the class Ad-dress exists, and not bring an error during compilation. This was actually notedby Raymond Hu as a potential bug. If the class Address is the first one to becompiled, however, the problem seems to disappear.

4.3 Variation 3

4.3.1 Description

1. Customer begins an order session (s) with Agency specifying a desiredjourney (either Train, Bus or Plane)

2. Agency opens a session (s1) with a Subagent and delegates session s alongwith the order sent by the Customer

3. If Subagent can provide the service

(a) Subagent sends price to Customer

(b) Customer either accepts or rejects price from Subagent

(c) If customer accepts price

• Subagent receives the customer’s address to return a date ofdispatch for the travel tickets and the order is completed

(d) If Customer rejects price the session is closed

4. If Subagent cannot provide the service, he delegates it to another subagentalong with the Customer order. Go back to step 3.

5. The delegation from Subagent to Subagent continues until there are noSubagents left

We now assume a different organisational structure for the Agency, where sub-agents are more independent and can provide any Service. The Agency doesnot know in advance what services each of it’s subagents can provide at anygiven time and delegates to an arbitrary subagent. Any subagent would dealwith the customer himself if possible, or delegate to the next subagent if not.We are hence dealing with a chain of delegation.

4.3.3 Protocols

The protocols for Customer and Agency remain unchanged as the original sce-nario. This is another example of how the internal workings of an organisationremain transparent to the customer. One would think that because Session-based programming involves protocols where the whole session is described, theprogrammer would have to go through the pain of having to change the protocoland/or its implementation for the customer, in order to reflect the way in whichhis session is handled. Yet again we have an example to show that this is notthe case.The change comes within the subagents. Each sub-agent has to forward theprotocol:

28

Page 34: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

4.3.2 Interactions

Customer Agency Subagent A

s

Strings1

Subagent B

[unavailable] s2

Subagent T

[unavailable] s3

[available] s’

[available] s’

[available] s’

String.P(A)

String.P(A)

String.P(A)

2

1

3

3

3

4

4

s1

s2

s3

Figure 4.4: Overview of interactions for Variation 3

Double

accept

Address

Date

s

reject

s

T

s

d

s

A B

A B

A B

A B

A

A requests session s with B

A sends type T to B

A can choose to repeat this

part of the session

A selects d at B

A and B close s

3c

3d

P(A) =

!<Double>.

?{

accept: ?(Address).!<Date>,

reject:

}

CustomerSubagent

(A|B|T)

Session s’

s’ Session s’ occurs

between A and B

[o] s’ If o then Session s’ occurs

between A and B

[o] s’ If o then A requests

session s with BA B

3b

3b

3a

Figure 4.5: Legend

29

Page 35: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

final noalias protocol p

{ //p is reused twice

!<Double>.

?{

ACCEPT: ?(Address).!<Date>,

REJECT:

}

}

final noalias protocol p_at

{

//subagent a to subagent t

cbegin.

!<@(p)>

.!<String>

}

The subagent receives p from Agency and then forwards it to the next subagentin case it cannot service the customer itself. Since no change to p occurs, thechain of delegation remains “stateless”. Any subagent receiving p does notknow how many subagents p has gone through before it came to him. As far asthe subagent is concerned, receiving p from the 100th subagent is the same asreceiving it from the Agency themselves.All that remains now is to implement the subagents to accept and pass del-egation. At this point we stress that our protocols for this variation are notadequate to deal with failure of the chain of subagents to deal with the cus-tomer’s request. We will do that at a latter stage.

4.3.4 Implementation

For any subagent (but the last) we have to possibilities. Either we can deal withthe customer ourselves, or we have to delegate. The function getAvailability(

String s); checks if the subagent can deal with the customer request.

if(!getAvailability(travDetails)){//Can’t deal with customer

System.out.println("Requested service unavailable in SubagentA");

noalias SJSocket s_st;

final noalias SJService a_at = SJService.create(p_at, addr_t,

port_t);

final noalias SJSocket s_at;

try (s_at)

{

s_at = a_at.request();

s_at.send(s_sc); //Delegate to next in chain

s_at.send(travDetails); // Send method of travel as well

System.out.println("Delegated to: " + addr_t +" " + port_t);

}

finally { }

}

else{

.... //Implement protocol as usual

30

Page 36: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

The above piece of code is almost identical to all the subagents. This makes itvery easy for the programmer. Every subagent-name can be a subclass of theclass subagent. A method similar to the above can be defined in the superclassand inherited by all subagents with the correct parameters for the host and portof the subagent we are delegating to. The method getAvailability(String s)

could be declared abstract in the superclass.Other than this, all we have to change in the implementation of the scenariowould be the host, port of the first subagent to which agency delegates and alsomake a final subagent either fail gracefully or never fail to serve the customer.

4.3.5 Comments

If a company decided to change it’s inner structure and the way in which cus-tomer requests are handled, this should have minimal effect on the customer,which is the case with Session-Based Programming. It’s also quite intuitive forthe programmer to know that if he wants to change the company inner work-ings, he doesn’t have to worry about the customer, and only edit the protocolsand code within the company classes.

The fact that we can delegate the same protocol an arbitrary number of times,makes it much easier to add another subagent to the chain of delegation. Theonly changes that would have to be made would be informing subagents of thisnew addition, and informing the added subagent of where he has to delegate incase he cannot deal with the customer. It is as easy as adding a variable to aLinkedList.

In spirit with the MOOSE (section 2.2) core language, SJ not only intro-duces Session-Based Programming but also has all the benefits of an Object-Orientated language. In this case, by making an abstract class subagent, theimplementation of our chain of delegation is simplified. The actual methodin which to construct the super and subclasses is exactly the same as regularJAVA, with no extra effort involved. The programmer can then concentrate onimplementing the individual characteristics for each subagent.

This example is more suitable for markets where the availability of services of-fered is constantly changing. This could be because of a very large customer baseor due to the market being extremely volatile, with prices constantly changing.An example of such a market would be the stock market.

If we assume that the Agency distributes shares equally among it’s subagentsso that they can service their respective clients, updating the Agency with theavailability of any given shares would be impractical.

Also, if the Agency was to attempt to make an educated choice about where todelegate by getting the availability for a Service by each subagent, it would findit very difficult. This is because then the subagents would have to commit to theavailability value that they provide the agency until it makes a decision. Theeffect of this action would be that they would be unable to sell any productsof the particular Service in the meanwhile, and in a sector such as the stock

31

Page 37: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

exchange, this could cost a lot of money. The best option would then be todelegate, as per this scenario.

A limitation of this scenario would be that the possibility of all subagentsbeing unable to provide a quote has not been accounted for. This issue is easyto resolve when we’re using Session-Based programming and will be addressedin the next variation.

4.4 Variation 4

4.4.1 Description

1. Customer begins an order session (s) with Agency specifying a desiredjourney (either Train, Bus or Plane)

2. Agency opens a session (s1) with a Subagent and delegates session s alongwith the order sent by the Customer

3. If Subagent can provide the service

(a) Subagent sends price to Customer

(b) Customer either accepts or rejects price from Subagent

(c) If customer accepts price

• Subagent receives the customer’s address to return a date ofdispatch for the travel tickets and the order is completed

(d) If Customer rejects price then the order session finishes

4. If Subagent is not the last of the chain of delegation and cannot providethe service, he delegates it to another subagent along with the Customerorder. Go back to step 3.

5. If Subagent cannot provide the service and is the last of the chain heinforms the client that the Agency is unable to offer the service he hasrequested and the session finishes

This is an extension of the previous variation to the scenario (section 4.3) anddeals with the possibility that the Agency is unable to deal with the Customer’srequest. Ideally the Subagent should be able to deal with this on their own. Itwould become quite messy if they had to start traversing the chain of delegationbackwards. We could, on the other hand, assume that each Subagent knows howto contact the Agency directly and begin a session with them but we will showthat this is not necessary in this situation.

4.4.3 Protocols

Unlike previous extensions, the Customer - Agency protocol will have to bealtered in this scenario. This is not because of the change in the way the Agencyhandles its request but due to the fact that in previous scenarios we assumedfor simplification that the Agency had unlimited supply of services and coulddeal with all requests coming its way.

32

Page 38: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

4.4.2 Interactions

Customer Agency Subagent A

s

String

s1

Subagent B

[unavailable] s2

Subagent T

[unavailable] s3

[available] s’

[available] s’

[available] s’

String.P(A)

String.P(A)

String.P(A)

2

1

3

3

3

5

4

[unavailable]

[unavailable] noticket

s

4

s1

s2

s3

Figure 4.6: Overview of interactions for Variation 4

33

Page 39: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Double

accept

Address

Date

s

reject

s

T

s

d

s

A B

A B

A B

A B

A

A requests session s with B

A sends type T to B

A can choose to repeat this

part of the session

A selects d at B

A and B close s

3c

3d

P(A) =

!{

ticket:

!<Double>.

?{

accept: ?(Address).!<Date>,

reject:

},

noticket:

}

CustomerSubagent

(A|B|T)

Session s’ s’ Session s’ occurs

between A and B

[o] s’ If o then Session s’ occurs

between A and B

[o] s’ If o then A requests

session s with BA B

3b

3b

3a

Figure 4.7: Legend

We will now have an outbranch statement in the protocol, after Agency re-ceives the order from the Customer. Through it the Agency will inform theCustomer whether or not it can provide a service. The Agency knows that thiswill be done by the Subagents but as far as the Customer is concerned, the onlysession he has to know about is the one with Agency.

34

Page 40: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

final noalias protocol p_ac

{//Agency to customer

sbegin.

?(String)

.!{

TICKET:

!<Double>.

?{//Nested branching

ACCEPT:

?(Address).!<Date>,

REJECT:

},

NOTICKET:

}

}

(AC) Agency - Customer Protocol

final noalias protocol p

{//delegated protocol

!{

TICKET:

!<Double>

.?{

ACCEPT:

?(Address).!<Date>,

REJECT:

},

NOTICKET:

}

}

final noalias protocol p_sa

{ //subagent - agency

sbegin.?(@(p)).?(String)

}

final noalias protocol p_ab

{//subagent a to subagent b

cbegin.

!<@(p)>.!<String>

}

(SP) Subagent Protocols

In listing (AC) the Agency is the party who decide whether the ticket can orcannot be provided, and hence have the outbranch statement around the optionsTICKET, providing a ticket andNOTICKET, unable to provide a ticket.This will correspond to the outbranch statement while the customer will beimplemented by an inbranch statement. Something new in this variation is thatwe have nested branch loops, and it’d be interesting to see if SJ can cope withthis. In listing (SP), the delegated protocol p has been changed to reflect thechanges to the Agency - Customer scenario but the principle is the same, theSubagent receives the remaining protocol and if necessary, delegates it furtherdown the chain.

4.4.4 Implementation

An easy mistake to make (or that I made) in the initial attempt to program aSubagent, might be to try and follow the protocol step by step as:

if (getAvailability(travDetails))

{

s_sc.outbranch(TICKET){....// follow protocol as listing below};

}

else

{

s_sc.outbranch(NOTICKET){...//session with Customer ends};

}

35

Page 41: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

However we must remember that the Customer is only informed that no ticket isavailable if none of the Subagents can provide a ticket. Whereas the if statementpart of the code above is correct, the else statement is only correct in the caseof the very last Subagent in the chain of delegation.Hence, for the rest of the Subagents the implementation would be:

if(getAvailability(travDetails))

{

s_sc.outbranch(TICKET)

{

...

s_sc.send(cost);

s_sc.inbranch()

{

case ACCEPT:

{

storeInDatabase((Address) s_sc.receive());

....

s_sc.send(date);

}

case REJECT: { System.out.println("Price Rejected"); }

}

}

}

else { ... //delegate }

with the delegation part inside the else statement being almost identical to theone in (SA).Due to the curly brackets around each inbranch case and inside the outbranch

statements there is no ambiguity to the programmer of what the above codewould mean. As I later found out, there were no problems in compiling orrunning the program either. SJ dealt with nested branching without any pecu-liarities.Other than it’s respective change in protocol, no change in the implementationof Agency was required. The implementation of customer is has to be alteredto match the new protocol.

...

s_ca.send(trav_method);

s_ca.inbranch()

{

case TICKET:

{... // follow protocol }

case NOTICKET:

{... // session ends here }

}

These changes in implementation are straightforward. By changing the protocolwe know that there have to be changes made to both parties involved in it. Asan example, for every

!{...}

added to the protocol, we must add an outbranch statement to the party imple-menting it, in this case Agency. And for every outbranch statement in Agency,

36

Page 42: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

we know that there must be a corresponding inbranch statement in Customer(the other party participating in the protocol) due to the duality of the protocol.These facts can act as pointers while programming and can make the task ofknowing which parts of the program to edit, even in a complicated scenario,easier.

4.4.5 Comments

There were no problems encountered with trying to achieve nested branchingin SJ. Although in previous scenarios the regular commands_at.send(s_sc) was used to delegate a session, in this variation I came acrossthe command s_at.pass(s_sc). Both of these work, with the latter one probablyonly used to stress the semantics of delegation, i.e. that we’re not just passinga regular object.

Three Subagent classes existed for the implementation of this protocol. Twoof them delegated the scenario to the next Subagent while the last one usedoutbranch to inform the Customer that the service could not be provided. Let’stake as an example ServiceT (the last subagent in the chain), and ServiceB(oneof the other subagents). Upon compilation, the SJ compiler statically checksthat the protocols of each class match with the implementation.In the case of ServiceB and classes that delegate a protocol:

• The compiler checks the that up to the point of delegation, any imple-mentation of the protocol matches the protocol itself.

• Once ServiceB has delegated the protocol, the compiler checks that noother operations upon the socket delegated have been performed

• No error is brought up for incomplete implementation of the protocol.

In the case of ServiceT and classes that don’t involve delegation:

• The compiler checks that the implementation of the protocol is correct.

• If the implementation of the protocol is incomplete, the compiler bringsan error.

The compiler is therefore relying on the fact that the programmer will notattempt to run the classes ServiceB and ServiceA without having completedthe implementation of the protocol in ServiceT and without it running.If that happens and a program tries to delegate to ServiceT then we will triggeran exception, as with any client program trying to reach a server that is not inoperation, in most languages. The operation of the compiler is therefore quitesound.Another few important points about the compiler are that

• In any error involving protocol implementations, the compiler messageusually consists of what SJ constructs it expected to find (according tothe protocol) and what it did find.

• Upon runtime, when the connection with the dual (regarding the proto-col) class is being established, the compiler dynamically checks if the twoprotocols match.

37

Page 43: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

• If the two protocols don’t match, the compiler again brings an error mes-sage informing us of where exactly the two protocols mismatch.

4.5 Variation 5

4.5.1 Description

1. Customer begins an order session (s) with Agency specifying a desiredjourney (either Train, Bus or Plane)

2. Agency opens a session (s1) with a Subagent and delegates session s alongwith the order sent by the Customer

3. If Subagent can provide the service

(a) Subagent sends price to Customer

(b) Customer either accepts or rejects price from Subagent

(c) If customer accepts price

i. Subagent receives the customer’s address to return a date ofdispatch for the travel tickets and the order is completed

ii. Subagent opens a session with Agency and sends confirmationthat the sale has been completed

(d) If Customer rejects price then the order session finishes

4. If Subagent is not the last of the chain of delegation and cannot providethe service, he delegates it to another subagent along with the Customerorder. Go back to step 3.

5. If Subagent cannot provide the service and is the last of the chain

(a) Subagent informs the client that the Agency is unable to offer theservice he has requested and the session finishes

(b) Subagent informs Agency that no sale took place

In this case we program the Agency to receive a confirmation from the Subagentthat the customer has a sale has taken place. Many businesses require to beinformed of every transaction completed by each Subagent. As an example,Agency could be a supplier for the Subagent and by receiving a notificationevery time a sale is made, it can then calculate when the Subagent would needto be re-stocked.Although here we only deal with sequentially running sessions, multiple sessionsoperating concurrently in a program is an important part of SJ and will beanalysed further.

4.5.3 Protocols

Calculating the protocols for this variation is a little different than what hasbeen shown before. In our current variation s the session between Agency andSubagent involves the Agency delegating the session with the Customer to Sub-agent. The delegated session has to then be completed before notifying the

38

Page 44: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

4.5.2 Interactions

Customer Agency Subagent A

s

String

Double

accept

Address

s1

Date

s

reject

s

3ci

3d

Subagent B

[unavailable] s2

CustomerSubagent

(A|B|T)

Session s’

Subagent T

[unavailable] s3

[available] s’

[available] s’

[available] s’

String.P(A)

String.P(A)

String.P(A)

2

1

3

3

3

5a

4

3b

3b

3a

[unavailable][unavailable] noticket

s

4

s_fin

AgencySubagent

(A|B|T)

Session s_fin

s_fin

sale

Integer

String

s_fin

s_fin

s_fin

s_fin

nosale

s_fin

s1

s2

s3

3cii

3cii

3cii

5b

Figure 4.8: Overview of interactions for Variation 5

39

Page 45: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

T

s

d

s

A B

A B

A B

A B

A

A requests session s with B

A sends type T to B

A can choose to repeat this

part of the session

A selects d at B

A and B close s

P(A) =

!{

ticket:

!<Double>.

?{

accept: ?(Address).!<Date>,

reject:

},

noticket:

}

s’ Session s’ occurs

between A and B

[o] s’ If o then Session s’ occurs

between A and B

[o] s’ If o then A requests

session s with BA B

Figure 4.9: Legend

Agency, and simply keeping the session between Agency and Subagent openwhile Customer and Subagent interact is impractical. This is especially so be-cause of the chain of delegation we already have setup, which would mean thateach time a Subagent delegates to the next, he would also have to delegate thesession with the Agency.

We will hence simply create a new session from the Subagent to the Agency,leaving the existing protocols intact. We assume that the notification can takeplace by the Subagent sending an Integer and a String (!<Integer>.!<String>)to the Agency corresponding to the quantity and the types of tickets sold.

final noalias protocol p_sa2

{//Subagent’s protocol

cbegin.!<Integer>.!<String>

}

The Subagent is the party who initiates/requests the session (client), and it willdo so when it completes the transaction with the Customer.

We point out that the case of the no Subagent being able to provide a tickethas not been explicitly resolved through the above protocol. We can probablyget around that by, say, the final Subagent sending an Integer with value zeroand a dummy string, meaning that a sale did not go through. However in thespirit of Session-based programming, and because it’s better practice, that issueshould be resolved through the second protocol which should read:

final noalias protocol p_sa2

{//Subagent’s protocol

cbegin.

!{

SALE:

!<Integer>.!<String>

NOSALE:

40

Page 46: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

}

}

4.5.4 Implementation

The Agency must become ready to accept the new session from a Subagent assoon as it has delegated the original session.

try (ss_ac)

{//Serversocket for session with Customer

...

try (s_ac)

{//Socket for session with Customer

...

try (s_as)

{//Socket for first session with Subagent

s_as = c_as.request();

s_as.pass(s_ac);

s_as.send(travDetails);

//Now we have finished the old session,

//we begin the listening for the new one

final noalias SJServerSocket ss_sa;

try (ss_sa)

{//Serversocket for second session with Subagent

ss_sa = SJServerSocketImpl.create(p_sa, port_sa);

noalias SJSocket s_sa;

try (s_sa)

{//Socket for second session with Subagent

s_sa = ss_sa.accept();

s_sa.inbranch()

{

case SALE:

{

Integer sales = (Integer) s_sa.receive();

String stype = (String) s_sa.receive();

System.out.println("Sales = " + sales + "Type = " +

stype);

}

case NOSALE: { }

}

catch{...}

...

SJ seems to have no problem in dealing with us beginning the new session insidethe try statement for the session with the Customer. The Agency, being theserver in the session does not have to worry about which host the request for thesecond session is coming through; all it has to do is listen on the specified port.This means that it will accept a session request from any of the Subagents.

The Subagent will need to create the second session with the Agency insidethe implementation of it’s session with the Customer. We have to rememberthat the Subagent only contacts the Agency if it can serve the Customer andthis happens within an inbranch statement.

41

Page 47: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

try (ss_sa)

{//Sessionsocket for session with Agency

...

try (s_sc, s_sa)

{//Sockets for session with Customer and Agency

...

//First get Subagent-Customer protocol from Agency

s_sc = (@(p)) s_sa.receive();

//Implement session with Customer

if(getAvailability(travDetails))

{

s_sc.outbranch(TICKET)

{

...

s_sc.inbranch()

{

case ACCEPT:

{

... //Interact with customer

final noalias SJService c_sa2 = SJService.create(p_sa2,

addr_a, port_sa2);

noalias SJSocket s_sa2;

try (s_sa2)

{//begin second session with Agency

s_sa2.outbranch(SALE)

{

s_sa2 = c_sa2.request();

s_sa2.send(new Integer(no_sales));

s_as2.send(Stype);

}

}

finally { }

...

The Subagent will start the new session with Agency in the case the Customeraccepts his quote and the order is completed. Otherwise it will delegate thesession as normal. If we had not changed the protocol to deal with the trans-action never being completed, the Agency would be left waiting for a Subagentto contact it forever.The final Subagent would have the additional responsibility of creating a sessionwith Agency if it cannot provide a quote for the Customer:

else

{

System.out.println("Requested journey not available in Last

Subagent");

final noalias SJService c_sa2 = SJService.create(p_sa2, addr_a,

port_sa2);

noalias SJSocket s_sa2;

try (s_sa2){

s_sa2 = c_sa2.request();

s_sa2.outbranch(NOSALE){ }

}

...

42

Page 48: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Some details are missing, like for example that the Subagent contacting theAgency does not provide any identification. Also security measures to ensurethat the sale has indeed taken place. However, these details are deemed to beout of scope for this project and their implementation would add nothing to ourscenario in terms of SJ.

4.5.5 Comments

Although the scenario by which the Subagent notifies the Agency is quite trivial,the tricky part is actually establishing the session between the two parties. Oncewe have achieved that we can implement any protocol, as shown in previousvariations.

If the Agency would be the party initiating the second session with the Sub-agent, then actually locating which Subagent made the sale in the chain ofdelegation would be very difficult.

The concept of Session-based programming might appear to have limitationswhen it comes to running many different sessions between parties. This variationis only a basic example of the flexibility that SJ can provide the programmer.As we will show later, the concurrent execution of many sessions originatingfrom a single party is possible.

In fact, programming Agency to be a server for the Subagent in this waywould be impractical in a real life scenario. This is because during the timeit is waiting for the Subagent to contact it, it is unavailable for any customersthat request sessions with it. If we were to stick with our implementation whichshould create a thread from Agency through which it will listen for a Subagentconfirming a sale, while a different thread should listen for a Customer initiatinga new transaction. However at this stage I did not have the knowledge toconstruct such programs. Those types of implementations will be illustratedlater.

4.6 Scenario Review

The TicketAgency scenario is an example of a business offering web servicessimilar to the way many businesses operate. We had seen how a programmerwould implement this scenario using the concepts of Session-based programmingintertwined with Object-Orientated programming through the original imple-mentation by Raymond Hu.In our variations of the scenario we tried to show the process of implementinga scenario in stages.

1. Beginning from the design stage, the programmer must first consider howinteractions between all parties participating in the scenario should beformed.

43

Page 49: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

2. Next the protocols have to be defined accordingly, with attention given tothe duality of each session.

3. By implementing the protocols the main skeleton of the program will havebeen completed

4. Any local computations and other properties of the programs not regard-ing the sessions can then be coded.

As the scenarios increase in size and complexity, directly implementing theprotocols after we have defined them might be an awesome task. It would bequite helpful if at first the programmer deals with trivial protocols, to achievecompilation of the program with all the sessions set up, and only then movingon to implement the correct protocols.

We have so far focused on the protocols themselves, and how each scenariowould be transformed into a protocol. We tried to show that any set of inter-actions between two parties can be directly transformed into an SJ protocol.Mastering this is an important basis for a programmer wishing to move on withSession-based programming.

Effort was also given into using as many of the SJ session types as possible.Some examples are inbranch - outbranch, outwhile - inwhile, delegation. Wetried to nest and intertwine these in a variety of ways in order to identify anyproblems with the compiler (but failed to find anything worth mentioning).

Although SJ is still in development, the writer has failed to find any majorissues with it. A couple of minor points would be that it is currently necessarythat for any if statement we include an else, regardless of whether it is empty ornot. Otherwise the compiler will bring an error message. Although in regularJAVA when the if statement consists of only one command we can omit thebrackets around it, in SJ this would bring an error. In general the programmershould include brackets pretty much everywhere he’s supposed to even if in somecases he could get away without doing so in JAVA.

SJ is an implementation of the MOOSE core language. The latter specificallyrequires its implementation (and hence SJ) is a multi-threaded language and sup-ports supports thread-spawning, iterative and higher-order sessions. Althoughwe have dealt with the latter through delegation, we haven’t touched the subjectof thread-spawning nor iterative sessions yet. This is a very important propertyof SJ, as shown in the last variation (sec:v5) and we will go deep into it later.

44

Page 50: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Chapter 5

Quote Request Scenario

5.1 Original Requirements

The Quote Request scenario was taken from Section[3.1.2] “C-UC-002 - QuoteRequest” in the Web Services Choreography Requirements[2] paper preparedby the Web Services Choreography Working Group[3] in March 2004.It is about a buyer interacting with multiple suppliers further interact withmultiple manufacturers in order to get and provide a quote for some goods orservices.The steps of the interaction exactly as given in the paper are given below:

1. A buyer request a quote from a set of suppliers.

2. All suppliers receive the request for quote and send requests for bill ofmaterial items to their respective manufacturers.

3. The suppliers interact with their manufacturers to build their quotes forthe buyer. The eventual quote is then sent back to the buyer.

4. EITHER

(a) The buyer agrees with one or more of the quotes and places the orderor orders. OR

(b) buyer responds to one or more of the quotes by modifying the quotesand sending them back to the relevant suppliers.

5. EITHER

(a) The suppliers respond to a modified quote by agreeing to it andsending a confirmation message back to the buyer. OR

(b) The supplier responds by modifying the quote and sending it backto the buyer and the buyer goes back to step 4. OR

(c) The supplier responds to the buyer rejecting the modified quote. OR

(d) The quotes from the manufacturers need to be renegotiated by thesupplier. Go to step 3.

45

Page 51: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

The paper[2]’s specification also includes the following diagram:

Figure 5.1: [Section 3.1.2, Fig 2] from paper: Quote Request relationships

Although no mention was made to the number of Buyers-Suppliers-Manufacturerson the scenario description, the diagram is part of the specification and so weneed to maintain these relationships within our implementation.Although the specification forms the “founding stone” of the scenario, someflexibility is left for the programmer’s implementation. An example of this isthe step: The suppliers interact with their manufacturers to build their quotesfor the buyer. The exact interaction pattern is left for the programmer to decide.Before we move into coding, we therefore need to specify the scenario further.

5.2 Design Issues

We identify a few of the “tricky” points of the scenario for the user to bear inmind:

• We have to deal with the many-to-many relationship between manufactur-ers and suppliers which could cause problems. For example, a manufac-turer M provides a quote Q for supplier S1 and S2 and while the supplierS1 is processing the quote, S2 purchases something from M. If S1 wishes

46

Page 52: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

to purchase from M at price Q, that price may no longer be available asM could have no more goods or services to sell.

• There exist an arbitrary number of suppliers and manufacturers. To simu-late the scenario we must pass the number of suppliers and manufacturersas a parameter to our programs, and ensure that they work properly forany number of suppliers/manufacturers.

• We need to define a way in which the suppliers will be matched with theirrespective manufacturers. As the figure 5.1 illustrates, not all suppliershave access to the same manufacturers.

• The customer must receive quotes from multiple suppliers. The best wayof doing this would be through threads. As a general “rule” a differentthread should be created for each session a class participates in.

• The multiple threads running at any one time will create the need forsynchronization.

• A manufacturer will be accepting session requests from multiple suppliers.These will possibly differ in type. For example, one supplier might wantto finalize a purchase while another might want to simply request a quotefrom the same manufacturer. Accepting any type of request is an issuethat will have to be addressed.

5.3 Specifications

Always in line with the original requirements from the Web Services Choreogra-phy Requirements[2] paper, we extend the scenario to form a concrete example.In our implementation we will therefore assume that the buyer is the TFL. Weassume that the agreement with the company producing the Oyster cards so faris coming to an end. The TFL requests quotes from several companies in orderto find the cheapest supplier and make an agreement with them.For the purposes of this example, oyster cards are made of the actual card, andthe chip contained in it. These are the two material items that the suppliers willrequest from their manufacturers. If a supplier doesn’t have a manufacturer forone or both of those items, it has to declare itself unable to provide a quote.We now need to specify the interactions between all the parties involved in thescenario. As the Manufacturer never deals with the Buyer directly we are onlyleft with the Buyer - Supplier and Supplier - Manufacturer interactions.

5.3.1 Buyer - Supplier Interactions

We have the following steps:

1. The buyer sends his order simultaneously to all of the suppliers

2. For each supplier EITHER

(a) He cannot provide a quote and notifies the buyer accordingly

(b) He can provide a quote in which case he sends the quote and quantityof items he can provide at that quote

47

Page 53: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

3. The buyer then compares all of his quotes and adds in shortlist “buyList”the price or prices that are the cheapest and can satisfy the quantity hehas demanded. He adds the rest to shortlist “negotiationList”

4. While there exist quotes in negotiationList:

(a) For all the quotes that are in negotiationList the buyer negotiatesthe quote with the supplier for a price better than what he currentlyhas in his buyList.

(b) The supplier either accepts, modifies or rejects the negotiated price.

i. If the supplier accepts, he is added to the buyList and we eithermove a supplier from buyList to negotiationList or reduce thequantity which we’re planning to purchase from him.

ii. If the supplier modifies the negotiated price either

A. The modified price is good enough, and he’s added to buyList.We either move a supplier from buyList to negotiationList orreduce the quantity which we’re planning to purchase fromhim.

B. The modified price is not good enough, and the buyer re-negotiates with him.

iii. If the supplier rejects, he’s removed from negotiationList

(c) The shortlists buyList and negotiationList are edited accordingly.

5. Buyer buys from suppliers in buyList enough to satisfy his demandedquantity.

5.3.2 Supplier - Manufacturer Interactions

As we have described before, we will have to find a way for the supplier to iden-tify which of the manufacturers he is he is connected with. That is merely a partof simulating the scenario. For the purposes of the interactions between supplier- manufacturer we will omit that process, which will however be analysed lateron.

To agree upon a quote the supplier and manufacturers interact as shown:

1. For every manufacturer supplier sends an order and receives a quote andquantity for that order

2. Supplier sorts the manufacturers depending on what they manufactureinto chipList and cardList.

3. For every manufacturer in chipList supplier accepts, negotiates or rejectstheir offer:

(a) If the supplier doesn’t have enough quotes to satisfy the buyer’s de-mand (for that item) he accepts, otherwise he accepts rejects or mod-ifies the manufacturer’s quote at his own discretion

(b) In case the supplier negotiates the manufacturer’s quote, the manu-facturer either

48

Page 54: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

i. Accepts the offer, supplier could potentially return and purchaseat this price.

ii. Modifies the offer. Go back to the beginning of step 3.

iii. Rejects the offer, negotiations fail.

4. Do the same as step 3 for every manufacturer in cardList

5. Pick the best manufacturer cardm and chipm out of cardList and chipList

6. To provide the customer with the final quote, return the sum of the pricesfrom cardm and chipm and add the suppliers profit

Notice that the supplier does not purchase anything from the manufacturers atthis stage. The interactions are only aimed to create a quote for the buyer’sorder. The buyer will then consider quotes from all suppliers as shown in theinteractions above before closing a deal.

When the buyer wants purchase e.g. 5 oyster cards with a supplier, thesupplier then purchases 5 cards from his chosen card manufacturer and 5 chipsfrom his chosen chip manufacturer.

When a supplier provides the buyer with a quote it commits to that quote.This means that if the buyer then wants to purchase at that quote and thesupplier finds out that the manufacturer has increased his price, he still has tosell to the buyer even if it means losing money.

5.4 Protocols

As we have described in the previous examples, Session-Based programming canbe used to provide encapsulation of the company structure within a company.The situation is no different in this case, despite the increased complexity ofthe scenario. We can deal with the Buyer - Supplier and Supplier - Manufac-turer sessions independently as far as producing the protocols is concerned. Wewill only include one part of each protocol which is enough to describe the in-teractions for each session. The dual can be calculated as shown in previouswork.

49

Page 55: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

5.4.1 Buyer - Supplier

public static final noalias protocol p_bs

{//Buyer - Supplier protocol

cbegin.

!{//identify whether new or old supplier

NEW: !<String>.

?{//supplier can provide quote or not

YES:

?(Double).?(Integer) ,

NO:

},

OLD:

!{//negotiate with or buy from supplier

NEGOTIATE:

!<Double>.

?{//supplier responds to negotiation

ACCEPT: ,

MODIFY: ?(Double) ,

REJECT:

},

BUY:

?(Double).?(Integer)

.!{//deal with issue of discrepancy

YES:

!<Integer> ,

NO:

}

}

}

}

(BS) Buyer - Supplier Protocol

Although we only have one session protocol for all the interactions betweenBuyer and Supplier we have used the session type .! for the Buyer to havecontrol over what type of interaction he wants with the Supplier. This canbe seen as having several protocols merged into one, with the benefit that theimplementation will be much easier as we will show later. Through this choicewe deal with accepting any type of request.

The NO: option in the NEW: case would occur when a Supplier notifies theBuyer that he cannot provide a quote. In case the Buyer negotiates the quote,he will send the negotiated price to the Supplier and await for his response,indicated by the .? part.

We note that in the BUY: case, a handshake occurs with the Supplier providingits current quote and quantity, which may have changed from it last interactionwith the Buyer. The Buyer reserves the right not to buy, in case the quote haschanged towards the worst.

50

Page 56: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

5.4.2 Supplier - Manufacturer

static final noalias protocol p_ms

{//manufacturer - supplier protocol

sbegin.

?(String).

?{

ID: //identify supplier

!<String>.

?{

DEAL: //supplier is ours

!<String> ,

NODEAL: //supplier is not ours

},

SESSION: //deal with supplier

?{

NEW: //first time we see supplier

?(String).!<Integer>.!<Double> ,

OLD:

![ //outwhile used when values

//have changed

!<Integer>.!<Double>

]*.

rec X[ //recursion

?{

BUY:

?(Integer) ,

ACCEPT:

,

NEGOTIATE:

?(Double)

.!{

ACCEPT: ,

MODIFY: !<Double>.#X , //recurse

REJECT:

},

REJECT:

}

]

}

}

}

(MS) Manufacturer - Supplier Protocol

The Manufacturer first receives a String of the Suppliers name. Supplier thenchooses between two types of session.

• ID, which is the process of determining whether a Supplier is connected toa Manufacturer (DEAL) or not (NODEAL)

• SESSION, the process of dealing with a Supplier who is already connectedwith the Manufacturer.

51

Page 57: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

The SESSION - OLD case signifies the state where the Manufacturer has providedSupplier with a quote before. The ![..]* statements are there to deal with thepossibility that the Manufacturer has made a sale since then. In that case, theManufacturer sends the new quote and quantity to the supplier. Finally, thisprotocol introduces the rec VAR[...] SJ session type. This stands for recursionand the #VAR command means that we recurse on the section of the scenariolocated within the square brackets.

5.5 Implementation

In this scenario, the Buyer - Supplier part was implemented first, and when thatwas completed I moved to implement the Supplier - Manufacturer.I will use he term “connection” between a pair of Supplier and Manufacturer toindicate that there’s a line going from a specific Supplier to a specific Manufac-turer as per diagram 5.1.

5.5.1 Ports

The Ports class was created with the purpose to contain an array of usableports and hosts, because in case the program was to be tested on a distributedenvironment, this was the easiest ways to input the hosts and ports.As implementation progressed the class has grown to also include the two pro-tocols shown above, a list of cities and a list of components, the use of whichwill be shown later. All protocols created everywhere else in the package arereferences to a protocol in Ports. As a side note, everything in the class had tobe declared static for the rest of the classes to be allowed to access it.

5.5.2 Location

This class Location is used for internal references within Buyer and Supplier toSuppliers and Manufacturers respectively. Each element of class location hasthe following properties along with their respective access methods: name, host,port, quote, quantity, component, state.

5.5.3 Supplier

I decided to implement the Supplier as an abstract class. Doing so enabled me todeclare all the functions that involved dealing with the Manufacturer abstract.Hence, during the design of the Buyer - Supplier part I could use a dummyextension to Supplier and trivial methods to stand for the values that wouldnormally be returned by the function after dealing with the Manufacturer.

The abstract functions are as follow:

public abstract Integer getAvailability(String o);

public abstract int acceptPrice(Double q);

public abstract Double getQuote (String o);

public abstract void sell(Integer i, Double d);

public abstract void modifyQuote(String o, Double q);

52

Page 58: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

This also divided the problem quite nicely. For any alterations in the Buyer -Supplier session I would edit Supplier. For the Supplier - Manufacturer sessionI would change something in the extension of Supplier.

Abstract Supplier

The Supplier abstract class deals with all interactions with the Buyer. Sincewe’re only dealing with one Buyer, the use of the main class would suffice for allinteractions. No creation of threads occurs in this class. The fact that we’re onlyusing one protocol saves a lot of code since, (as shown in Variation 4, Section4.2.4) there are certain parts of code when dealing with final noalias Socketsthat have to be duplicated throughout our program. Using only one protocolalso makes the implementation look quite tidy, with every step correspondingto a case from the protocol and, due to the duality property, also correspondingto an action from the Buyer.In other words, it has the advantages of Session-Based Programming.

Dealing with many protocols might result in one of our programs crashing.For example, consider creating two different protocols for cases NEW: and OLD:.Our Buyer chooses to outbranch to NEW: and when it completes the session itimmediately chooses to start a new session with the same supplier and outbranch

to OLD:. Then if the Supplier doesn’t create the new session and sets up tolisten for requests on time, the Buyer would get an exception. In our currentimplementation that never happens.

The Supplier has a counter and every time he modifies a negotiated quote,it’s counter decrements. Hence he cannot modify the quote forever. This wasessential to ensure that no infinite loops existed in the implementation because,as shown by the description, the Buyer never rejects a quote from a Supplier,he will either accept or negotiate the Supplier’s quote. In situations where theBuyer would never accept a Supplier’s quote, termination is solely dependenton the Supplier.

...

case OLD:

{

s_sb.inbranch()

{

case NEGOTIATE:

{

...

int v = state.intValue(); //counter value

int apn = acceptPrice(negotiation); //value determining

... //whether to accept, modify or reject negotiated offer

else if (apn==0 && v>0)

{

s_sb.outbranch(MODIFY)

{

53

Page 59: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

modifyQuote(order,negotiation);

s_sb.send(quote);

...

state = new Integer(v-1);

}

}

else

{

s_sb.outbranch(REJECT)

{

if (v!=-2)

{// if v==-2, we have already stopped negotiations so we

// shouldn’t be here

System.out.println(name + " rejected Negotiated Price of "

+ negotiation);

state = new Integer(-2);

}

...

}

...

In the purchase stage, the Supplier sends the quote and quantity to the Buyerand accepts any decision. Although things would be much simpler if the Sup-plier locked his quote (i.e. the Manufacturer’s as well) once he had offered it tothe Buyer, in a business environment that is very rarely done. This is becausethe Supplier doesn’t always have control over what the Manufacturers do butalso because actually locking the price would mean that if another customercame with a better offer we would be unable to sell to him. Also, the Buyercould possibly never return to actually purchase the product.

case BUY:

{

...

s_sb.inbranch()

{

case NO:

{ //in case our quote is worse than the one we previously

offered the buyer

System.out.println("Discrepancy in manufacturer quote due to

prior purchase,"

+ " negotiations with buyer have collapsed.");

}

case YES:

{

Integer rquant = (Integer) s_sb.receive() ;

if (state.intValue()!=-2)

{ //if we haven’t ceased negotiations already

sell ( rquant, quote );

...

}

else { ... } //For debug purposes

}

}

54

Page 60: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

}

Another possible solution could have been that the Supplier locks the quote andawaits for the Buyer to confirm that he will not be purchasing at that quote. Ichose not to do that, however, because it would greatly reduce the concurrencyof this scenario.

As mentioned in Design Issues(5.2), since a variable number of suppliers/man-ufacturers exists, there has to be an automated way of matching the supplierswith their respective manufacturers. Ideally that method would be in concreteSupplier since it involves interacting with Manufacturer. However, since ab-stract Supplier contains a continuous server session loop in it’s constructor itwas impossible to implement this matching process in concrete Supplier.

Upon creation, a Supplier is assigned a city semi-randomly out of the citiesin the Ports array cities:

private String getCity(int nman)

{

int n = Ports.cities.length;

int min = Math.min(n,nman);

//ensure we don’t get invalid array element access

float prob = (float) (new Random().nextInt(min+1))/min;

//probability

String c = Ports.cities[0];

int i = 0;

//randomly choose a city out of cities

while (i<min)

{

if (prob <= (float) i/(min-1))

{

c = Ports.cities[i];

System.out.println("City: " + c);

return c;

}

i++;

}

//for debug purposes

System.out.println("Error in cities");

return c;

}

By having an almost identical method in Manufacturer, we assign him a cityupon creation too. In the ID: section of our protocol the !<String> is the citythe Manufacturer sends to the Supplier.

ID: //identify supplier

!<String>.

?{

DEAL: //supplier is ours

!<String> ,

NODEAL: //supplier is not ours

},

55

Page 61: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

The Supplier compares that to his own city and only creates a connection be-tween the Manufacturer and himself if those match. By creating a connectiona Supplier adds the said Manufacturer (as an element of type Location) to aLinkedList mans, in which all the Manufacturers with whom he has a connec-tion with are included. Each supplier uses the method findmanufacturers() inthe constructor and after being assigned a city to establish connections.This method creates a thread for each manufacturer in the scenario and has asession with them, traversing the protocol as shown above.

for (int i = 0; i<nman; i++)

{

...

new Thread()

{

public void run()

{

..

try (s_sm) //Try connection with manufacturer

{

s_sm = c_sm.request();

s_sm.send(name);

s_sm.outbranch(ID)

{

String c = (String) s_sm.receive(); //receive city

int is = (c.compareTo(city)); //compare

if (is == 0)

{

s_sm.outbranch(DEAL)

{//we match

String co = (String) s_sm.receive(); //get component

ml.setComponent(co); //store it

ms.add(ml); //store manufacturer

...

}

}

else

{//dont match

s_sm.outbranch(NODEAL)

{ ... }

}

..

This way, we get the quotes faster than we would if we attempted to do thissequentially, and at the same time. However, we must ensure that all the threadshave finished before we move on and to do this we need to apply synchronization.

Synchronization We add an element to syncl each time a thread has com-pleted a session. This way we increment it’s size which can be used as a counter:

final List syncl = new LinkedList();

//syncl used for synchronisation purposes

for (int i = 0; i<nman; i++)

{

56

Page 62: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

...

new Thread()

{

public void run()

{

...

syncl.add("a"); //add anything to syncl

synchronized (syncl)

{

if (syncl.size()==fnman)

{//if all threads have finished

syncl.notifyAll();

}

}

}

}.start();

}

Syncl size becomes a record of the number of threads running (we cannot use aregular int counter as only final class objects can be accessed within the thread),we are forcing our program to wait for all the threads to have completed beforemoving on.

synchronized (syncl)

{//concurrency control

while (syncl.size()<nman)

{//while not all threads have finished

try { syncl.wait(); }

catch (InterruptedException ie)

{

ie.printStackTrace();

}

}

This method of thread creation and synchronization control is used several timesin this scenario.

Concrete Supplier

Our concrete Supplier (named SupplierA), only contains the implementationof the abstract functions in Supplier(5.5.3) which are the interactions with theManufacturer. The constructor method reads:

public SupplierA (int nsuppliers,int nman,int port,String name)

throws RuntimeException

{//Implementation of SupplierA

super(nsuppliers, nman, port, name);

}

RuntimeException as opposed to a regular Exception was used because it waseasier to deal with certain errors on run-time rather than dealing with the com-piler.The constructor of SupplierA is just a reference to the constructor of Supplier.Although ideally we would have some code such as running the findmanufacturers() from here, this would never be implemented due to the fact that the Supplierconstructor is an infinite loop.

57

Page 63: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

getAvailability(String order) The getAvailability method is the mainfunction in SupplierA. Through this we:

1. Get the first bunch of quotes and quantities for each Manufacturer (Byrunning the NEW: case in protocol (MS)

2. Separate manufacturers into chip and card manufacturers (using the sortComponents() method)

3. Get the quantity we can provide for cards and chips (using getPartQuantity

(String order, List parts))

4. Return the quantity

At this point through implementation I realised that the quantities returned bythe cards and chips manufacturers will probably differ. I therefore added thefollowing piece of code to deal with that:

int min = Math.min(chipsquantity,cardquantity);

if (min > 0)

{//else there’s an error somewhere (for debug purposes)

ga = new Integer(min);

quantity = ga.intValue();

}

This just means that we return the minimum of the two quantities, since wecan’t make our product with just one of the two items.

public Double getQuote(String o)

{

...

getPartQuote(o,chips);

getPartQuote(o,cards);

Location chip = (Location) chips.get(0);

Location card = (Location) cards.get(0);

double qv = chip.getQuote().doubleValue()

+ card.getQuote().doubleValue() + interest;

...

return new Double(qv);

}

The function heavily depends on the function getPartQuote, and adds any in-terest to the two quotes. Note that getPartQuote sorts the manufacturers soLocation chip = (Location)chips.get(0); gets the best chip manufacturer.

getPartQuote(String order, List part) This it where it all happens. TheSupplier opens a new thread and session for each of his Manufacturers andnegotiates with them as per the protocol until it gets a final price (or negotiationsbreak down). What is interesting to see is the implementation of recursion asdefined in protocol (MS).

58

Page 64: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

s_sm.recursion(X)

{// part to be recursed is within s_sm.recursion(X)

...

if (fi==0)

{//if we don’t have enough quantity accept price

k = 1;

}

else

{ //else decide whether to accept/modify/reject

k = acceptPrice(quotemp);

}

...

if (k==1 && qv>0)

{//if accept price and manufacturer quantity > 0

s_sm.outbranch(ACCEPT) { ... }

}

else if (k==0 && qv > 0)

{

s_sm.outbranch(NEGOTIATE)

{

...

s_sm.inbranch()

{

case ACCEPT: { ... }

case MODIFY:

{

....

s_sm.recurse(X);

}

case REJECT: { ... }

}

}

}

else { s_sm.outbranch(REJECT){...} }

}

The .s_sm.recursion(X) refers to rec X [... ] and s_sm.recurse(X) to the #X

in protocol (MS). In other words the s_sm.recurse(X) command tells the pro-gram to run whatever is within the brackets of .s_sm.recursion(X). The samesynchronization was implemented just as shown in Supplier (5.5.3, Synchroniza-tion).

modifyQuote() The scenario in Original Requirements(5.1) specifically men-tions in 5.b and 5.d that whilst negotiating with the Buyer the Supplier couldmodify the quote or it might have to renegotiate with his Manufacturers. It wasnecessary to implement this method in a way that would reflect this choice.

public void modifyQuote(String order,Double q)

{

...

int rand = new Random().nextInt(11);

if (rand>5)

{

interest /= 2 ;

59

Page 65: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

quote = new Double(q.doubleValue() - interest);

}

else { quote = getQuote(order); }

...

}

We will randomly choose between cutting of some of our interest or re-contactingall the manufacturers via getQuote(o) through the use of Random().

sell(Integer quantity, Double quote) Through the sell function a Supplierwill contact the chip and card manufacturers and purchase a given quantity forthe both of them. It is intersting to see that because even though we willnever recurse in the case of BUY: we still have to include the s_sm.recursion(X)

command around the protocol.

s_sm.outbranch(SESSION)

{

...

s_sm.outbranch(OLD)

{

s_sm.inwhile(){ ... }

...

s_sm.recursion(X)//This has to be included here

{//despite the fact that we never recurse

s_sm.outbranch(BUY)

{

Integer fd = new Integer(fdeduct);

s_sm.send(fd);

}

}

}

}

Upon reaching the implementation of sell, I realised that the program wouldbecome too complicated if I was to assume that the quantity of the Suppliersis finite and that the Manufacturer has to always commit to a quote he hasprovided the Supplier.Think of the example where the Supplier purchases the quote from the cardManufacturer and then finds out that they cannot purchase from the chip Man-ufacturer. I would then need to implement the sales to be reversible which couldbring a chain of complications (if for example the manufacturer has already con-tacted a different supplier with the already reduced quantity). I did realise laterthat there was a way to go around this, described in the Comments Section, butby that point it was too late.

5.5.4 Buyer

The Buyer is very much the party who pulls the strings in this scenario. Wesaw in protocol (BS) that for each session the Buyer selects the kind of inter-action he wants the Supplier. This choice provides us with great flexibility inimplementing the way in which the Buyer makes a purchase. In summary thebuyer:

60

Page 66: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

1. Sends the order to all suppliers and gets quote/quantity for all of the oneswho can supply for that order

2. Exhausts every possibility of getting a better quote from a Supplier whileat the same time ensuring he doesn’t make all of them stop negotiationswith him

3. Moves on to purchase the best quotes

• If the Supplier can still provide a quote better than or equal to theone promised the Buyer purchases

• If the Supplier’s quote has been altered negatively he cancels thepurchase

The function sort(int l, int h) exists to sort the Buyer’s records of Suppliers(through a LinkedList of class Location) ascending on the quote they have pro-vided (A.1)e.g. the Supplier with the best quote would come in first.The function amendLists() recalculates which suppliers are in LinkedLists “bList”and “nList” (corresponding to buyList and negotiationList), according to theany new quotes (A.2). Note that bList and nList only contain the index of thereference to the Supplier in the LinkedList “suppliers”. amendLists() ensuresthat suppliers who Buyer has stopped negotiating with are not entered in nListnor bList:

while (myq>0 && i < (suppliers.size()) )

{//while quantity not yet satisfied

//and still some suppliers left

Location sl = (Location) suppliers.get(i);

int q = sl.getQuantity().intValue();

if (sl.getState())

{//if still negotiating with supplier

myq-=q;

bList.add(new Integer(i));

np = sl.getQuote();

}

i++;

}

while (i < suppliers.size())

{//for the rest of the suppliers

Location sl = (Location) suppliers.get(i);

if (sl.getState())

{//if still negotiating with supplier

nList.add(new Integer(i));

}

i++;

}

This is our way of keeping track of state and ensuring that the Buyer does notmistakenly continue to attempt negotiations with a Supplier. Retrospectively,this could have also been included in the protocol as the decision that no furthernegotiation will take place is joint. In any case our implementation ensures thata Supplier and a Buyer who have stopped negotiations will never attempt tohave a session with each other.

61

Page 67: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

At each stage a separate thread is created in Buyer for every session initiated.If we compare protocols (BS) with (SM), we see that in the case of the (SM)the Supplier needs to either agree on an offer with the Manufacturer or stopnegotiations.

The way we have structured the protocol (BS), the Buyer can pause negotiationswith a single Supplier and wait to get the results from negotiations with otherSuppliers before he makes a decision as to how to proceed. This is essentialin having a realistic negotiation process where the parties need to make aninformed decision of what to buy by looking around first.The main part of the program is the negotiation process:

while(!nList.isEmpty())

{

final List dummylist = new LinkedList(); //loop synchronization

for (int i = 0; i<nList.size();i++)

{

... //for supplier i

Thread t = new Thread()

{

public synchronized void run()

{

...// establish connection through socket s_bs

try (s_bs)

{

...

s_bs.outbranch(OLD)

{

s_bs.outbranch(NEGOTIATE)

{

nptemp = new Double (Math.max(np.doubleValue()

-10.0,0.0) );

s_bs.send( nptemp );

s_bs.inbranch()

{

...// cases modify, accept, reject

}

synchronized(suppliers)

{//access to suppliers has to be controlled

suppliers.set(index,slocation);

}

}

}

synchronized(dummylist) {... }

// if all threads in for loop have finished notifyall

synchronized (nList){...}

//if nList is empty notifyall

}

...//catch statements

}

};

t.start();

62

Page 68: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

}//for loop ends here

synchronized (dummylist){...}

//while threads still running wait

sort(0,suppliers.size()-1); //sort suppliers

amendLists();//amend bList, nList

} //while loop ends here

synchronized (nList){...}

//while nList not empty wait

...

The above diagram is an overview of the method used for negotiations with asmuch code as possible removed without distorting the meaning. The easiestway to think of this is that the for loop stands for getting quotes off of all thesuppliers in nList. While the nList is not empty, we simultaneously get quotesfrom each Supplier in the list. We then re-sort our lists and re-arrange nListand bList. As we run this while loop again and again the nList decrements insize (every time a Supplier stops negotiations) until it becomes empty. We canthen move on to purchase from Suppliers in bList.I left the synchronization skeletons to show how the process was controlled,since it is a bit more complicated than what was shown before.

buy(Double quote, Integer quantity, int index) The scenario left thepossibility of the Buyer purchasing from more than one Suppliers open and Ihave implemented this. In case the Supplier with the best price cannot satisfythe Buyer’s quantity demanded, we can then purchase the rest from the secondbest Supplier. That is why the bList could possibly contain more than onemembers. In the buy

s_bs.outbranch(BUY)

{

if (recquote.compareTo(slquote)<=0 && (recquant.compareTo(tq)>=0 ||

recquant.compareTo(qI)>0))

//if received quote <= quote promised

//and quantity is >= to quantity promised or satisfies demand

{

..

s_bs.outbranch(YES)

{

if (tq.compareTo(qI)<=0)

{//if their quantity > our demanded

buy(slquote,tq,index);//buy their quantity

s_bs.send(tq);

}

else

{//else buy our demand

buy(slquote,qI,index);

s_bs.send(qI);

}

}

}

else

{

s_bs.outbranch(NO){...} //Discrepancy in value

}

63

Page 69: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

}

The Buyer checks if the Suppliers quantity is more than his own quantity de-manded. If so then he only buys his demanded quantity, otherwise he buy’s asmuch as the Supplier can offer.We also see how the Buyer does not buy anything if the quote is worse than orequal to what was promised, or if the quantity is less than what was promisedand cannot satisfy our demand. Given that the Manufacturers have been hard-coded to have an enormous quantity, the statements about quantity can bedisregarded.

5.5.5 Manufacturer

When a Manufacturer is created, it is assigned a city through the getCity()

method described in Abstract Supplier. It is also assigned a component usinga very similar JSTgetComponent() method (REFERENCE APPENDIX). Thequote range of a Manufacturer depends on the type of items it manufactures.After this stage the Manufacturer listens for any Suppliers requesting sessions inan infinite loop. Whenever a Manufacturer makes a sale, it changes boolean sc

to true. This indicates that if any Suppliers for whom he has already provideda quote try to contact him, he will send the updated quote. We have includedthis in our scenario through the ![...]* statements.

public void runSession()

{

...

case OLD:

{

boolean ssc = sc;

s_ms.outwhile(ssc)

{

s_ms.send(new Integer(quantity));

s_ms.send(new Double(quote));

ssc = false;

}

The Manufacturer checks if sc is true and if it is it updates the Supplier beforeit moves on with the protocol. We can do this because the ![...]* statementallows for zero-to-any recursions and in our case it will do zero or one.An interesting point is that the recursion between Supplier and Manufactureras shown in protocol (MS), must be explicitly defined inside Manufacturer too.

s_ms.recursion(X)

{

s_ms.inbranch()

{

...

case NEGOTIATE:

{

...

else if (counter>0)

{

s_ms.outbranch(MODIFY)

64

Page 70: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

{

....//local computation

s_ms.recurse(X);

}

}

...

This SJ type is not a “traditionally” dual type, unlike all others. None of theparties makes the decision of when or for how long to recurse for the bothof them like for example an inwhile statement. This was possibly done toallow for local computation taking place before the s_ms.recurse(X) command.For example, if we had a protocol rec x[!<String>.#X] then the only way tospecify in implementation when after sending the String to recurse would be toexplicitly state it through a command such as the s_ms.recurse(X) command.

Manufacturer Generation The way in which we generate an arbitrary num-ber of manufacturers is the following:

for (int i = 0 ; i<nman; i++)

{//nman is an argument given on command line

final int z = i;

new Thread()

{

public void run()

{

try {

new Manufacturer(nman,Ports.manports[z],z);

}

...// catch statements

}

}.start();

}

The same method is used in concrete Supplier to create the number of suppliersthat we want. This might be quite simple but for some time and withoutrealising it I was creating threads with a session between the same Supplier andthe Buyer!

5.6 Testing

One of the main difficulties in this project was the absence of any formal testingmethods or software in SJ. This is to be expected of a language that is still indevelopment. Tools normally available in a JAVA environment such as JUNITwere hence unavailable to us.All of the testing of the protocols implemented in this project was thereforemanual.

Variations In the variations of the TicketAgency Protocol taken from the“Web Services Choreography Description Language: Primer 1.0”??, compilingthe program would in most cases mean the programs were running correctly.That is why no examples of testing were included in this document.

65

Page 71: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Quote Request Testing the Quote Request scenario was very difficult and aparticularly extensive and tedious process. This was due to the fact that there alot of shared variables incorporated in the implementation of this scenario withmultiple threads attempting to access each of them with conflicting operationsat the same time.We have already shown a few code extracts with debug code. Those weremainly used to ensure that our methods were functioning correctly during theoperation of the program. For pretty much every function in all of the classes Itried to identify the cases where a function would go wrong and make it print astatement indicating that an error has occurred such as in class Manufacturer:

private String getCity(int nman)

{

int n = Ports.cities.length;

int min = Math.min(n,nman);

...

//System.out.println(prob);

String c = Ports.cities[0];

int i = 0;

while (i<min)

{

if (prob <= (float) i/(min-1)){... //assign city and return it;}

i++;

}

System.out.println("Error in cities");

return c;

}

This function was in fact originally programmed wrong. The int min = Math

.min(n,nman); statement was not included and in cases where the number ofcities was smaller than the number of manufacturers we would get an illegalarray element access attempt.

These simple tests would work for such easy functions but were inadequatefor others. For example, to check whether the Buyer negotiation process withall of the Suppliers was correct, I was required to test all the negotiation casesindividually to ensure that the synchronization methods were sufficient and thatin no case did we have a racing condition left unresolved. For a very long timeI believed there was something wrong with my synchronization controls wherein fact I was trying to use the SJ syntax in an inappropriate way:

s_bs.inbranch()

{

case ACCEPT:{...}

case MODIFY:{...}

case REJECT:{...}

synchronized(suppliers)

{

suppliers.set(index,

slocation);

}

}//end inbranch

Incorrect Implementation

s_bs.inbranch()

{

case ACCEPT:{...}

case MODIFY:{...}

case REJECT:{...}

}//end inbranch

synchronized(suppliers)

{

suppliers.set(index,

slocation);

}

Correct Implementation

66

Page 72: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

This was the error with my code. What I “meant” by this code was that afterall of the cases ACCEPT,MODIFY,REJECT, we would set the element in suppliers asshown. However, the way the code is written, the element is set only in the caseof REJECT. It is illegal SJ syntax to include anything outside a .case K: bracketand within an .inbranch() bracket. Unfortunately SJ doesn’t bring an error forthis illegal syntax and it is easy for the eye to skip. The correct implementationwould be to set the supplier outside the inbranch bracket.

A lot of tests involved identifying the potential cases we might have and theresults we should get. I would then run the program in a way to produce theparticular case and ensure that it runs correctly. Potential cases for the abovenegotiation process would hence be:

• CASE: Buyer has to buy from more than one Supplier to satisfy its demand

• CASE: A Supplier is moved from nList to bList and then back to nListagain

• CASE: A Supplier stops negotiations and is then added to one of the lists(should never occur)

• CASE: A Supplier exists in both lists at the same time (should neveroccur)

Once tricky cases are identified, I had to ensure that the program operatedcorrectly by analyzing the step by step progress it made. As no debugger wasavailable, I had to edit most of the functions to printout a string every timethey were accessed and another every time they were exited. Also, the sortmethod was edited so that it printed the state of the lists nList and bList afterexecution. These steps resulted in a “custom-made” log being produced eachtime I ran the programs, tracing the progress made, including things such asany negotiations, any quotes received or sent, entering an branch statement etc.Here is an example of a part of the log for Supplier:

67

Page 73: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

BLIIST:Supplier 1 119.0

NLIIST:Supplier 0 123.0

TEST after

inside modify

Supplier 0 modified quote to

104.5

Out of loop for outbranch

END FOR

h 0 Supplier 1

J before 1 Supplier 0

I after0 Supplier 0

J after1 Supplier 1

Supplier 0 Supplier 1

TEST AMEND LIST

Log from Buyer

Supplier 1 has accepted quote

of 17.0 from manufacturer

4 | 4

OUTSIDE LOOP

Outside getPartQuote

Outside getQuote

Outside getPartQuote

Inside getPartQuote

Outbranch Old

Supplier 0 has rejected

manufacturer 6s offer

1 | 7

Outbranch Old

State has changed, received new

quote/quantity values

Outbranch Old

Supplier 0 negotiated quote to

19.0 for manufacturer 3

Manufacturer 3 has accepted

negotiated quote.

Log from Supplier

A lot of errors were traced and edited in this way, some of them being the buyercontinuing to negotiate with a supplier even after they have ceased negotiations,several elements referencing to the same supplier being added in bList again andagain and lots more.

The most important part in the programs was to ensure that the accessedresources were accessed in a synchronized way. Even with the logs once such amistake is made, it is very difficult to trace.

5.7 Comments

The advantages of Session-Based Programming become more apparent as thecomplexity of the interactions increases. If we were dealing with regular socketprogramming, for every packet we received we would have to type check it andthen have a bunch of if statements through which we would decide how to actnext. Just beginning to consider situations in which we receive the same datatype for two different “branches” in our interaction pattern gives an indicationof how the situation soon gets out of control.

The use of inheritance in Supplier really helped in making the implementationof this scenario possible. Programming just one part of the interactions (e.g.Buyer - Supplier) at a time was quite mind jolting, let alone dealing with both.This is another example of how the Object-Orientated characteristics of SJ helpthe programmer during implementation.

A more complicated but more sound way of implementing the fact that aManufacturer must update the Supplier of any changes to the quote/quantitycould be the following:

68

Page 74: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

• We could create a thread for each Supplier dedicated to listening for anysession requests by a Manufacturer.

• The buyer would also have such a thread for listening for session requestsfrom Suppliers.

• If such a request occurs from Manufacturer to Supplier then the Supplierwould update its records and then in turn perhaps notify the Buyer thatits quote/quantity has also changed.

In real life, a lot of handshaking would be involved between two parties insuch transactions. For example the Buyer would first have to confirm that theSupplier really is the supplier he claims to be and vice versa.The Manufacturers don’t keep track of which of the Suppliers they’re dealingwith and trust that the Suppliers outbranch to the correct session type. Inreality there would again be an identification process. The Manufacturer wouldprobably also keep track of the state the Supplier is in except in some rare cases(like for example, in-house manufacturers).

Each manufacturer has been programmed to listen for session requests sequen-tially. This could be changed to concurrent at the cost of increased complexity.In that case the Manufacturer would need to have a “main” thread in which helistens for any new Suppliers. The session protocol in this main thread wouldbe dedicated to identifying new Suppliers. If a new Supplier is identified as oneof the Manufacturer’s potential clients, the Manufacturer would create a newthread dedicated explicitly to the said Supplier. He would then open a sessionin that thread with the protocol as shown above and send the supplier the portdedicated to him. This would in fact be a candidate for an extension to ourprotocol.

Programming the Buyer - Supplier protocol so that the Buyer can make aninformed decision of where to buy from was one of the biggest difficulties increating this scenario. So far I had only dealt with one-to-one scenarios. It was ofutmost importance to illustrate that the concept of Session-Based Programmingdoes not infer that once two parties have began interacting, they cannot becontrolled or updated with developments happening in their environment. Thiscould have also been achieved by using complicated synchronization methodssuch as wait() in several places around the code. I do, however, believe thatthe implemented way is simpler and does not come with any restrictions ininteractions.

69

Page 75: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Chapter 6

Evaluation

6.1 SJ Comparative Evaluation

SJ is a mixture of Object Orientated Programming and Socket Programming.Through SJ we can deal with objects as opposed to byte streams in SocketProgramming. We are not, however using Remote Method Invocation which isusually associated with Object Orientated Programming. In the meanwhile weare using protocols to define our interaction patterns and dual sessions for anyestablished connections.

6.1.1 Advantages

• Component Interface is explicit in SJ through the use of types. In SocketProgramming (SP) we’re dealing on the level of bytes sent and received andmany different types of messages may be received into a single variable.

• In SP we have to do a lot of work to construct a message before sendingit. In SJ we only have to declare what type it is.

• Through SJ we can use inheritance, and pass objects of any JAVA serializable

class. We can also create multi-threaded programs.

• We don’t need to deal with buffers for data received as with Socket Pro-gramming. Marshalling of data into memory is handled by SJ.

• SJ expands well to complicated scenarios through the use of sessions. Itwould be quite suitable for business interactions due to the almost directtranslation of the interaction pattern to an SJ protocol.

• It’s easy to simulate Remote Method Invocation through SJ just by send-ing the parameters of the method and receiving the result, as long as wehave declared the appropriate protocol and the objects passed are serial-izable.

• SJ does not require the use of a security manager.

• RMI is aspired towards one way communication. That is a party B doingsome local computation for a party A and returning a result. Using RMI

70

Page 76: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

in order to have interaction between two programs A and B, would involvesetting up method invocation of B in A and another method invocationof A to B. Using SJ we can have an interactive session much easier.

• SJ seems to be easier to learn than RMI and Socket Programming

• Static type checking occurs upon compilation and dynamic protocol com-patibility checking occurs upon connection establishment

6.1.2 Disadvantages

• In Socket Programming, interaction is difficult because of the need tospecify a custom protocol. This is the same with SJ. Although designinga SJ protocols is not difficult, in RMI this is not required at all.

• Programs written in a language such as CORBA are highly optimized andcompatible with a client written in any other language. Once it is fullyimplemented, SJ will need to be able to compete in that respect.

• Development tools do not exist for SJ at the moment while competinglanguages have many.

• The same applies for testing tools. Also, the error messages sent by theSJ compiler are sometimes long and vague even though the first messageusually points correctly to what the problem is.

6.1.3 Comments

SJ is a realisation of session programming and has a lot of advantages when im-plementing Business interaction patterns involving Web Services. The compilerallows us to use the typing language to statically check each protocol with it’simplementation upon compilation of a program.When a connection is established between two programs, their protocols aredynamically checked for compatibility. This is all the session control we re-quire and is arguably easier than having to define interfaces in IDL when usingRPC. The protocols reflect the scenarios which they’re implementing and areprogrammed in a logical structure which means that as the interaction patternsincrease in complexity the user is still to follow what is happening with theprotocol. This is unlike languages such as XML where the code is not aimed foreasy human interpretation.After defining the protocol, programming in SJ is straight foward. The SJ ses-sion types are very similar to the JAVA syntax and the direct correspondenceof each session type to the defined protocol means that the user already knowswhat the skeleton of his program would look like. All that is left is to programlocal computation which does not involve any additional difficulties than regularobject orientated programming. We are using JAVA after all.Some barometric issues for SJ are likely to be its compatibility to other toolsused in programming web services. This is a characteristic in web services whichhave been blossoming due to their cross-platform interoperability, and easy de-ployability. There’s a variety of languages and platforms co-existing on the weband SJ would have to provide the necessary compatibility in order to be used.

71

Page 77: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

6.2 SJ Protocols Evaluation

Implementing the scenarios in SJ was one of our prime goals in this project,as this included learning how to program in a new language in a limited timeframe. Now that we have achieved a certain number of protocols we must reflectback on them and rate the quality of our work. Unfortunately we must skipthe all-important criterion of performance, since we didn’t have nearly enoughtime to produce similar programs in other languages and compare them to theSJ implementations.

6.2.1 Correctness

As described in section 5.6, all testing for this project was manual. It was easyto test the variations and ensure that they were correct. In the case of theQuoteRequest scenario this was much more difficult. At this stage however, Ihave performed a very large amount of tests and am confidence of the correctnessof the protocol. However, this does not mean that there aren’t any issues withour implementation.

In an environment such as the one we are simulating, the manufacturer wouldhave the decision of either committing to a quote he has provided a supplier ortake any opportunity he has to sell a product. The first option could perhapshave been implemented through the use of “timeouts”. However it would beunwise for a manufacturer to commit to the quote indefinitely. This would beequivalent to a store owner not selling a product because some time ago a clientdropped by and asked him the price for it. By making this decision choice wehave, however, allowed the possibility that when the supplier eventually movesin to buy something from the manufacturer, it might now have a different price.This brings up a lot of complications. The way we have dealt with it is forthe buyer to handshake with a supplier prior to purchase. The supplier in turnchecks his prices with his manufacturers and in case the new price of the supplieris worse than what was promised then the Buyer refuses to make the purchase.

A possibility for an error existed when a supplier confirmed a sale from a cardmanufacturer but then realised that his chip manufacturer is unable to providehim with the quantity or price sold. We were hence forced to make the supplierquantity indefinite and force the supplier to buy even if the quote was worsethan promised. This is a drawback with our system as it is not very realistic.

6.2.2 Scalability

In the variations of TicketAgency, the scenario was only suitable for a givennumber of services. All the classes had to be hardcoded and run from a termi-nal window. This is due to not using threads which is what we did in the QuoteRequest scenario to produce an arbitrary number of suppliers and manufactur-ers.

The Quote Request scenario was tested with up to 20 suppliers and 20 man-ufacturers and worked without any problems in terms of crashing. the numberof suppliers and manufacturers are provided as arguments to the program and

72

Page 78: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

no other work has to be done by the user. With those numbers of suppliers andmanufacturers it’s more likely to get the limitation described above arise moreoften, however no incorrect purchases and results are produced with respectto the assumptions we have made in our system. (e.g. manufacturer’s infinitequantity) Note that this issue is not related to session programming and SJ butis more of a synchronization issue in JAVA.

6.2.3 Difficulty

The variations all consisted of their own interesting alterations to the scenariowhich required some thought before implementing. I feel they are good pieces ofwork for exhibition due to the fact that they present a solution to an interestingprogramming problem without containing too much code. Having said that,they felt much harder whilst I was programming them rather than looking backat them now. This is probably due to the fact that I have some experience inprogramming in SJ now.

The Quote Request scenario was definitely one of the hardest things I everhad to program. In the original plan, and I think my supervisor would agree,I considered it to be much easier than what it proved out to be. This wasone of the reasons why I didn’t manage to produce any benchmark tests intime. I learnt a lot of things during programming the scenario such as the useof threads in Web Programming and implementing concurrency control for amulti-agent system with complicated interactions. I attempted to deal withall the complicated issues in the original use case such as recursion and themany-to-many Supplier-Manufacturer relation.

6.3 Project Evaluation

The variations to TicketAgency present interesting examples of delegation andcontain interaction patterns common to many type of businesses. Throughthem, along with picking up the necessary skills to program the more compli-cated Quote Request scenario we have produced some interesting SJ programs.

The implementation of the Quote Request scenario is one of the complicatedscenarios implemented in SJ and could be used to test properties of SJ suchas the robustness of the language. It is also interesting to see how the difficultaspects of the scenario were solved in SJ. Producing the same scenario in another language was not feasible for this project and we cannot, hence, make thecomparison between SJ and other languages. However, ease of programming isone of the strong points of SJ and this is something I tried to stress throughoutthis paper.

Unfortunately, due to our time constraints we were unable to produce Bench-mark tests and this has restricted us to only passing qualitative evaluation ofSJ, and focusing on it’s properties from a programmers point of view.

Through this project I hope to have provided the SJ designers with some usertesting and a different point of view with my feedback. Most programmers in

73

Page 79: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

SJ have so far come from an environment within the design team and hencealready had the necessary skills to program in SJ. Supervising the learningcurve of someone without any background to Session-Based Programming, me,hopefully gave them an idea of how a user with no background in SJ wouldreact to it.

74

Page 80: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Chapter 7

Conclusions and FutureWork

7.1 Conclusions

The use of session programming to control interaction patterns between com-municating processes brings a lot of advantages we are reflected upon SJ. Thedynamic type-check upon connection establishment ensures that the protocolsof the two processes are compatible and in case they’re not, the session is imme-diately dropped to the floor. No time is wasted in attempting to run the sessionif the protocols are incompatible.

The ability to send and receive types brings SJ on a higher level than regularSocket programming and the nastiness that comes with programming in it. WebServices that interact within a service-oriented environment typically participatein one of a number of predefined message exchange patterns. The way in whichprotocols are defined in SJ allows a programmer to effortlessly translate averagesized Business scenarios into protocols. This gets harder as the scenarios getmore complicated but through the Quote Request scenario we have shown thatthe protocols don’t scale into incomprehensible monsters.

Through this project we have learnt about Session-Based Programming andthe advantages of merging it with object-orientated programming. We havelearn how to program in SJ and how to implement interactions in the language,incorporating object-orientated features such as inheritance to provide subtleimplementations to complicated scenarios. We have seen how the use of thread-ing is essential in creating certain protocols and this is also the case in webservices due to the interaction with arbitrary number of other services and theneed to both listen for session requests and initiate sessions. We have also seenhow the use of anonymous classes can make thread spawning much easier andalso make the implementation of a program more subtle. In SJ we have lookedfor the properties which make a language suitable for web service applicationsand business applications. In many cases we have found them.

75

Page 81: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

We hope to have contributed to the WS-CDL group by implementing theirscenario through a language supporting session programming. Additionally, wehope that our feedback about SJ will be useful to the designers and that theprotocols implemented through this project are good enough for exhibition.

7.2 Future Work

We have implemented the Quote Request scenario by making the Buyer multi-threaded but not the Supplier and Manufacturer. The latter two are not neces-sarily required to be multi-threaded but it would be interesting to see a scenariowhere each party participating would both initiate sessions (as client) and ac-cept sessions (as server). For example implementing the manufacturer to alerta supplier that he has made a sale and the quantity and quote have changed.In other words, we would be making the parties involved more like regular webservices that do not act as either servers or clients but usually act as both.

In our Quote Request we can deal with the Manufacturer - Supplier inter-action better. It seems the reasonable way to do that would be to lock theManufacturer while he waits for the Supplier to return and purchase something.This is what I really wanted to avoid, as it really destroys the concurrency ofthe system that we have tried so hard to accomplish! Producing solutions tothis problem would be a possible extension to our work. Note that the possiblescenario does not require that the Buyer “shops around” before finalizing a pur-chase. This is something we have added to the specifications and which I feelreally adds to the scenario. The implementation of a Buyer-Supplier interactionsimilar to the Supplier-Manufacturer would eliminate this issue altogether, butwouldn’t be as interesting.

When we set out to do this project a part of our original goals was to producesome Benchmark Tests comparing protocols implemented in SJ with other lan-guages, mainly RMI. This, however, proved unfeasible in the end, particularlybecause the Quote Request scenario implemented was too complicated for me tostart programming in other languages. It was also not a very good performanceindicator for SJ but was more interesting in terms of design decisions and theway it was implemented. Benchmark tests would definitely be a good additionto our work.

We have used a version of SJ implemented through TCP/IP as the underlyingprotocol. and it would be interesting to see an implementation of it throughHTTP which might even be out at the time of writing. The Web Services thatcould be programmed through it would be spread on a much larger range andit would be interesting to explore how it compares to already existing imple-mentations of web services in other languages. It would be interesting to runour programs in a distributed environment which is a stage we haven’t reachedin this project. It would also be interesting to see what additional capabilitiesSJ brings to the table compared to existing solutions, for example through theapplication of delegation to sender - intermediary - receiver protocols.

76

Page 82: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

We have implemented many variations of the TicketAgency scenario due tothe interesting delegation cases it offers. More scenarios could always be imple-mented with focus on other properties of SJ and other environments.

Enclosing, an analytical comparison could be provided between SJ and otherlanguages. This need not only be limited to benchmark test results but alsocomparisons between rather complicated implementations of business scenarios.

77

Page 83: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

78

Page 84: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Appendix A

Methods

A.1 Buyer’s Sort Method

public synchronized void sort(int lo, int hi)

{

//System.out.println("sort");

int pivot = (lo + hi) /2; //pivot value

Double x=((Location) suppliers.get( pivot )).getQuote();

//get supplier at pivot value

int i = lo;

int j = hi;

Location h;

while (i<=j)

{

while ( ((Location ) suppliers.get(i)).getQuote().compareTo(x) < 0

) { i++;}

while ( ((Location) suppliers.get(j)).getQuote().compareTo(x) > 0)

{ j--;}

//System.out.println("inside while i<=j loop sort");

if (i<=j)

{

h = (Location) suppliers.get(i);

//System.out.println("h " + i + " " + h.getName() + " " );

suppliers.set(i,suppliers.get(j));

//System.out.println("J before " + j + " " + ((Location)

suppliers.get(j)).getName() + " " );

//System.out.println("I after" + i + " " +((Location) suppliers.

get(i)).getName() + " " );

suppliers.set(j,h);

//System.out.println("J after" + j + " " + ((Location) suppliers

.get(j)).getName() + " " );

i++; j--;

}

}

if (lo<j) { sort(lo, j); }

if (i<hi) { sort(i, hi); }

//for (int kk = 0; kk < suppliers.size() ; kk++)

//{

// System.out.print(((Location) suppliers.get(kk)).getName() + "

" );

//}

}

sort()

79

Page 85: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

A.2 Buyer’s amendLists Method

public synchronized void amendLists()

{

int i = 0;

int myq = quantity;

bList.clear(); //empty lists

nList.clear();

while (myq>0 && i < (suppliers.size()) )

{//do until quantity satisfied or no more suppliers

Location sl = (Location) suppliers.get(i);

//System.out.println("TEST AMEND LIST");

int q = sl.getQuantity().intValue();

if (sl.getState())

{

myq-=q;//decrement temporary quantity

bList.add(new Integer(i)); //add to buylist

np = sl.getQuote();

}

i++;

}

//System.out.println("i got out");

//System.out.println(suppliers.size());

while (i < suppliers.size())

{//add the rest to nList...

Location sl = (Location) suppliers.get(i);

if (sl.getState())

{//...if we haven’t stopped negotiations

nList.add(new Integer(i));

}

i++;

}

/*

for (int pi = 0; pi<bList.size();pi++)

{//for all members of bList

Integer index = (Integer)bList.get(pi);

Location ltemp = (Location) suppliers.get(index.intValue());

System.out.println("BLIIST:" + ltemp.getName()+ " " + ltemp.

getQuote());

}

for (int pi = 0; pi<nList.size();pi++)

{//for all members of nList

Integer index = (Integer)nList.get(pi);

Location ltemp = (Location) suppliers.get(index.intValue());

System.out.println("NLIIST:" + ltemp.getName() + " " + ltemp.

getQuote());

}

*/

//System.out.println("DONE AMENDING");

}

amendLists()

80

Page 86: Session-Based Web Service Programming for Business Protocolsyoshida/CDL_USECASE/sj/report/report.pdf · 2.1 Session Programming In the “Language Primitives and Type discipline for

Bibliography

[1] Web Services Choreography Description Language: Primer 1.0. http://www.w3.org/TR/

ws-cdl-10-primer/.

[2] Web Services Choreography Requirements. http://www.w3.org/TR/ws-chor-reqs/.

[3] W3C Web Services Choreography. http://www.w3.org/2002/ws/chor/.

[4] M. Dezani-Ciancaglini, D. Mostrous, N. Yoshida, and S. Drossopoulou. Session Typesfor Object-Oriented Languages. In ECOOP’06, volume 4067 of LNCS, pages 328–352.Springer, 2006.

[5] K. Honda, V. T. Vasconcelos, and M. Kubo. Language primitives and type disciplinesfor structured communication-based programming. In ESOP’98, volume 1381 of LNCS,pages 22–138. Springer-Verlag, 1998.

[6] K. H. Raymond Hu, Nobuko Yoshida. Session-based distributed programming in java.2008.

[7] SJ homepage. http://www.doc.ic.ac.uk/~rh105/sessionj.html.

81