09.07.2015 Views

sudparis.eu

sudparis.eu

sudparis.eu

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Middleware for Internetdistributed applicationsS. Chabridon, C. Taconet, S.TataASR/CSC50023 novembre 2014


✬Licence✩Ce document est une documentation libre, placÃľe sous la Licence de Documentation Libre GNU (GNUFree Documentation License).# 1Copyright (c) 2007-2010 C. Taconet, S. Chabridon, D. ConanPermission est accordÃľe de copier, distribuer et/ou modifier ce document selon lestermes de la Licence de Documentation Libre GNU (GNU Free Documentation License),version 1.2 ou toute version ultÃľri<strong>eu</strong>re publiÃľe par la Free Software Foundation; avecles Sections Invariables qui sont ‘Licence’ ; avec les Textes de PremiÃĺre deCouverturequi sont ‘Middleware for Internet distributed applications’et avec les Textes de QuatriÃĺme de Couverture qui sont ‘References of all thechapters’.Une copie de la prÃľsente Licence p<strong>eu</strong>t Ãłtre trouvÃľe Ãă l’adresse suivante :http://www.gnu.org/copyleft/fdl.html.Remarque : La licence comporte notamment les sections suivantes : 2. COPIES VERBATIM, 3.COPIES EN QUANTITÃĽ, 4. MODIFICATIONS, 5. MÃĽLANGE DE DOCUMENTS, 6. RECUEILS DEDOCUMENTS, 7. AGRÃĽGATION AVEC DES TRAVAUX INDÃĽPENDANTS et 8. TRADUCTION.✫✪Ce document est prÃľparÃľ avec des logiciels libres :• L A TEX : les textes sources sont Ãľcrits en L A TEX (http://www.latex-project.org/, le site du Groupefrancophone des Utilisat<strong>eu</strong>rs de TEX/L A TEX est http://www.gutenberg.<strong>eu</strong>.org). Une nouvelle classeet une nouvelle f<strong>eu</strong>ille de style basÃľes sur la classe seminar ont ÃľtÃľ tout spÃľcialement dÃľvÃľloppÃľes:newslide (projet picoforge newslide, http://picoforge.int-evry.fr/projects/slideint)et slideint (projet picoforge slideint, http://picoforge.int-evry.fr/projects/slideint);• emacs: tous les textes sont ÃľditÃľs avec l’Ãľdit<strong>eu</strong>r GNU emacs(http://www.gnu.org/software/emacs);• dvips: les versions PostScript (PostScript est une marque dÃľposÃľe de la sociÃľtÃľ Adobe SystemsIncorporated) des transparents et des polycopiÃľs Ãă destination des ÃľlÃĺves ou des enseignants sontobtenues Ãă partir des fichiers DVI (« DeVice Independent ») gÃľnÃľrÃľs Ãă partir de LaTeX parl’utilitaire dvips (http://www.ctan.org/tex-archive/dviware/dvips);• ps2pdf et dvipdfm: les versions PDF (PDF est une marque dÃľposÃľe de la sociÃľtÃľ Adobe SystemsIncorporated) sont obtenues Ãă partir des fichiers Postscript par l’utilitaire ps2pdf (ps2pdf Ãľtantun shell-script lanÃğant Ghostscript, voyez le site de GNU Ghostscript http://www.gnu.org/-software/ghostscript/) ou Ãă partir des fichiers DVI par l’utilitaire dvipfm;• makeindex: les index et glossaire sont gÃľnÃľrÃľs Ãă l’aide de l’utilitaire Unix makeindex(http://www.ctan.org/tex-archive/indexing/makeindex);• TeX4ht: les pages HTML sont gÃľnÃľrÃľes Ãă partir de LaTeX par TeX4ht (http://www.cis.ohio--state.edu/~gurari/TeX4ht/mn.html);• Xfig: les figures sont dessinÃľes dans l’utilitaire X11 de Fig xfig (http://www.xfig.org);• fig2dev: les figures sont exportÃľes dans les formats EPS (« Encapsulated PostScript ») et PNG(« Portable Network Graphics ») grÃćce Ãă l’utilitaire fig2dev (http://www.xfig.org/userman/-installation.html);• convert: certaines figures sont converties d’un format vers un autre par l’utilitaire convert(http://www.imagemagick.org/www/utilities.html) de ImageMagick Studio;• HTML TIDY: les sources HTML gÃľnÃľrÃľs par TeX4ht sont « beautifiÃľs » Ãă l’aide de HTML TIDY(http://tidy.sourceforge.net) ; vous pouvez donc les lire dans le source;Nous espÃľrons que vous regardez cette page avec un navigat<strong>eu</strong>r libre: Mozilla ou Firefox par exemple.Comme l’indique le choix de la licence GNU/FDL, tous les ÃľlÃľments permettant d’obtenir ces supportssont libres.Ce cours a bénéficié des relectures attentives et constructives de...Middleware for Internet distributed applicationsTélécom SudParis / INF — S. Chabridon, C. Taconet, S.Tata — 3 novembre 2014 — ASR/CSC5002 2


Middleware for Internet distributed applicationsContentsLicence 1Presentation of the teaching unit Middleware for Internet distributed applications 111 Administrative Information 122 Objectives of this teaching unit 123 Organisation of this teaching unit 124 Big Picture 135 Conferences 146 Evaluation 146.1 Architecture of the mailbox manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156.2 Mailbox manager usecase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1516Middleware definitions and overview 17Outline 181 Which middleware? 181.1 Middleware definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191.2 Middleware: a picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191.3 Middleware as a universal adapter to build high level applications ? . . . . . . . . . . . . . 202 Families of middleware 203 Middleware for separation of concerns purpose 213.1 Levels of heterogeneity addressed by middleware . . . . . . . . . . . . . . . . . . . . . . . . 223.2 Middleware for several levels of distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . 223.3 Examples of software distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 Which technology for which situation 234.1 Interaction styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244.2 Object/Service/Component lifecycle : servers and containers . . . . . . . . . . . . . . . . . 244.3 Data management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.4 Presentation middleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.5 Service Oriented Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264.6 Component based Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264.7 Architectural styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 Layer view of some middleware frameworks 276 Conclusion 28RESTful WebServices in Java 29Outline 30Télécom SudParis / INF — S. Chabridon, C. Taconet, S.Tata — 3 novembre 2014 — ASR/CSC5002 3Middleware for Internet distributed applications1 Introduction 301.1 What is REST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301.2 REST: Representational State Transfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311.3 REST resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311.4 Uniform interface: CRUD operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321.5 Are these operations sufficient to build an application ? . . . . . . . . . . . . . . . . . . . . 321.6 Representation formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331.7 How to implement a RESTful service ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 Hyper Text Transfer Protocol: basics reminder 342.1 HTTP GET Request message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342.2 HTTP Response message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362.3 HTTP GET vs POST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 Representation of a Java object 373.1 JAXB - Java Architecture for XML Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . 383.2 JAXB data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383.3 JAXB annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393.4 JAXB annotations example file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403.5 JAXB in action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413.6 Handling cycles in JAXB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433.7 Json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433.8 Json in gson . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443.9 Skier in json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443.10 gson custom serialization/deserialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454 Java RESTful service 464.1 REST JAX-RS architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474.2 @path annotation and resource URI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474.3 Input or output representation format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484.4 JAXB representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494.5 Path and template parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494.6 Hello World in REST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504.7 Java Client example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504.8 Light server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514.9 Parameter annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514.10 REST Synthesis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52References 52Middleware for synchronous requests illustrated with WebServices 53Outline 541 Introduction 541.1 Middleware for distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541.2 Goal : interoperability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551.3 Distribution models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551.4 Client-server models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561.5 Middleware for distributed objects history . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561.6 Synchronous vs asynchronous mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572 Synchronous middleware and the big picture 572.1 Introduction of the distributed example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582.2 Principle of distributed objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582.3 The stub and the skeleton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592.4 Proxy Object and inheritance tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592.5 Distribution Implementation Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60Télécom SudParis / INF — S. Chabridon, C. Taconet, S.Tata — 3 novembre 2014 — ASR/CSC5002 4


Middleware for Internet distributed applicationsUseful links 114References 115Introduction to design patterns for middleware 117Foreword 118Outline 1181 Distributed system organisation with a middleware 1192 Design patterns 1192.1 Objectives of the pattern orientation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1202.2 Some design pattern examples for middleware . . . . . . . . . . . . . . . . . . . . . . . . . . 1202.2.1 Example 1: A client/server middleware . . . . . . . . . . . . . . . . . . . . . . . . . 1212.2.2 Example 2: Integration of legacy applications . . . . . . . . . . . . . . . . . . . . . . 1212.2.3 Example 3: Adaptation to client resources . . . . . . . . . . . . . . . . . . . . . . . . 1222.2.4 Example 4: Monitoring and control of networked equipments . . . . . . . . . . . . . 1222.3 Definition of design patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1232.4 Writing patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1232.5 Classifying patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1243 Patterns for distributed interaction 1243.1 Asynchronous call, synchronous call, buffered message . . . . . . . . . . . . . . . . . . . . . 1253.2 Call-back and Inversion of control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1253.3 Reflection: Observe and act on its own state and behaviour . . . . . . . . . . . . . . . . . . 1263.4 Factory: Entity creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1273.4.1 Sequence diagram of Factory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1273.5 Proxy: Representative for remote access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1283.5.1 Sequence diagram of Proxy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1283.6 Wrapper or Adapter: Interface transformation . . . . . . . . . . . . . . . . . . . . . . . . . 1293.6.1 Sequence diagram of Wrapper/Adapter . . . . . . . . . . . . . . . . . . . . . . . . . 1293.7 Interceptor: Adaptable service provision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1303.7.1 Sequence diagram of Interceptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1303.8 Similarities and differences between the previous patterns . . . . . . . . . . . . . . . . . . . 1314 Patterns for composition 1324.1 Principle of de/composition in distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . 1324.2 Contract: Qualified required/offered interfaces . . . . . . . . . . . . . . . . . . . . . . . . . 1324.3 Layer or Abstract machine or Protocol stack: Vertical decomposition . . . . . . . . . . . . . 1334.4 Multi-tier architecture: Horizontal decomposition . . . . . . . . . . . . . . . . . . . . . . . . 1334.4.1 Focus on presentation tier: The MVC pattern . . . . . . . . . . . . . . . . . . . . . . 1344.4.2 MVC pattern vs 3-tier architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1354.5 Component/Container: Contract + Factory + Interceptor + extra-functionalities . . . . . . 1354.6 Composite with sharing: Component + Vertical decomposition + Sharing . . . . . . . . . . 1364.6.1 Example of the Fractal Component Model . . . . . . . . . . . . . . . . . . . . . . . . 1365 Patterns for coordination 1365.1 Naming: White pages service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1375.2 Trading: Yellow pages service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1375.3 Publish/subscribe or Observer or Event channel: Change-propagation mechanism . . . . . . 1385.3.1 Example of OMG CORBA Event channel . . . . . . . . . . . . . . . . . . . . . . . . 1385.4 Pipes and filters: Structure for processing streams of data . . . . . . . . . . . . . . . . . . . 139Component Middleware 141Outline 142Télécom SudParis / INF — S. Chabridon, C. Taconet, S.Tata — 3 novembre 2014 — ASR/CSC5002 7Middleware for Internet distributed applications1 Foreword 1422 Introduction 1422.1 Limits of object-oriented programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1432.2 Motivations for Component Based Development . . . . . . . . . . . . . . . . . . . . . . . . 1432.3 What is a component ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1442.4 Characterization of a component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1442.5 Runtime environment of a component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1452.5.1 Runtime environment of a component (cont.) . . . . . . . . . . . . . . . . . . . . . . 1452.5.2 Technical services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1462.6 Multi-tier Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1462.7 The 6 Roles in Component Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1472.7.1 The 6 Roles in Component Development (cont.) . . . . . . . . . . . . . . . . . . . . 1472.8 Main component middleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1483 Overview of EJB Technology 1483.1 What is EJB ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1493.2 Java Community Process (JCP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1493.3 EJB Container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1503.3.1 EJB Container - Provided services . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1503.3.2 EJB Container - Provided services (cont.) . . . . . . . . . . . . . . . . . . . . . . . . 1513.3.3 EJB Container - Provided services (cont.) . . . . . . . . . . . . . . . . . . . . . . . . 1513.4 Java EE at a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1523.4.1 Java EE Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1523.4.2 Java EE - 3-tier Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1533.4.3 Java EE - 3-tier Architecture (cont.) . . . . . . . . . . . . . . . . . . . . . . . . . . . 1533.5 EJB types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1543.5.1 EJB types (cont.) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1543.6 Main EJB3 Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155Main EJB3 Annotations (cont.) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155Main EJB3 Annotations (cont.) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1563.7 Bean development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1563.7.1 Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1573.8 Session Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1573.8.1 Stateless Session Bean - Calculator Example . . . . . . . . . . . . . . . . . . . . . . 1583.8.2 Stateless Session Bean - Calculator Example - Implementation class . . . . . . . . . 1583.8.3 Stateless Session Bean - Calculator Example - Client side . . . . . . . . . . . . . . . 1593.8.4 Stateless Session Bean - No-interface view . . . . . . . . . . . . . . . . . . . . . . . . 1593.8.5 Stateful Session Bean - Cart Example . . . . . . . . . . . . . . . . . . . . . . . . . . 1603.8.6 Stateful Session Bean - Cart Example (cont.) . . . . . . . . . . . . . . . . . . . . . . 1603.8.7 Stateful Session Bean - Cart Example - Implementation class . . . . . . . . . . . . . 1613.8.8 Stateful Session Bean - Cart Example - Implementation class (cont.) . . . . . . . . . 1613.8.9 Stateful Session Bean - Cart Example - Client side . . . . . . . . . . . . . . . . . . . 1623.9 Entity Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1623.9.1 Entity Bean (cont.) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1633.9.2 Entity Bean - Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1633.9.3 Multiplicities in Entity Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . 1643.9.4 Multiplicities in Entity Relationships - OneToMany example . . . . . . . . . . . . . 1643.9.5 Persistence management mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1653.9.6 Entity Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1653.9.7 Container-Managed Entity Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . 1663.9.8 Application-Managed Entity Manager . . . . . . . . . . . . . . . . . . . . . . . . . . 1663.9.9 How to use the Entity Manager - Example . . . . . . . . . . . . . . . . . . . . . . . . 1673.9.10 Persistence Unit - persistence.xml file . . . . . . . . . . . . . . . . . . . . . . . . . . 1673.9.11 Persistence Unit - persistence.xml file - Example . . . . . . . . . . . . . . . . . . . . 1683.10 Transaction Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1683.10.1 Transaction Service (cont.) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169Télécom SudParis / INF — S. Chabridon, C. Taconet, S.Tata — 3 novembre 2014 — ASR/CSC5002 8


Middleware for Internet distributed applications4 Conclusion 1695 References 170Prerequisites for developing multi-tier applications in Java 171Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1721 Java Annotations 1721.1 Java Annotations - Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1721.2 Create your own annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173Micro Project 177References of all the chapters 183Télécom SudParis / INF — S. Chabridon, C. Taconet, S.Tata — 3 novembre 2014 — ASR/CSC5002 9Middleware for Internet distributed applicationsTélécom SudParis / INF — S. Chabridon, C. Taconet, S.Tata — 3 novembre 2014 — ASR/CSC5002 10


Presentation of the teaching unit Middleware for Internet distributed applications✬✩3 Organisation of this teaching unit A middleware panorama# 41. Fundamentals of middleware Synchronous distributed requests (REST and Web Services) Message-oriented middleware - MOM (Java Messages Service [JMS]) Well-known patterns to build distributed middleware2. Component-based middleware with JavaEE Main concepts of component-oriented middleware (containers, extra-functionalproperties) Extra-functional properties and services illustrated for the JavaEE middleware(naming service, notification service, transaction service, persistency service) EJB components3. Web Services composition and cloud computing Web Services composition (SCA) Development of applications in a cloud environment✫✪✬✩# 54 Big Picture✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 13Presentation of the teaching unit Middleware for Internet distributed applications✬✩# 6✫✪✬5 Conferences✩# 7 Wednesday 5th November, 2.30-5.45 pm Nenad Bogojevic, Expert Online & Front Office Architecture, Amad<strong>eu</strong>s Amad<strong>eu</strong>s is the leading provider of IT solutions to the global tourism and travelindustry. Wednesday 12th November, 2.30-5.45 pm Hervé Leclerc, CTO Alter Way Feedback on OpenStack, an open source IAAS framework for cloud computing✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 14


Presentation of the teaching unit Middleware for Internet distributed applications 6 Evaluation✬✩6 Evaluation# 8 Graded lab (30%) Subject: Web Services composition and cloud computing Wednesday 19th November Micro Project (70%) Subject: Mailbox manager and directory manager Project defense: Friday 21st November Results:◮ Original demonstration◮ Report (6 pages)◮ Defense✫✪✬6.1 Architecture of the mailbox manager✩# 9✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 15Presentation of the teaching unit Middleware for Internet distributed applications✬✩6.2 Mailbox manager usecase# 10✫✪✬✩Any questions ?# 11Good Work !✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 16


Middleware definitions andoverviewChantal TaconetASR/CSC50023 novembre 201417Middleware definitions and overview✬✩Outline# 21 Which middleware? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Families of middleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Middleware for separation of concerns purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Which technology for which situation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 Layer view of some middleware frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 Conclusion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22✫✪✬1 Which middleware?✩# 3 A wide number of middleware technologies are hidden under those acronyms!✫✪Some acronyms ...B2B Business to BusinessB2C: Business to ConsumersCORBA: Common Object Request Broker ArchitectureCORBA DDS: CORBA Data Distribution Service EAI Enterprise Application IntegrationESB Enterprise Service BusEJB Enterprise Java BeanJavaEE Java 2 Enterprise EditionJMS Java Message ServiceMOM Message Oriented MiddlewareMVC Model View ControllerTELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 18


Middleware definitions and overview 1 Which middleware?M2M Machine to MachineP2P Peer to PeerRMI Remote Method InvocationRPC Remote Procedure CallREST Representational State TransferSCA Service Component ArchitectureSOA Service Oriented ArchitectureSOAPWebServiceWSDL Web Service Description Language... how to choose the good technology ?✬1.1 Middleware definitions✩ Several definitions a# 4 Middleware is software glue. Middleware is the slash in Client/Server Software that mediates between an application program and a network. Middleware is computer software that connects software components orapplications. It is used most often to support complex, distributed applications.It includes web servers, application servers, content management systems, andsimilar tools that support application development and delivery. Middleware isespecially integral to modern information technology based on XML, SOAP, Webservices, and service-oriented architecture. It goes on to say that it describes apiece of software that connects two or more software applications so that theycan exchange data. Middleware is any software that allows other software to interact.a Found on middleware.org (http://www.middleware.org/whatis.html) and wikipedia(http://en.wikipedia.org/wiki/Middleware)✫✬ Middleware is sometimes called plumbing because it connects application andpasses data between them. Middleware is software used for coupling high level system components(application) with basic system components (data and network)✪✩# 5✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 19Middleware definitions and overview✬✩1.2 Middleware: a picture# 6✫✪The structure of application may be divided into the following layers:• Presentation (i.e., presentation and interactions with the end users)• Application logic (i.e., brains of the application)• Data (i.e., memory of the application)These three layers may or may not be distributed. Middleware may handle the interactions between thelayers and/or between distributed layers of the same or of different levels.This classification is a mean to have a first overview of the acronyms you can see about middlewaretechnologies. The boundaries of the classification are not closed. Some middleware may be placed indifferent categories.✬1.3 Middleware as a universal adapter to build high levelapplications ?✩# 7✫✪The middleware may play the role of a universal adapter (which is of course an unreachable holy grail).The picture suggests that several adapters and so middleware are necessary.TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 20


Middleware definitions and overview✬✩3.2 Middleware for several levels of distribution# 11 pieces of software connected by middleware may be distributed on: Several processes (in the same computer) Several computers (in the same local area network) Several networks (in the same company) Several companies✫✪✬3.3 Examples of software distribution✩# 12✫✪As we can see in this picture, middleware may connect pieces of software in various situations: machine tomachine (M2M), database to database, server to database, business to business (B2B), business to consumers(B2C). The constraints set on the middleware and the requirements on the middleware are not the samein all these situations. Some reasons are the characteristics of the computers they operate on, the firewallsto cross on the networks, the connectivity of the computers, the software available on the computers. Themiddleware play an essential role to enable interactions between different pieces of software distributed onthe network and to allow software architect to build high level software.TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 23Middleware definitions and overview 4 Which technology for which situation✬✩4 Which technology for which situation# 134.2 Interaction styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154.2 Object/Service/Component lifecycle : servers and containers . . . . . . . . . . . . . . . . . . . 154.4 Data management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174.4 Presentation middleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174.6 Service Oriented Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194.6 Component based Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .195.0 Architectural styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21✫✪✬4.1 Interaction styles✩# 14 Middleware for distributed synchronous requests (network layer) RPC: request broker, CORBA: object request broker, multi-languages, Local Area Network (LAN) RMI: object request broker, java, LAN Web services (synchronous messages): request broker, multi-languages, WideArea Network, service orchestration, clouds Message Oriented Middleware (MOM) (network and data layers) JMS, LAN ESB Enterprise Service Bus, WAN EAI Enterprise Application Integration, data exchange, WAN✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 24


Middleware definitions and overview 4 Which technology for which situation✬✩4.2 Object/Service/Component lifecycle : servers and containers Application server manager: instantiation, containers Application Servers◮ JavaEE (JBoss, glassfish, Websphere):◮ Light servers : Spring Web container : Web Server (tomcat, jetty, LiteWebServer:# 15✫✪✬4.3 Data management✩ Data Oriented Middleware (network and data layers) EAI Enterprise Application Integration, data exchange, WAN REST (Representational State Transfer), DDS Data Distribution Service# 16 Transaction middleware : several requests in a same transaction (commited orrollbacked) (network layer) JavaEE (EJB), includes transaction management Persistency middleware handles persistency of data or objects (data layer) JavaEE (EJB) includes persistency preoccupation (various technologies) Hibernate is a persistency framework (from object to relational databaseparadigm)✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 25Middleware definitions and overview 4 Which technology for which situation✬✩4.4 Presentation middleware Presentation middleware: handles presentation of information (presentation layer) Struts Web presentation of components through the MVC approach (ModelView Controler)# 17✫✪✬4.5 Service Oriented Architecture Service Oriented Architecture (for sequence of services) Service abstraction Service Orchestration Workflow of services✩# 18aa Source de la figure https://www.ibm.com/developerworks/mydeveloperworks/blogs/devaprasad/✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 26


Middleware definitions and overview✬✩4.6 Component based Architecture Component abstraction Component Assembly (e.g. SCA Service Component Architecture, Fractalcomponents, CORBA Component Model)# 19✫✪✬4.7 Architectural styles✩ P2P (peer 2 peer) M2M (machine 2 machine) B2B Business 2 business B2C Business 2 consumers 3 tiers# 20✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 27Middleware definitions and overview✬✩5 Layer view of some middleware frameworks# 21✫✪✬6 Conclusion✩# 22 Choice of a middleware may be decided lately when designing an application (ModelDriven Architecture). Middleware may connect pieces of software implemented separately and available onthe network. Standardisation is essential to connect pieces of software Universal adapter is of course not possible: Many technologies are available with different characteristics (e.g., targetplatform, semantics, efficiency) The basic of middleware is about distribution (RPC, RMI, MOM, SOAP)sometimes called plumber solutions. Above distribution, higher abstractions may be built: publish/subscribe, datadistribution, persistency, transactions, presentation, naming, workflow,orchestration and composition.✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 28


RESTful WebServices in JavaChantal TaconetASR/CSC50023 novembre 201429RESTful WebServices in Java 1 Introduction✬✩Outline# 21 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Hyper Text Transfer Protocol: basics reminder. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .133 Representation of a Java object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 Java RESTful service. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35✫✪✬1 Introduction✩# 31.1 What is REST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.3 REST: Representational State Transfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.3 REST resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.5 Uniform interface: CRUD operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.5 Are these operations sufficient to build an application ? . . . . . . . . . . . . . . . . . . . . . . . . . 81.7 Representation formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.7 How to implement a RESTful service ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 30


RESTful WebServices in Java 1 Introduction✬✩1.1 What is REST REST is a "URL friendly" way to retrieve distributed resources REST is built upon HTTP Examples of REST resources twitter API (https://dev.twitter.com/docs/api/1.1)# 4 google maps API(https://developers.google.com/maps/documentation/webservices/)#Give a try on your webbrowser to discover where are those placeshttp://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=falsehttp://maps.googleapis.com/maps/api/geocode/json?latlng=48.858518, 2.294524&sensor=falsehttp://maps.googleapis.com/maps/api/geocode/json?latlng=48.625595, 2.443234&sensor=false youtube API(https://developers.google.com/youtube/2.0/developers_guide_protocol_api_query_parameters)#Give a try on your webbrowser to discover TelecomSudParis on youtubehttp://gdata.youtube.com/feeds/api/videos?q=telecom<strong>sudparis</strong>&max-results=5✫✪✬1.2 REST: Representational State Transfer✩# 5 Architectural style defined by Fielding in 2000 [Fielding, 2000] Described by six identified constraints Client/server architecture: independance between the client and the server Stateless: no client context on the server ↦→ client requests include all thenecessary context Cacheable: clients can cache responses Layered system: clients and servers may be connected through intermediatelayers (e.g.. proxies) Code on demand: the state may include code (e.g., javascript) Uniform interface between clients and servers World Wide Web conforms to the REST architectural style Applications that conform to this architectural style are called RESTful Main advantages: scalability, simplicity of interfaces✫✪“REST’s client-server separation of concerns simplifies component implementation, reduces the complexityof connector semantics, improves the effectiveness of performance tuning, and increases the scalability ofpure server components. Layered system constraints allow intermediaries - proxies, gateways, and firewalls- to be introduced at various points in the communication without changing the interfaces between components,thus allowing them to assist in communication translation or improve performance via large-scale,shared caching. REST enables intermediate processing by constraining messages to be self-descriptive: interactionis stateless between requests, standard methods and media types are used to indicate semanticsand exchange information, and responses explicitly indicate cacheability.” R. FieldingTélécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 31RESTful WebServices in Java 1 Introduction✬✩1.3 REST resource# 6 Any (web) resource Identified by a global identifier (e.g. URI: Uniform Resource Identification) State of a resource may be transfered through a representation of this resource✫✪✬1.4 Uniform interface: CRUD operations✩# 7 Requests and responses are built around the transfer of representations ofresources Requests are one of the four CRUD Operations: Create ↦→ POST http method Read ↦→ GET http method Update ↦→ PUT http method Delete ↦→ DELETE http method✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 32


RESTful WebServices in Java 1 Introduction✬✩1.5 Are these operations sufficient to build an application ?# 8Resource Create Read Update DeletePOST GET PUT DELETECollection Create entry List entries Replace collection Delete collectionElement / Get element Replace element Delete element✫✪✬1.6 Representation formats✩# 9 Resources are distinct from their possible representations Format of a representation (i.e. content type) is defined by anInternet media type (previously known as a MIME type) Some common formats plain text: text/plain html: text/html xml: text/xml, application/xml code: application/javascript json: application/json image: image/jpeg, image/png, image/* video: video/mpeg✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 33RESTful WebServices in Java 2 Hyper Text Transfer Protocol: basics reminder✬✩1.7 How to implement a RESTful service ?# 10 Resource available through a web server Resource available through an application server (e.g. JEE) Resource maintained by light servers (e.g., home made http server with jerseycontainers) Resources may be implemented with many languages PHP C++ Java classes following the JAX-RS specification (several implementations, e.g.,jersey) . . .✫✪✬2 Hyper Text Transfer Protocol: basics reminder✩# 112.1 HTTP GET Request message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132.3 HTTP Response message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162.3 HTTP GET vs POST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 34


RESTful WebServices in Java 2 Hyper Text Transfer Protocol: basics reminder✬✩2.1 HTTP GET Request messageGET /hello HTTP/1.1Accept: text/plain, text/html%---empty line: end of header# 12 Sent to a web server to access one of its web resource Request message (message method, identification of the resource inside theserver, http version)◮ for example: GET /hello HTTP/1.1 Request Headers◮ accepted content types (e.g. Accept: text/plain, text/html)◮ accepted charsets (e.g. Accept-Charset: utf-8)◮ cookie (e.g. Cookie: Version=1; Skin=new;) Request body (not necessary for a get)✫✬✪✩ Give it a trytelnet www-tp.tem-tsp.<strong>eu</strong> 80GET /~taconet/index.html HTTP 1.0telnet www-inf.it-<strong>sudparis</strong>.<strong>eu</strong>GET /COURS/(\codemodule)/Documents/HTML/index.htmlRETURN# 13✫✪Do you speak http fluently ?You can test your http language ability with a telnet on port 80, here is an example dialog, but not soeasy . . . , simpler with a browser.telnet www-tp.tem-tsp.<strong>eu</strong> 80Trying 157.159.10.123...Connected to www-tp3.int-evry.fr.Escape character is '^]'.GET /~taconet/index.html HTTP 1.0HTTP/1.1 200 OKDate: Mon, 23 Sep 2013 09:24:33 GMTServer: Apache/2.2.15 (CentOS)Last-Modified: Mon, 16 Feb 2009 15:45:07 GMTETag: "61f04-1a0-4630b122446c0"Accept-Ranges: bytesContent-Length: 416Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 35RESTful WebServices in Java 2 Hyper Text Transfer Protocol: basics reminderConnection: closeContent-Type: text/html; charset=UTF-8Content-Language: frCSC 3502 (CI1/2)Module CSC 3502Bonjour Ãă tous.Connection closed by foreign host.✬2.2 HTTP Response message✩# 14HTTP/1.1 200 OK return codeDate: Mon, 11 Nov 2013 17:47:24 GMT header (begin)Server: Apachee/2.2.3 (Debian GNU/Linux)Perl/v5.8.4 PHP/5.2.6Last-Modified: Wed, 28 Apr 2012 15:55:02 GMTContent-length: 327Content-type: text/htmlempty line (end of header) content... document HTML Return code 100 - 199: Information message 200 - 299: Success (e.g., 200 OK) 300 - 399: Redirections 400 - 499 : client-side errors (e.g., 404 Not Found, 403 Forbidden) 500 - 599 : server-side errors (e.g., 500 Internal Server Error) Header Resource content✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 36


RESTful WebServices in Java✬✩2.3 HTTP GET vs POST# 15 GET method, gets data, it has no input For input, use POST to create or PUT to update But, for HTML forms, which do have inputs, both GET and POST are usedMethod GET POSTHTML URL http://www-inf/AfficheGET.php?Nom=Taconet&Prenom=Chantal http://www-inf/POSTForm.htmlHTTP GET /AfficheGET.php?Nom=Taconet&Prenom=Chantal HTTP/1.1 POST AffichePOST.html HTTP/1.1Host: www-inf.it-<strong>sudparis</strong>.<strong>eu</strong> Host: www-inf.it-<strong>sudparis</strong>.<strong>eu</strong>Content-Type: application/x-www-form-urlencodedContent-length: 27Nom=Taconet&Prenom=Chantal GET method easiest to test through WebBrowsers . . . but should not be used toupdate or create REST resources✫✪✬✩ Give it a trytelnet www-inf.it-<strong>sudparis</strong>.<strong>eu</strong> 80POST /COURS/(\codemodule)/Documents/HTML/AffichePOST.php HTTP/1.1Host: www-inf.it-<strong>sudparis</strong>.<strong>eu</strong>Content-Type: application/x-www-form-urlencodedContent-length: 27Nom=Taconet&Prenom=Chantaltelnet www-inf.it-<strong>sudparis</strong>.<strong>eu</strong> 80GET /COURS/(\codemodule)/Documents/HTML/AfficheGET.php?Nom=Taconet&Prenom=Chantal HTTP/1.1Host: www-inf.it-<strong>sudparis</strong>.<strong>eu</strong># 16RETURN✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 37RESTful WebServices in Java 3 Representation of a Java object✬✩3 Representation of a Java object# 173.2 JAXB - Java Architecture for XML Binding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .203.2 JAXB data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203.3 JAXB annotations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .213.4 JAXB annotations example file. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .243.5 JAXB in action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273.7 Handling cycles in JAXB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293.7 Json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293.9 Json in gson . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323.9 Skier in json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323.10 gson custom serialization/deserialization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34✫✪✬3.1 JAXB - Java Architecture for XML Binding✩# 18 JAXB used to transfer complex java objects in XML structured strings Marshalling: Convert a Java object into an XML file Unmarshalling: Convert an XML content into a Java Object✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 38


RESTful WebServices in Java 3 Representation of a Java object✬✩3.2 JAXB data types Java basic types have a representation in xs typesJava type xs typejava.lang.String xs:stringint xs:int# 19double xs:doubleboolean xs:booleanjava.util.Date xs:dateTime What about complex type ?✫✪✬✩java ClassXSD schema# 20public class Person {private String name;private int age;private String gender;...}Java objectXML documentPerson p=new Person("Bjoern Daehlie", 41, "Male");Bjoern Daehlie41Male✫✪How to write a class serializable with JAXB:• Get and set methods for each private attributeor use the @XmlAccessorType(XmlAccessType.FIELD) all the attributes are• Provice an empty constructorTélécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 39RESTful WebServices in Java 3 Representation of a Java object✬✩3.3 JAXB annotationsAnnotation Description@XmlRootElement(namespace ="namespace")Root element for an XML tree@XmlType(propOrder = "field2","field1",.. )XSD Type, order of fields# 21@XmlElement(name ="newName")Rename a field (element)@XmlAttribute Translated into an attribute (rather than anelement)@XmlTransient Not translated into XMLall attributes translated (by default, onlypublic + getter/setter@XmlAccessorType(XmlAccessType.FIELD)@XmlElementWrapper(name="")✫Add a wrapper XML element✪✬3.4 JAXB annotations example file✩# 22import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlElementWrapper;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlAccessType;import java.util.Collection;@XmlRootElement@XmlAccessorType(XmlAccessType.FIELD)public class Skier extends Person {private String nationalTeam;@XmlElementWrapper(name = "achievements") @XmlElement(name="achievement")private Collection achievements;public Skier() { }public Skier (Person person, String nationalTeam, Collection achievements) {super(person);this.nationalTeam=nationalTeam;this.achievements=achievements;}}✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 40


RESTful WebServices in Java 3 Representation of a Java object✬✩import javax.xml.bind.annotation.XmlType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlAccessType;# 23// All the fields, even the private ones are in the XML@XmlAccessorType(XmlAccessType.FIELD)public class Person {private String name;private int age;private String gender;}public Person() { }public Person(Person person) {this(person.name,person.age,person.gender);}public Person(String name, int age, String gender){this.name=name;this.age=age;this.gender=gender;}✫✪✬✩Example XML Document for a Skier object# 24Bjoern Daehlie41MaleNorway12 Olympic Medals9 World ChampionshipsWinningest Winter OlympianGreatest Nordic Skier✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 41RESTful WebServices in Java 3 Representation of a Java object✬✩3.5 JAXB in action# 25JDK commands Java Class to XSD : schemagen XSD to java class : xjc✫✪✬✩ Using the JAXB API to marshall and unmarshallclass Marshal {private static final String file_name = "bd.mar";private Skier createSkier() {Person bjoern = new Person("Bjoern Daehlie", 41, "Male");List listMajorAchievements = new ArrayList();# 26}listMajorAchievements.add("12 Olympic Medals");listMajorAchievements.add("9 World Championships");listMajorAchievements.add("Winningest Winter Olympian");listMajorAchievements.add("Greatest Nordic Skier");return new Skier(bjoern, "Norway", listMajorAchievements);public static void main(String[ ] args) throws JAXBException,IOException {new Marshal().run_example();}✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 42


RESTful WebServices in Java 3 Representation of a Java object✬✩# 27}private void run_example() throws JAXBException,IOException {JAXBContext ctx = JAXBContext.newInstance(Skier.class);Marshaller m = ctx.createMarshaller();m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// Marshal a Skier object: 1st to stdout, 2nd to fileSkier skier = createSkier();m.marshal(skier, System.out);FileOutputStream out = new FileOutputStream(file_name);m.marshal(skier, out);out.close();// Unmarshal as proof of conceptUnmarshaller u = ctx.createUnmarshaller();Skier clone = (Skier) u.unmarshal(new File(file_name));System.out.println();m.marshal(clone, System.out);}✫✪✬3.6 Handling cycles in JAXB @XmlTransient attribute not marshalled beforeUnmarshal and afterUnmarshal: callbacks called (when defined) before andafter unmarshalling✩# 28@XmlRootElementclass Department {@XmlAttribute String name;@XmlElement(name="employee") List employees;}class Employee {}@XmlTransient Department department; // parent pointer not marshalled@XmlAttribute String name;public void afterUnmarshal(Unmarshaller u, Object parent) { // after JAXB unmarshallthis.department = (Department)parent;}✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 43RESTful WebServices in Java 3 Representation of a Java object✬✩3.7 Json# 29 Json as an alternative representation of objects JSON (JavaScript Object Notation) is a lightweight data-interchange format. Itis easy for humans to read and write. It is easy for machines to parse and generate.(json.org) Example in Json, object with an array membermyObject = {"first": "John","last": "Doe","age": 39,"sex": "M","salary": 70000,"registered": true,"interests": [ "Reading", "Mountain Biking", "Hacking" ]}✫✪✬3.8 Json in gson✩ Many primitives to serialize/deserialize Json strings, google json is one of them A field declared as transient will not be serialized# 30class BagOfPrimitives {private int value1 = 1;private String value2 = "abc";private transient int value3 = 3;BagOfPrimitives() {}}//(Serialization)BagOfPrimitives obj = new BagOfPrimitives();Gson gson = new Gson();String json = gson.toJson(obj);//==> json is {"value1":1,"value2":"abc"}//Note that you can not serialize objects with circular references since that will result in infinite recursion.//(Deserialization)BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);//==> obj2 is just like obj✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 44


RESTful WebServices in Java 3 Representation of a Java object✬✩3.9 Skier in json# 31public class Person {private String name;private int age;private String gender;public Person() { }public Person(Person person) {this(person.name, person.age, person.gender);}public Person(String name, int age, String gender){this.name=name; this.age=age; this.gender=gender;}}public class Skier extends Person {private String nationalTeam;private Collection achievements;public Skier() { }public Skier (Person person, String nationalTeam, Collection achievements) {super(person); this.nationalTeam=nationalTeam; this.achievements=achievements;}}✫✪✬✩# 32private void run_example() {try {Gson gson = new Gson();// Marshal a Skier object: 1st to stdout, 2nd to fileSkier skier = createSkier();String json = gson.toJson(skier);System.out.println("The initial skier: "+json);PrintWriter out = new PrintWriter(file_name);out.println(json);out.close();// Unmarshal as proof of conceptSkier clone = (Skier) gson.fromJson(json, Skier.class);json = gson.toJson(clone);System.out.println("His clone: "+json);}catch(IOException e) { System.err.println(e);}}1 {"nationalTeam":"Norway","achievements":["12 Olympic Medals","9 World \Championships","Winningest Winter Olympian","Greatest Nordic Skier"],"name":"Bjoern \Daehlie","age":41,"gender":"Male"}✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 45RESTful WebServices in Java✬✩3.10 gson custom serialization/deserialization For specific purpose, one can customs serializers# 33public class ProductJsonSerializer implements JsonSerializer {@Overridepublic JsonElement serialize(final Product product, final Type typeOfSrc, final \JsonSerializationContext context) {final JsonObject json = new JsonObject();json.addProperty("i", product.getId());json.addProperty("n", product.getName());json.addProperty("p", product.getPrice());final JsonArray categoriesArray = new JsonArray();json.add("c", categoriesArray);for (final Category category : product.getCategories()) {categoriesArray.add(context.serialize(category));}}}return json;✫✪✬✩ For specific purpose, one can custom deserializers# 34public class ProductJsonDeserializer implements JsonDeserializer {@Overridepublic Product deserialize(final JsonElement json, final Type typeOfT, final \JsonDeserializationContext context) throws JsonParseException {Product product = new Product();// Parsing will be done here.return product;}} Register serializer/deserializerGsonBuilder gson = new GsonBuilder();gson.registerTypeAdapter(Product.class, new ProductJsonSerializer());gson.registerTypeAdapter(Product.class, new ProductJsonDeserializer());✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 46


RESTful WebServices in Java 4 Java RESTful service✬✩4 Java RESTful service# 354.2 REST JAX-RS architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374.2 @path annotation and resource URI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374.3 Input or output representation format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394.5 JAXB representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414.5 Path and template parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414.7 Hello World in REST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434.7 Java Client example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434.9 Light server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454.9 Parameter annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454.10 REST Synthesis. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .46✫✪✬4.1 REST JAX-RS architecture✩# 36✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 47RESTful WebServices in Java 4 Java RESTful service✬✩4.2 @path annotation and resource URI Each resource is identified by a URI defined by The server URLhttp://localhost:9999/MyServer/ The root resource class◮ @path annotation for a RestFul java class# 37@Path("/hello") // http://localhost:9999/MyServer/hellopublic class Hello {} Additionnally, a method may have a subidentification@Path("replace") //http://localhost:9999/MyServer/hello/replacepublic String replace(...) {}method SubPath CRUD http msg parameters presentation✫replace replace update TBD TBD TBD✪✬4.3 Input or output representation format✩# 38 Defined with @consumes for input (POST and PUT) and @produces for output(GET) Defined for a class and/or overloaded on a method Client requirement and server representation offers should match✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 48


RESTful WebServices in Java 4 Java RESTful service✬✩ Client requirement defined in the GET requestGET /hello HTTP/1.1Host: localhostAccept: text/html, text/plain Service offeree# 39@GET@Produces("text/html")public String readHTML() {return ""+msg + "";}method SubPath CRUD http msg parameters presentationreadHTML / read GET / HTML Matching representation defined in the response headerHTTP/1.1 200 OKContent-Type: text/htmlHello✫✪✬4.4 JAXB representation✩ @produces("application/xml") Return type is a class annotated @XmlRootElement or @XmlType# 40@GET@Path("searchskier")//http://localhost:9999/MyServer/skiers/searchskier?name=xxx@produces("application/xml")public Skier getSkier(@QueryParam("name") String name){}...Skier foundSkier= lookup(name);return foundSkier; // marshalled in XML with JAXBmethod SubPath CRUD http msg parameters presentationgetSkier searchskier?name= read GET name XML✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 49RESTful WebServices in Java 4 Java RESTful service✬✩4.5 Path and template parameters Parameters included in the URL Requested URLhttp://localhost:9999/MyServer/calc/add?a=3&b=4 Method definition# 41@Path("/calc")public class CalcRest {@GET@Path("/add")@Produces(MediaType.TEXT_PLAIN)public String addPlainText(@QueryParam("a") double a, @QueryParam("b") double b) {return (a + b) + "";}method SubPath CRUD http msg parameters presentation✫addPlainText add?a=&b= read GET a,b TEXT✪✬4.6 Hello World in REST✩# 42@Path("/hello") public class HelloRest {private static String msg = "Hello world";@GET @Produces("text/plain") public String read() {return msg + "\n"; }@GET @Produces("text/html") public String readHTML() {return ""+msg +""; }@GET @Produces("text/plain") @Path("/{extra}") // http:..../hello/xxxpublic String personalized_read(@PathParam("extra") String cus) { return HelloRest.msg + ": " + cus + "\n";}@GET @Produces("text/plain") @Path("replace") // http:..../hello/replace?newmsg=xxxpublic String replaceAndRead(@DefaultValue("") @QueryParam("newmsg") String new_msg ) {System.out.println("replaceAndRead new_msg="+new_msg);HelloRest.msg = new_msg;return HelloRest.msg + "\n";@PUT @Consumes("text/plain") @Path("replace") public void replace(String new_msg) {System.out.println("replace new_msg="+new_msg);HelloRest.msg = new_msg;@DELETE @Path("/delete") public void delete() {HelloRest.msg = "";System.out.println( "Message deleted.\n");method SubPath CRUD http msg parameters presentationread / read GET / TEXTreadHTML / read GET / HTMLpersonalized_read {extra} read GET extra TEXTreplaceAndRead replace?newmsg= read :-( GET newmsg TEXTreplace replace update PUT newmsg TEXT✫delete delete delete DELETE / /✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 50}}}}


RESTful WebServices in Java 4 Java RESTful service✬✩4.7 Java Client examplepublic class HelloRestClient {static final String REST_URI = "http://localhost:9999/MyServer/";# 43public static void main(String[] args) {Client client = Client.create(new DefaultClientConfig());URI uri=UriBuilder.fromUri(REST_URI).build();WebResource service = client.resource(uri);// Get plain textSystem.out.println(uri+"hello GET TEXT_PLAIN");System.out.println("hello output as plain text : "+service.path("hello").accept(MediaType.TEXT_PLAIN).get(String.class));System.out.println("---------------------------------------------------");System.out.println(uri+"hello/replace PUT coucou TEXT_PLAIN");service.path("hello").path("replace").put("coucou");System.out.println("---------------------------------------------------");System.out.println(uri+"hello/delete DELETE TEXT_PLAIN");service.path("hello").path("delete").delete();System.out.println("---------------------------------------------------");✫✪✬4.8 Light server✩public class Publisher {static final String BASE_URI = "http://localhost:9999/MyServer/";# 44public static void main(String[] args) {try {HttpServer server = HttpServerFactory.create(BASE_URI);// The root resources in the java path will be automatically detectedserver.start();System.out.println("Browse the available operations with this URL : "+BASE_URI+"application.wadl");System.out.println("Press Enter to stop the server. ");System.in.read();System.out.println("Server stopped.");server.stop(0);} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 51RESTful WebServices in Java 4 Java RESTful service✬✩4.9 Parameter annotations# 45 @pathparam: in the path (hello/coucou) @queryparam: in the URL (hello?newmsg=coucou) @FormParam: input from a form through a POST @HeaderParam: in the http header @CookieParam: in a cookie✫✪✬4.10 REST Synthesis✩# 46 Easy to write and easy to test RESTful WebServices As a consequence, a high percentage of deployed web services are RESTfulservices No service interface language: Interface of services have to be well documented Not so natural to write java REST clients (one has to construct the method call)✫✪References[Burke, 2010] Burke, B. (2010). RESTful Java. O’Reilly.[Fielding, 2000] Fielding, R. T. (2000). REST: Architectural Styles and the Design of Network-based SoftwareArchitectures. Doctoral dissertation, University of California, Irvine.[Kalin, 2010] Kalin, M. (2010). Java Web Services, Up and Running. O’Reilly.Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 52}}}


Middleware for synchronousrequests illustrated withWebServicesSophie Chabridon and Chantal TaconetASR/CSC50023 novembre 201453Middleware for synchronous requests illustrated with WebServices 1 Introduction✬✩Outline# 21 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Synchronous middleware and the big picture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103 CORBA introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 WebService introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .295 Interface definition language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 Distributed Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427 First steps with WebServices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .468 GIOP/IIOP : ORBs interoperability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599 SOAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7110 Conclusions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .77✫✪✬1 Introduction✩# 31.1 Middleware for distribution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41.3 Goal : interoperability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.3 Distribution models. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61.5 Client-server models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.5 Middleware for distributed objects history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.0 Synchronous vs asynchronous mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 54:


Middleware for synchronous requests illustrated with WebServices 1 Introduction✬✩1.1 Middleware for distribution# 4 Middleware is a software layer which provides : Programming interfaces (common API) Protocol for interoperability◮ With data exchange format✫. . . to support distribution and heterogeneity.✪✬1.2 Goal : interoperability✩ Existing “legacy code”, Numerous languages,# 5 Several operating systems, Various hardware (e.g., little endian, big endian), Several network protocols⇒ need for interoperability!✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 55Middleware for synchronous requests illustrated with WebServices 1 Introduction✬✩1.3 Distribution models Point to point message Point to multipoint message# 6 Event/action Publish/subscribe Client/server Mobile code Virtual shared memory✫✪✬1.4 Client-server models✩ Procedural Remote Procedure Call - RPC# 7 Object-oriented Remote Method Invocation (RMI, Common Object Request Broker ArchitectureCORBA) Data-oriented SQL requests REST (Representational State Transfer)- create, read, update, delete over HTTP Traditionnal Web (HTTP requests) Web Services (SOAP over HTTP)✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 56


Middleware for synchronous requests illustrated with WebServices✬✩1.5 Middleware for distributed objects history# 8 Comes from two technologies : Objects (inheritance, encapsulation and polymorphism) RPC or Remote Procedure Call (distribution, heterogeneity, data marshalling andunmarshalling)✫✪✬1.6 Synchronous vs asynchronous mode✩ Two entities (e.g., processus) communicate# 9 In synchronous mode: the two entities (client and server) are active at the sametime, after a request, client is waiting for server response. In asynchronous mode: entities send messages, they don’t wait for responses,they don’t know when the message will be delivered✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 57Middleware for synchronous requests illustrated with WebServices 2 Synchronous middleware and the big picture✬✩2 Synchronous middleware and the big picture# 10✫✪✬2.1 Introduction of the distributed example✩# 11 Which distribution ? Which abstractions (service, object) ? Which middleware ?✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 58


Middleware for synchronous requests illustrated with WebServices 2 Synchronous middleware and the big picture✬✩2.2 Principle of distributed objects# 12✫✪✬2.3 The stub and the skeleton✩# 13Request semantics: synchronous : client is blocked during the call “at most once”✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 59Middleware for synchronous requests illustrated with WebServices 2 Synchronous middleware and the big picture✬✩2.4 Proxy Object and inheritance tree# 14✫✪✬2.5 Distribution Implementation Process✩# 151. Description of the interface in IDL2. IDL compiler creates the stub and theskeleton3. Write both client and serverimplementations✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 60


Middleware for synchronous requests illustrated with WebServices 2 Synchronous middleware and the big picture✬✩2.6 Multi-languages (or multi-ORBs, or multi-OSs)# 16✫✪✬2.7 Distribution implications✩# 17 Objects/service implementation are in different spaces (not the same process, notthe same computer . . . ): Assign a unique identifier to each object/service in different spaces Localize objects/service implementations Transports requests and replys Use of a n<strong>eu</strong>tral network format for the data✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 61Middleware for synchronous requests illustrated with WebServices 2 Synchronous middleware and the big picture✬✩2.8 Invocation sequence diagram# 18✫✪✬2.9 Middleware for synchronous requests : main concepts✩# 19✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 62


Middleware for synchronous requests illustrated with WebServices 2 Synchronous middleware and the big picture✬✩2.10 Inherent complexity of distribution No global state Poor debugging tools# 20 Partial failures, network partition Requests in parallel (concurrency management) Trusting the caller (authentication)✫✪✬2.11 Main distributed object middleware✩CORBA (OMG) 1991Java RMI (Sun) 1997DCOM (Microsoft) 1998.net (Microsoft) 2001WebService (w3C) 2001# 21✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 63Middleware for synchronous requests illustrated with WebServices 2 Synchronous middleware and the big picture✬✩2.12 Middleware history# 22✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 64


Middleware for synchronous requests illustrated with WebServices 3 CORBA introduction✬✩3 CORBA introduction# 233.2 CORBA specified by the OMG (Object Management Group). . . . . . . . . . . . . . . . . . . .253.2 CORBA Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253.3 Some CORBA implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26✫✪✬3.1 CORBA specified by the OMG (Object Management Group)✩# 24 International consortium founded in 1989 by 8 companies (3Com Corporation, AmericanAirlines, Canon Inc., Data General, Hewlett-Packard, Philips Telecommunications N.V., SunMicrosystems and Unisys Corporation) In 1998 more than 800 members (computer manufacturers, software vendors,academics...), Some OMG standards: CORBA, UML, MDA, DDS, CCMIts role : promoting distributed objects technologies, and produce specifications(accepted by vote).See (http://www.omg.org)✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 65Middleware for synchronous requests illustrated with WebServices 3 CORBA introduction✬✩3.2 CORBA Overview# 25✫✪✬3.3 Some CORBA implementations✩# 26JDK SUN (java)freeMICO Frankfort University (C++)TAO Washington University (C++)OmniORB AT&T (C++ and Python)✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 66


Middleware for synchronous requests illustrated with WebServices 4 WebService introduction✬✩4 WebService introduction# 274.2 Web Services specified by W3C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.2 Two classes of WebServices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.4 Web Service Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314.4 Some WebServices implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31✫✪✬4.1 Web Services specified by W3C✩# 28 World Wide Web Consortium International standards organization for the World Wide Web created in 1994 2011: 322 members Famous standards : CSS, CGI, DOM, HTML, OWL, SOAP, XML, XPath, WSDL(http://www.w3c.org)✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 67Middleware for synchronous requests illustrated with WebServices 4 WebService introduction✬✩4.2 Two classes of WebServices# 29 REST Web Services Web resources manipulated through a uniform set of operations◮ POST (create resource), GET (read resource), PUT (update resource),DELETE (delete resource) -(CRUD) Arbitrary Web Services Services expose an arbitrary set of operations✫✪✬4.3 Web Service Overview✩# 30✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 68


Middleware for synchronous requests illustrated with WebServices 4 WebService introduction✬✩4.4 Some WebServices implementationsSome platforms among a list of many many Web services platforms(http://en.wikipedia.org/wiki/List_of_web_service_frameworks)# 31JDK(>1.6) JAVA ImplÃľmentation de JAX-WS (Java API for XML Web Services)METRO JAVA Uptodate implementation of JAX-WS (Oracle)glassfish JAVA Implementation of JAX-WS + application server + JavaEE (Oracle)gsoap C, C++ free softwarephp/soap php free software.net C#, VB Microsoft✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 69Middleware for synchronous requests illustrated with WebServices 5 Interface definition language✬✩5 Interface definition language# 325.2 Interface definition language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345.2 CORBA IDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345.4 RMI IDL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .365.4 WSDL: Web Service Definition Language - Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . 365.6 WSDL 1.1 vs WSDL 2.0. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .385.6 WSDL PrintService example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385.8 WSDL: PrintService - text file excerpt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405.8 Design methodologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40✫✪✬5.1 Interface definition language✩ To produce stub and skeletons, middleware use Interface Definition Languages Independent of implementation languages Independent of hardware and operating systems, Independent of implementation (processus, databases, objects. . .# 33✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 70


Middleware for synchronous requests illustrated with WebServices 5 Interface definition language✬✩5.2 CORBA IDL IDL compilers generate stubs and skeleton for (C, C++, Smalltalk, COBOL, ADA,JAVA),. Language2IDL tool may also be used# 34struct PrinterInfo {string printerName; // printer Identifierstring hostName; // computer which hosts the implementation objectlong currentJob; // current Task number};exception PrintDenied {PrinterInfo printerInfo;string reason;};struct JobInfo {long jobNumber;long jobSize;};interface Printer {};PrinterInfo getPrinterInfo ();JobInfo submitPrint (in string fileName) raises (PrintDenied) ;✫✪The CORBA IDL language has been created in 1991 before the Java language (1995). It is closer to theC++ syntax. The difficulty for using CORBA IDL is to learn a new language. Hopefully, we can easilyproduce a CORBA IDL from a Java interface. For example rmic is able to produce a CORBA IDL file froman interface.✬5.3 RMI IDL✩import java.rmi.Remote;import java.rmi.RemoteException;# 35public interface PrinterOperations extends Remote {PrinterInfo getPrinterInfo ( ) throws RemoteException;JobInfo submitPrint ( String fileName)throws PrintDenied, RemoteException;}; RMI client/server are written in JAVA/JAVA JAVA interface is the interface definition language✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 71Middleware for synchronous requests illustrated with WebServices 5 Interface definition language✬✩5.4 WSDL: Web Service Definition Language - Concepts A service may have several ports (operations are grouped in ports) Bindings define protocols, and URL to access a port Each operation is then defined by request, response and fault messages# 36✫WSDL 1.1 (source wikipedia)✪✬5.5 WSDL 1.1 vs WSDL 2.0✩# 37aa source wikipedia✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 72


Middleware for synchronous requests illustrated with WebServices 5 Interface definition language✬✩5.6 WSDL PrintService example# 38✫✪✬5.7 WSDL: PrintService - text file excerpt✩# 39 ... ... ... ✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 73Middleware for synchronous requests illustrated with WebServices 6 Distributed Identification✬✩5.8 Design methodologies# 40 Bottom-Up strategy (for example JAX-WS)1. Write implementation classes/interface with java annotations(@webservice,@webmethod)2. WSDL generating tool to expose some methods as a Web Service Top-Down strategy1. Write WSDL2. Produce the class skeleton (methods to be completed)✫✪• The Printer example is 155 lines long✬6 Distributed Identification✩# 416.1 Distributed Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426.3 CORBA IOR : Interoperable Object Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446.3 Web Services URLs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .44✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 74


Middleware for synchronous requests illustrated with WebServices 6 Distributed Identification✬✩6.1 Distributed Identification# 42 Because of distribution, objects/services don’t share the same space How middleware are able to : Provide unique identifiers Locate distributed entities Transport messages to their destination✫✪✬6.2 CORBA IOR : Interoperable Object Reference✩ An IOR is opaque to developers but ... known by ORB developers. (binary) Its structure is detailed in CORBA core specification# 43✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 75Middleware for synchronous requests illustrated with WebServices 7 First steps with WebServices✬✩6.3 Web Services URLs For each service port : a URL NB: the URL is included in the interface (defined in WSDL)# 44binding="PrinterServiceSoapBinding"


Middleware for synchronous requests illustrated with WebServices 7 First steps with WebServices✬✩7.1 Development steps# 46 On the server side Define the interface of the service with WSDL or with a java interface Translate the WSDL to java interface or java interface to WSDL with anappropriate tool Deploy the implementation in a Web server (or write a server which instantiatesthe service) On the client side Generate the Web Service stub from the URL of the deployed WSDL Write and test the client✫✪✬7.2 The printer manager example✩# 47✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 77Middleware for synchronous requests illustrated with WebServices 7 First steps with WebServices✬✩7.3 Automatic generation of stub and skeleton# 48✫✪✬7.4 Service side: describe the interface of the service✩ For example with a java interface# 49package printer;import javax.jws.WebService;@WebServicepublic interface PrinterService {public PrinterInfo getPrinterInfo();public JobInfo submitPrint (String fileName) throws PrintDenied;}public final class PrinterInfo{...}private String printerName = null;private String hostName = null;private int currentJob = (int)0;✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 78


Middleware for synchronous requests illustrated with WebServices 7 First steps with WebServices✬✩7.5 Service side: provide an implementation of the servicepackage printer;import java.net.*;import java.io.*;import javax.jws.WebMethod;import javax.jws.WebService;import javax.jws.WebParam;# 50@WebService(endpointInterface="printer.PrinterService")public class Printer {private short currentJob;private String printerName;private String hostName;public Printer(String name) {printerName=name;try {hostName=InetAddress.getLocalHost().getHostName();} catch (UnknownHostException u) {hostName="unknown computer";}System.out.println(hostName+ ": Printer "+name+ " instantiation ");}public Printer() {this("hp");}✫@WebMethod()public PrinterInfo getPrinterInfo() {return new PrinterInfo(printerName, hostName, currentJob);}✪✬✩# 51}@WebMethod()public JobInfo submitPrint (@WebParam(name = "fileName", targetNamespace = "")String fileName) \throws PrintDenied {// Open the file and get its sizeSystem.out.println("Printing document : "+ fileName + " on " + printerName);File file=new File(fileName);if (file==null) //throw new PrintDenied(new PrinterInfo(printerName, hostName, currentJob), \fileName+" can't open file");throw new PrintDenied(fileName+" can't open file");if ( ! file.isFile() ) //throw new PrintDenied(new PrinterInfo(printerName, hostName, currentJob), \fileName+" : is not a file");throw new PrintDenied(fileName+" : is not a file");if (currentJob > 5) {System.out.println("I am definitely overloaded, you must restart !");throw new PrintDenied("overloaded");}}currentJob++;System.out.println("... "+ " size " + file.length()+ " Current Job : "+currentJob);return new JobInfo(currentJob, (int)file.length());✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 79Middleware for synchronous requests illustrated with WebServices 7 First steps with WebServices✬✩7.6 JAX-WS annotations @WebService Marks a Java class as implementing a Web Service, or a Java interfaceas defining a Web Service interface.// Link the class and the interface@WebService(endpointInterface="printer.PrinterService")public class Printer {# 52 @WebMethod : Customizes a method that is exposed as a Web Service operation. @OneWay : the web method has only an input message and no output @WebParam: Customizes the mapping of an individual parameter to a Web Servicemessage part and XML element @WebResult: Customizes the mapping of the return value to a WSDL part andXML element.@WebMethod(operationName="add") // for different names in WSDL@WebResult(name="return")public int addNumbers(@WebParam(name="num1")int number1,@WebParam(name="num2")int number2);@OneWaypublic void checkIn(String name);✫✪✬7.7 Service side: write the publisher✩package printer;import javax.xml.ws.Endpoint;public class PrinterServerPublisher {# 53protected PrinterServerPublisher() throws Exception {// START SNIPPET: publishSystem.out.println("Starting Server");Printer printer = new Printer();String address = "http://localhost:9000/PrinterService";Endpoint.publish(address, printer);// END SNIPPET: publish}public static void main(String args[]) throws Exception {new PrinterServer();System.out.println("Server ready...");}}✫Thread.sleep(360 *60 *1000);System.out.println("Server exiting");System.exit(0);✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 80


Middleware for synchronous requests illustrated with WebServices 7 First steps with WebServices✬✩7.8 Start the service Compile everything Starts the publisher# 54java -cp class printer.PrinterServerPublisher In a navigator, verify that the service is deployed URL (http://localhost:9000/PrinterService) And have a look on the wsdl URL (http://localhost:9000/PrinterService?wsdl)✫✪✬7.9 Client side: generate the stub✩ Produce the stub from the URL URL(http://localhost:9000/PrinterService?wsdl) with wsimport# 55wsimport -d class -s generated -keep http://localhost:9000/PrinterService?wsdl✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 81Middleware for synchronous requests illustrated with WebServices 7 First steps with WebServices✬✩7.10 Client side in java Write, compile and test a client# 56import printer.*;public class PrinterClient {public static void main (String [] args){try{if ( args.length < 1) {System.out.println("usage: java ClassName" + " file_name");System.exit (-1);}}}String fileToPrint=args[0];PrinterService printerService = new PrinterService_Service().getPrinterPort();PrinterInfo printerInfo=printerService.getPrinterInfo();System.out.println("Printer :"+printerInfo.getPrinterName()+" \n\t on machine " + \printerInfo.getHostName() + " \n\t running task : " + printerInfo.getCurrentJob() + "\n");JobInfo jobInfo=printerService.submitPrint(fileToPrint);System.out.println("\n submitPrint("+fileToPrint+")"+"Job "+ jobInfo.getJobNumber()+": \"+jobInfo.getJobSize()+ " bytes");}catch(Exception e) {System.out.println(e);}✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 82


Middleware for synchronous requests illustrated with WebServices 8 GIOP/IIOP : ORBs interoperability✬✩8 GIOP/IIOP : ORBs interoperability# 578.2 Inter ORB - Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598.2 GIOP functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598.4 CDR : Common Data Representation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .618.4 GIOP/IIOP Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618.6 GIOP/IIOP Sequence Diagram. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .638.6 GIOP headers : MessageHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638.8 GIOP headers : RequestHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658.8 GIOP headers : ReplyHeader. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .658.10 GIOP headers : LocateRequestHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678.10 GIOP headers : LocateReplyHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678.12 IIOP (Internet InterOrb Protocol) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698.12 IIOP : connection management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69✫✪✬8.1 Inter ORB - IntroductionIDL → interoperability between a client and a serverGIOP → interoperability between ORBs) GIOP : General Inter-ORB Protocol IIOP: Internet Inter-ORB Protocol (GIOP application to TCP/IP)✩# 58✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 83Middleware for synchronous requests illustrated with WebServices 8 GIOP/IIOP : ORBs interoperability✬✩8.2 GIOP functions# 59 Common Data Representation : CDR Interoperable Object Reference : IOR Inter ORB Protocol : IOP (8 message types) applied to different transport protocols (connection oriented, reliable, ordered dataflows).✫✪✬8.3 CDR : Common Data Representation✩# 60 Byte order defined by source coding mode: all messages include a LittleIndian or BigEndian flag, the destination is responsible for reordering bytes. CDR representation of all CORBA-IDL types type alignment definition, the decoding of a CDR message requires the IDL description of the associatedrequest✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 84


Middleware for synchronous requests illustrated with WebServices 8 GIOP/IIOP : ORBs interoperability✬✩8.4 GIOP/IIOP Messagesmessage origin numberRequest client 0Reply server 1# 61CancelRequest client 2LocateRequest client 3LocateReply server 4CloseConnection server 5MessageError client or server 6Fragment client or server 7✫✪✬8.5 GIOP/IIOP Sequence Diagram✩# 62✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 85Middleware for synchronous requests illustrated with WebServices 8 GIOP/IIOP : ORBs interoperability✬✩8.6 GIOP headers : MessageHeader# 63struct MessageHeader_1_1 {char magic [4];Version GIOP_version;octet flags; // GIOP 1.1 changeoctet message_type;unsigned long message_size;};✫✪✬8.7 GIOP headers : RequestHeader✩# 64struct RequestHeader_1_1 {IOP::ServiceContextList service_context;unsigned long request_id;boolean response_expected;octet reserved[3]; // Added in GIOP 1.1sequence object_key;string operation;Principal requesting_principal;};✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 86


Middleware for synchronous requests illustrated with WebServices 8 GIOP/IIOP : ORBs interoperability✬✩8.8 GIOP headers : ReplyHeader# 65enum ReplyStatusType {NO_EXCEPTION,USER_EXCEPTION,SYSTEM_EXCEPTION,LOCATION_FORWARD};struct ReplyHeader {IOP::ServiceContextList service_context;unsigned long request_id;ReplyStatusType reply_status; };✫✪✬8.9 GIOP headers : LocateRequestHeader✩# 66struct LocateRequestHeader {unsigned long request_id;sequence object_key;};✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 87Middleware for synchronous requests illustrated with WebServices 8 GIOP/IIOP : ORBs interoperability✬✩8.10 GIOP headers : LocateReplyHeader# 67enum LocateStatusType {UNKNOWN_OBJECT,OBJECT_HERE,OBJECT_FORWARD};struct LocateReplyHeader {unsigned long request_id;LocateStatusType locate_status;};✫✪✬8.11 IIOP (Internet InterOrb Protocol)✩# 68 GIOP adaptation to TCP transport protocol Any ORB (CORBA 2.0 compliant) must support IIOP. Java RMI uses also IIOP protocol✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 88


Middleware for synchronous requests illustrated with WebServices 9 SOAP✬✩8.12 IIOP : connection management# 69 The client uses the address contained in the IOR to establish a TCP connection. Servers are awaiting connections (accept()). After a connection is established, the client can send messages of type Request,LocateRequest, CancelRequest, and the server can respond by Reply,LocateReply or CloseConnection. The client has the initiative to close the connection. However the server can ask forconnection closing (CloseConnection) when it lacks of resources.✫✪✬9 SOAP✩# 709.1 SOAP envelop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719.3 From Java method to SOAP body . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749.3 SOAP over HTTP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 89Middleware for synchronous requests illustrated with WebServices 9 SOAP✬✩9.1 SOAP envelop# 71 Envelope Namespace declarations Header◮ Authentification◮ Session◮ . . . Body◮ Method (request, response,fault) and parameters✫✪✬9.2 From Java method to SOAP body✩ Java methodpublic void myMethod(int x, float y); WSDL1.1 message (RPC encoded)# 72 SOAP body (RPC encoded) 55.0 ✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 90


Middleware for synchronous requests illustrated with WebServices 9 SOAP✬✩9.3 SOAP over HTTP SOAP request (Document encoded)POST /InStock HTTP/1.1Host: www.example.orgContent-Type: application/soap+xml; charset=utf-8Content-Length: nnn# 73IBM✫✪✬✩ SOAP response (Document encoded)HTTP/1.1 200 OKContent-Type: application/soap+xml; charset=utf-8Content-Length: nnn# 7434.5✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 91Middleware for synchronous requests illustrated with WebServices 10 Conclusions✬✩10 Conclusions# 7510.2 Comparison CORBA/RMI/WebServices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7710.2 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77✫✪✬10.1 Comparison CORBA/RMI/WebServices✩CORBA RMI Web ServicesOrigin OMG SUN W3COS multiples multiples multiples# 76Prog. language multiples Java multiplesIDL IDL CORBA interface Java WSDLdata presentation CDR Java serialisation SOAP Envelopeprotocole IIOP / GIOP JRMP ou IIOP SOAP Protocol above HTTP, SMTP, ...connexions connected connected short connexionsobject references IOR (location independant) symbolic names/IP+port URL (included in WSDL)naming service NS, trading RMI registry, JNDI UDDI, WSILmain advantages services/efficiency easy to use in java messages auto describedmain difficulties complex to learn Java/Java lack of services✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 92


Middleware for synchronous requests illustrated with WebServices 10 Conclusions✬✩10.2 Conclusions# 77 Distributed middleware market not stabilized, Granularity of distribution variable (object, service), Complexity of distribution Synchronous request middleware is the necessary foundation to build higher levelmiddleware Middleware services (e.g. name service, yellow pages) Message Oriented Middleware (MOM) (asynchronous middleware) Application servers Component middleware Compositions and orchestrations Model Driven approach and generation tools for code generation towards differentmiddleware platforms✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 93Middleware for synchronous requests illustrated with WebServices 10 ConclusionsReferences[Kalin, 2010] Kalin, M. (2010). Java Web Services, Up and Running. O’Reilly.[Krakowiak, 2009] Krakowiak, S. (2009). Middleware Architecture with Patterns and Frameworks.http://sardes.inrialpes.fr/ krakowia/MW-Book/ (.)[Object-Managment-Group, 2002] Object-Managment-Group (July 2002). The Common Object RequestBroker: Architecture and Specification version 3.0. OMG Documents formal/02-06-01.... and omg.org, w3c.orgTélécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 94


Message Oriented Middlewareillustrated with JMSChantal TaconetASR/CSC50023 novembre 201495Message Oriented Middleware illustrated with JMS 1 Introduction✬✩Outline# 21 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 JMS concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 JMS programming model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .224 Advanced JMS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .32✫✪✬1 Introduction✩# 31.1 MOM overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41.3 MOM and the big picture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61.3 Some use cases and their requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.5 Loosely coupled producers and consumers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.5 Consumers, producers,qu<strong>eu</strong>es: 2 use cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.7 Communication channel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.7 Pull model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.9 Push model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.9 Publish/subscribe model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.0 Some MOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 96


Message Oriented Middleware illustrated with JMS 1 Introduction✬✩1.1 MOM overview# 4 MOM (Message Oriented Middleware) Alternative to synchronous invocation programming Producer/Consumer vs client/server: Message producers (publisher) Message consumers (subscriber) Enable communication 1 to n, n to 1, or n to n Asynchronous communication between producers and consumers Decouple clients and servers When direct connections between communication entities are notpossible/needed Several semantics according to requirements◮ Efficiency, scalability◮ Reliability✫✪✬1.2 MOM and the big picture✩Structural CompositionsActivity OrchestrationsSCABPELApplication servers− Life cycle (instantiate)− Persistency# 5JEEMessage Oriented MiddlewareJMSWebServices/JavaRMI/CORBASynchronous Distributed RequestssocketsTCP/UDP✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 97Message Oriented Middleware illustrated with JMS 1 Introduction✬✩1.3 Some use cases and their requirements# 6 Order application for a mobile sailman Connection deconnection handling, reliability Emails Deconnection handling, reliability, eventually delivered, routing protocol betweensource and target Network of sensors, monitoring (e.g. Ambient Assisting Living) Efficiency, multi-point Update planes cockpit databases Connection deconnection handling, reliability, eventually delivered, multi-point On line gaming: time critical delivery Efficiency: time critical delivery Consistency in P2P Scalability, eventually delivery✫✪✬1.4 Loosely coupled producers and consumers✩# 7 Spatially: Producers and consumers are not directly linked together but through amessage channel Producers and consumers don’t even need to know their identifications Temporally: Message transmission time between the consumer and the producer unknown Consumers and producers don’t have to be available at the same time Syntactically: Producers and consumers are not linked with a common API(compared to RMI)✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 98


Message Oriented Middleware illustrated with JMS 1 Introduction✬✩1.5 Consumers, producers,qu<strong>eu</strong>es: 2 use cases 1 producer, 1 consumer, several qu<strong>eu</strong>es# 8 n producers, n consumers, 1 qu<strong>eu</strong>e✫✪✬1.6 Communication channel✩ Producers and consumers are linked through a third entity: the message channel# 9producerconsumerproducerchannelconsumer✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 99Message Oriented Middleware illustrated with JMS 1 Introduction✬✩1.7 Pull model Producer and consumer are active Consumer fetches messages# 10:Producer :Channel:Consumerpush(message)message=pull()✫✪✬1.8 Push model✩ Producer and channel are active Consumer receives messages Consumer has to register a handler# 11:Producer :Channel:Consumerpush(message)push(message)✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 100


Message Oriented Middleware illustrated with JMS✬✩1.9 Publish/subscribe model Producers for a topic are publishers Consumers for a topic are subscribers Messages are delivered to all the subscribed consumers:Producer :Channel c1:Consumer c2:Consumer# 12 register(topic)subscribe(topic)subscribe(topic)publish(topic,message)push(topic,message)push(topic,message)✫✪✬1.10 Some MOM✩# 13 TIBCO (Event enabled Enterprise) JMS (Java Message Service): JORAM (ObjectWeb), Swift MQ, WebsphereMQ,ActiveMQ (apache) RabbitMQ (VMWare, many languages and OS supported) CORBA notification service IBM MQ (Message Qu<strong>eu</strong>es) MSMQ (Microsoft Message Qu<strong>eu</strong>e)✫✪For a study of MOM and comparison read: [Smile, 2009]TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 101Message Oriented Middleware illustrated with JMS 2 JMS concepts✬✩2 JMS concepts# 142.2 Java Message Service. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .162.2 JMS Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162.3 Destinations: Qu<strong>eu</strong>es and Topic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .182.4 Push and pull message consumption. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20✫✪✬2.1 Java Message Service✩# 15 Java API defined by SUN Several JMS implementations Asynchronous: The JMS provider may deliver messages to clients as they arrive Reliable: A message is delivered once and only once✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 102


2 JMS concepts 2.3 Destinations: Qu<strong>eu</strong>es and Topic✬✩2.2 JMS Architecture# 16 JMS clients: Producers and consumers of messages Messages: Objects of communication between JMS clients Administered objects (on the JMS provider side) Connection factories: Create connections between clients (producers orconsumers) and JMS providers Destinations: Communication channelsJMS clientproducer orconsumerJMS Providerconnection factorydestination✫✪✬2.3 Destinations: Qu<strong>eu</strong>es and Topic✩# 17 One JMS provider may host several destination channels 2 messaging domains: qu<strong>eu</strong>es: Point to point◮ n producers — 1 consumer by message◮ A single message will be received by exactly one consumer◮ A qu<strong>eu</strong>e can have many consumers with messages load balanced across theavailable consumers topics: publish/subscribe◮ Topic: n producers (publisher) — n consumers (subscribers to the topic)◮ Each message is received by all the consumers✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 103Message Oriented Middleware illustrated with JMS 2 JMS concepts✬✩2.3.1 Qu<strong>eu</strong>esJMS clientproducer# 18JMS clientproducerqu<strong>eu</strong>esends consumesJMS clientconsumer Each message has only one consumer The consumer can fetch the message whether it was running when the producersent the message or not✫✪✬2.3.2 Topics✩JMS clientproducer(1)JMS clientconsumer# 19JMS clientproducerpublishestopic(1)(2)(2)(1) subscribesthen*(2) deliversJMS clientconsumer Each message may be delivered to multiple consumers Subscribers have to subscribe to topics Publishers and subscribers have a timing dependency: Consumers can only receive messages published after their subscription Consumers have to be active in order for them to consume messages aa Except if the topic subscription is declared durable where consumers may receive messages sentwhile the subscribers are not active✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 104


Message Oriented Middleware illustrated with JMS 3 JMS programming model✬✩2.4 Push and pull message consumption# 20 Two methods may be used for message consumption, regarding the JMS server andthe consumer: Pull: The consumer explicitely fetches the message (calls the receive methodon the destination) Push: The consumer registers a message listener (JMS calls the onMessagemethod of the consumer)✫✪✬3 JMS programming model✩# 213.1 JMS objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223.3 Connection Factory. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .233.5 Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263.5 Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263.5 Destination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263.7 Message Acknowledgment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283.7 Message Producer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .283.9 Message Consumer (pull) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303.9 Message consumer (push with a listener) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 105Message Oriented Middleware illustrated with JMS 3 JMS programming model✬✩3.1 JMS objectsProducer ObjectsConnectionFactory(proxy)createsConsumer ObjectsConnection# 22MessageProducercreatescreatesSessioncreatescreatesMessageConsumersendsTocreatesreceivesFromdestination (proxy)✫✪The figure presents the different concepts (classes) manipulated by an application which uses JMS.• Proxy to Administered objects: (objects on the JMS providers)– Connection factory: proxy to the provider object which creates connections– Destination: proxy to a provider communication channels• Client objects:– Connection: client’s active connection to its JMS provider (i.e., an open TCP/IP socket)– Session: single-threaded context for producing and consuming messages (allow message ordering,include messages in a transaction,– Message producer: a client uses a MessageProducer object to send messages to a destination– Message consumer: a client uses a MessageConsumer object to receive messages from a destination.– Destination✬3.2 Connection Factory✩ Connection Factory is an administered object (follows the factory design pattern) A connection factory is: Access point (or proxy) to a JMS provider Needed to create a connection to a JMS provider# 23ConnectionFactory connectionFactory =new XXXXXConnectionFactory(user, password, url);// url: e.g. tcp://localhost:61616aa class XXXXXConnectionFactory implements interface ConnectionFactory The connectionFactory reference may also be obtained through a naming server.✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 106


Message Oriented Middleware illustrated with JMS 3 JMS programming model✬✩3.3 Connection Encapsulates a TCP/IP socket between a client and a JMS server# 24javax.jms.Connection connection;connection = connectionFactory.createConnection();connection.start();...connection.stop();//temporary stop message delivery...connection.start();...connection.close();✫✪✬3.4 Session✩# 25 Creates MessageProducer and/or MessageConsumer Defines a serial order for the messages it consumes and the messages it produces. Is included in a single thread a May include transactions An acknowledged mode is defined for the sessionjavax.jms.Session session;session = connection.createSession(transactionMode, ackMode);ba to which may be attached a message listenerb several modes to acknowledge each received message✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 107Message Oriented Middleware illustrated with JMS 3 JMS programming model✬✩3.5 Destination# 26 Destination is an administered object; it is a proxy to a communication channel onthe JMS provider; Destination is a communication channel Qu<strong>eu</strong>e for point-to-point domain Topic for publish/subscribeString subject;javax.jms.Session session;javax.jms.Destination destination;destination = session.createTopic(subject);destination = session.createQu<strong>eu</strong>e(subject);aa It may also be obtained through a naming server.✫✪✬3.6 Message Acknowledgment✩# 27 A JMS message has to be acknowledged to be successfully consumed. Message may be acknowledged:1. After the client receives the message2. After the client has finished to process the message According to the chosen mode, acknowledgment is initiated: Automatically by the JMS provider◮ Session.AUTO_ACKNOWLEDGE: The session automatically sends theacknowledgement (after receive() or after onMessage())◮ Session.DUPS_OK_ACKNOWLEDGE: For performance reasons, the JMS provideris authorized to lazily acknowledge and not save its context, possibleduplication of messages if the JMS provider fails. Explicitly in the client business code,◮ Session.CLIENT_ACKNOWLEDGE: The consumer explicitly callsmessage.acknowledge() (after processing it)⋆ one ack acknowledges all the messages previously received by the session✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 108


Message Oriented Middleware illustrated with JMS 3 JMS programming model✬✩3.7 Message Producer Created by a session Sends messages to the destination# 28javax.jms.MessageProducer producer;javax.jms.TextMessage message;producer = session.createProducer(destination);...message = session.createTextMessage(texte);producer.send(message);✫✪✬3.8 Message Consumer (pull)✩ Created by a session Receives messages from a destination# 29javax.jms.MessageConsumer consumer;javax.jms.Message message;consumer = session.createConsumer(destination);message = consumer.receive(); // synchronous receive✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 109Message Oriented Middleware illustrated with JMS 4 Advanced JMS✬✩3.9 Message consumer (push with a listener) Asynchronous event handler for messages Implements interface MessageListener which offers method onMessage A message listener is registered to a MessageConsumer# 30public class MyListener implements MessageListener {public void onMessage(Message message) {...}}MyListener messageListener;consumer.setMessageListener(messageListener);✫✪✬4 Advanced JMS✩# 314.1 Message Selector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324.3 Messages parts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344.3 ExceptionHandling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344.5 Message persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364.5 Durable subscription. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .364.0 Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 110


Message Oriented Middleware illustrated with JMS 4 Advanced JMS✬✩4.1 Message Selector# 32 Message selector filters the message received by a consumer A selector is a string expression (subset of SQL92) A selector is given at the consumer creation Only messages with properties matching the message selector expression aredelivered to the consumerString selector="NewsType = 'Sports' OR NewsType = 'Politics'";session.createConsumer(destination, selector);✫✪✬4.2 Messages parts✩# 33 A message is made up of three parts: Header which defines information used by JMS:◮ such as JMSDestination JMSDeliveryMode JMSExpiration JMSMessageId... Properties◮ mainly used by message selector Body,◮ several type of bodies may be used:⋆ TextMessage⋆ MapMessage : (name, value) pairs⋆ ObjectMessage: Serializable java objects⋆ Message: Empty body⋆ StreamMessage and ByteMessage✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 111Message Oriented Middleware illustrated with JMS 4 Advanced JMS✬✩4.3 ExceptionHandling# 34 The root class of exceptions is JMSException Subclasses: IllegalStateException, InvalidClientIDException,InvalidDestinationException, InvalidSelectorException,JMSSecurityException, MessageEOFException, MessageFormatException,MessageNotReadableException, MessageNotWriteableException,ResourceAllocationException, TransactionInProgressException,TransactionRolledBackException✫✪✬4.4 Message persistence✩# 35 What if the JMS server fails ? JMS has two modes: Messages are saved to persistent memory: PERSISTENT mode Or NON_PERSISTENT mode By default the mode is PERSISTENT Additionally, messages may have a time to liveproducer.setDeliveryMode(DeliveryMode.PERSISTENT);producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);producer.setTimeToLive(milliseconds);✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 112


Message Oriented Middleware illustrated with JMS✬✩4.5 Durable subscription# 36 In publish/subscribe mode, by default, messages published are only delivered toactive subscribers Alternatively, it is possible to create durable subscribers Messages will be retained and recovered when subscribers go through nonactive/active periodsString clientId;connection.setClientID(clientId);consumer = session.createDurableSubscriber((Topic) destination,consumerName);✫✪✬4.6 Transactions✩ Series of operations may be grouped into atomic units called transactions If any one of the operation fails, the transaction may be rolled back Otherwise the transaction may be committed# 37boolean transactionMode=true;javax.jms.Session session;session=connection.createSession(transactionMode, ackMode);....session.commit();session.rollback();✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 113Message Oriented Middleware illustrated with JMS✬✩Conclusions# 38 MOM: a solution to decouple producers and consumers MOM insure reliable message delivery semantics Persistent messages Delivery acknowledgment Message ordering✫✪✬Useful links✩# 39 Apache Active MQ (http://activemq.apache.org/) javadoc activemq(http://activemq.apache.org/maven/activemq-core/apidocs/) Documentation Sun Tutorial SUN (http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JMS.html) javadoc API JMS (http://java.sun.com/j2ee/1.4/docs/api/index.html)✫✪TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 114


Message Oriented Middleware illustrated with JMSReferences[Eugster et al., 2003] Eugster, P., Felber, P., Guerraoui, R., and Kermarrec, A.-M. (2003). The many facesof publish/subscribe. ACM Computing Survey, 35(2):114–131.[Hinze et al., 2009] Hinze, A., Sachs, K., and Buchmann, A. P. (2009). Event-based applications and enablingtechnologies. In DEBS.[Mühl et al., 2006] Mühl, G., Fiege, L., and Pietzuch, P. (2006). Distributed Event Based Systems. Springer.[Smile, 2009] Smile (2009). Livres blancs/Système et infrastructure/Middleware orientés messages.www.smile.fr/Livres-blancs/Systeme-et-infrastructure/Middleware-orientes-messages.TELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 115Message Oriented Middleware illustrated with JMSTELECOM SudParis — INF — 3 novembre 2014 — ASR/CSC5002 116


Introduction to design patterns formiddlewareDenis ConanASR/CSC50023 novembre 2014117Introduction to design patterns for middleware✬✩Foreword# 2 The sources of this presentation are: S. Krakowiak (UniversitÃľ Joseph Fourier), “Patrons et canevas pourl’intergiciel”, ICAR 2006 French Speaking Summer School on Middleware andConstruction of Distributed Applications, Autrans, France, August 2006.◮ URL of the slides in French:http://sardes.inrialpes.fr/ecole/2006/ICAR-06-Intro.pdf S. Krakowiak “Chapitre 1: Introduction Ãă l’intergiciel” dans “Intergiciel etConstruction d’Applications RÃľparties”, 2006,http://sardes.inrialpes.fr/ecole/livre/pub/Chapters/Intro/intro.html S. Krakowiak “Chapitre 2: Patrons et canevas pour l’intergiciel” dans “Intergicielet Construction d’Applications RÃľparties”, 2006,http://sardes.inrialpes.fr/ecole/livre/pub/Chapters/Patterns/patterns.html S. Krakowiak “Middleware Architecture with Patterns and Frameworks”, 2007,http://sardes.inrialpes.fr/~krakowiak/MW-Book/ (see the first two chapters)✫✪✬✩# 3 E. Gamma, R. Helm, R. Johnson, J. Vlissides “Design Patterns: Elements ofR<strong>eu</strong>sable Object-Oriented Software”, Addison-Wesley, 1994◮ Has been translated in French F. Buschmann, R. M<strong>eu</strong>nier, H. Rohnert, P. Sommerlad and M. Stal“Pattern-Oriented Software Architecture: Volume 1, A System of Patterns”,Wiley, 1996 D.C. Schmidt, M. Stal, H. Rohnert and F. Buschmann “Pattern-OrientedSoftware Architecture, Volume 2, Patterns for Concurrent and NetworkedObjects”, Wiley, 2000. Buschmann, K. Henney and D.C. Schmidt “Pattern-Oriented SoftwareArchitecture, Volume 4, A Pattern Language for Distributed Computing”, Wiley,2007✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 118


Introduction to design patterns for middleware✬✩Outline# 42 Distributed system organisation with a middleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Design patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Patterns for distributed interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 Patterns for composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 Patterns for coordination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40✫✪✬1 Distributed system organisation with a middleware✩# 5✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 119Introduction to design patterns for middleware 2 Design patterns✬✩2 Design patterns# 62.2 Objectives of the pattern orientation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.2 Some design pattern examples for middleware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .82.4 Definition of design patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.4 Writing patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.0 Classifying patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16✫✪✬2.1 Objectives of the pattern orientation✩Each pattern describes a problem that occurs over and over again in our environment,and then describes the core of the solution to that problem, in such a way that you canuse this solution a million times over, without ever doing it the same way twice. a# 7 Present the design principles of middleware architecture in a systematic way Identify the main design and implementation problems Exhibit the main design solutions relevant to middleware construction Illustrate the patterns in frameworks in the teaching unit Well known software design patterns: Factory Singleton Iteratora Alexander, Christopher (1977). A Pattern Language: Towns, Buildings, Construction. OxfordUniversity Press.✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 120


2 Design patterns 2.2 Some design pattern examples for middleware✬✩2.2 Some design pattern examples for middleware# 82.2.2 Example 1: A client/server middleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.2.2 Example 2: Integration of legacy applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.2.4 Example 3: Adaptation to client resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.2.4 Example 4: Monitoring and control of networked equipments . . . . . . . . . . . . . . . . . 12✫✪✬2.2.1 Example 1: A client/server middleware✩# 9✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 1212 Design patterns 2.2 Some design pattern examples for middleware✬✩2.2.2 Example 2: Integration of legacy applications# 10✫✪✬2.2.3 Example 3: Adaptation to client resources✩# 11✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 122


Introduction to design patterns for middleware 2 Design patterns✬✩2.2.4 Example 4: Monitoring and control of networkedequipments Physical organisation Logical organisation# 12✫✪✬2.3 Definition of design patterns✩# 13 Definition (not limited to program design) A set of design rules (element definitions, element composition principles, rulesof usage) that allow the designer to answer a class of specific needs in a specificenvironment Properties Elaborated from the experience acquired: Class of problems, capture of thesolution elements common to those problems Defines design principles, not specific to the implementation Provides an aid to documentation: Common terminology, even formaldescription (“pattern language”)✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 123Introduction to design patterns for middleware✬✩2.4 Writing patterns# 14 Name: Higher abstraction which conveys the essence of the pattern succinctly Intent: Short statement stating what the pattern does, its rationale, and theparticular design issue or problem addressed Motivation and context: Scenario illustrating the class of problems addressed;should be as generic as possible Problem: Requirements, desirable properties of the solution; constraints of theenvironment Solution Structure: Static aspects, i.e. components, relationships; may be depicted in aclasses/components diagram Interactions: Dynamic aspects, i.e. run-time behaviour, life-cycle; may bedepicted in a communications/sequence/timing diagram Also known as & related patterns: Other well-known names & closely relatedpatterns✫✪✬2.5 Classifying patterns✩# 15 Architectural: Large scale, structural organisation, subsystems and relationshipsbetween them Design: Small scale, commonly recurring structure within a particular context Idioms: Language specific, how to implement a particular aspect in a given language And many more: Software process, requirement elicitation, analysis, etc.✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 124


Introduction to design patterns for middleware 3 Patterns for distributed interaction✬✩3 Patterns for distributed interaction# 163.2 Asynchronous call, synchronous call, buffered message. . . . . . . . . . . . . . . . . . . . . . . . . .183.2 Call-back and Inversion of control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183.3 Reflection: Observe and act on its own state and behaviour . . . . . . . . . . . . . . . . . . . . 203.4 Factory: Entity creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223.5 Proxy: Representative for remote access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243.6 Wrapper or Adapter: Interface transformation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .263.7 Interceptor: Adaptable service provision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283.8 Similarities and differences between the previous patterns . . . . . . . . . . . . . . . . . . . . . . . 29✫✪✬3.1 Asynchronous call, synchronous call, buffered message✩# 17✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 125Introduction to design patterns for middleware 3 Patterns for distributed interaction✬✩3.2 Call-back and Inversion of control# 18✫✪According to wikipedia, “Inversion of control —also known as IoC— is a concept, and an associated set ofprogramming techniques, in which the control flow is inverted compared to the traditional interaction modelexpressed in imperative style by a series of procedure calls. Thus, instead of the programmer specifying, bythe means of function calls, a series of events to happen during the lifetime of a programme, they wouldrather register desired responses to particular happenings, and then let some external entities take over thecontrol over the precise order and set of events to happen.Informally, it is expressed by the Hollywood Principle - ‘Don’t call us, we’ll call you’.A closely related concept and a direct application of IoC principle is event-driven programming.”✬3.3 Reflection: Observe and act on its own state and behaviour✩# 19 Context: Support different types of variations/adaptations of an application Problem: Particular variations must be hidden to the client Solution Make the system self-aware◮ Select aspects of its structure and behaviour accessible for adaptation⋆ Objectify/reify information about properties and variant aspects of theapplication’s structure, behaviour, and state into a set of meta-objects Split the architecture into two major parts◮ Meta-level: Self-representation of the system in meta-objects⋆ Type structures, algorithms, or even function call mechanisms◮ Base level: Application logic⋆ Uses the meta-objects to remain independent of those aspects that change An interface is specified for manipulating the meta-objects◮ Meta-Object Protocol responsible for performing changes✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 126


3 Patterns for distributed interaction 3.4 Factory: Entity creation✬✩ Architecture principle# 20✫✪✬3.4 Factory: Entity creation✩# 21 Context: Applications organised as a set of distributed entities Problem Dynamically create multiple instances of an entity type Desirable properties◮ Instances should be parameterised◮ Evolution should be easy, i.e. no hard-coded decisions Constraints: Distributed environment, i.e. no single address space Solution Abstract factory: Defines a generic interface and organisation for creatingentities; the actual creation is deferred to concrete factories that actuallyimplement the creation methods A further degree of flexibility is achieved by using Factory Factory, that is thecreation mechanism itself is parameterised✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 1273 Patterns for distributed interaction 3.5 Proxy: Representative for remote access✬✩3.4.1 Sequence diagram of Factory# 22✫✪✬3.5 Proxy: Representative for remote access✩# 23 Context: A client needs access to the services by some entity (the “servant”) Problem Define an access mechanism that does not involve◮ Hard-coding the location of the servant into the client code◮ Deep knowledge of the communication protocols by the client Desirable properties◮ Access should be efficient at run-time and secure◮ Programming should be simple: No difference between local and remote access Constraints: Distributed environment (no single address space) Solutions Use a local representative of the server on the client side that isolates the clientfrom the communication system and the servant Keep the same interface for the representative as for the servant Define a uniform proxy structure to facilitate automatic generation✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 128


3 Patterns for distributed interaction 3.6 Wrapper or Adapter: Interface transformation✬✩3.5.1 Sequence diagram of Proxy# 24✫✪✬3.6 Wrapper or Adapter: Interface transformation✩# 25 Context: Clients requesting services; servers providing services; services defined byinterfaces Problem R<strong>eu</strong>se an existing server by modifying either its interface or some of its functionsin order to satisfy the needs of a client (or class of clients) Desirable properties: Should be run-time efficient; should be adaptable becausethe needs may change and may not be anticipated; should be itself r<strong>eu</strong>sable(generic) Solutions The wrapper screens the server by intercepting method calls to its interface Each call is prefixed by a prologue and followed by an epilogue in the wrapper The parameters and results may need to be converted✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 1293 Patterns for distributed interaction 3.7 Interceptor: Adaptable service provision✬✩3.6.1 Sequence diagram of Wrapper/Adapter# 26✫✪✬3.7 Interceptor: Adaptable service provision✩# 27 Context: Service provision (in a general setting) Client-server, peer-to-peer, high-level to low-level May be uni- or bi-directional, synchronous or asynchronous Problem Transform the service (adding new treatments), by different means◮ Interposing a new layer of processing (like wrapper)◮ Changing the destination (may be conditional) Constraints: Services may be added/removed dynamically Solutions Create interposition entities (statically or dynamically). These entities◮ Intercept calls (and/or return statements) and insert specific processing, thatmay be based on content analysis◮ May redirect call to a different target◮ May use call-backs✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 130


Introduction to design patterns for middleware 3 Patterns for distributed interaction✬✩3.7.1 Sequence diagram of Interceptor# 28✫✪# 29✬3.8 Similarities and differences between the previous patterns Wrapper Vs. Proxy Wrapper and Proxy have a similar structure◮ Proxy preserves the interfacesVs. Wrapper transforms the interface◮ Proxy often (not always) involves remote accessVs. Wrapper is usually on-site Wrapper Vs. Interceptor Wrapper and Interceptor have a similar function which is behavioural reflection◮ Wrapper transforms the interfaceVs. Interceptor transforms the functionality (may completely screen servant) Reflection Vs. Interceptor Interceptor provides a means to implement reflective mechanisms◮ Not the only way to implement reflection (others = language, byte codetransformation, etc.)◮ Interceptor exposes only part of the state of the base level Reflection can define a type of interception mechanism in the form of ameta-object protocol✫✩✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 131Introduction to design patterns for middleware 4 Patterns for composition✬✩4 Patterns for composition# 304.2 Principle of de/composition in distribution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .324.2 Contract: Qualified required/offered interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324.4 Layer or Abstract machine or Protocol stack: Vertical decomposition. . . . . . . . . . . .344.4 Multi-tier architecture: Horizontal decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344.6 Component/Container: Contract + Factory + Interceptor + extra-functionalities 375.0 Composite with sharing: Component + Vertical decomposition + Sharing . . . . . . . 40✫✪✬4.1 Principle of de/composition in distribution✩# 31 Objective Ease the design◮ Show the design approach through the means of the structure◮ Show off the interfaces and the dependencies Ease the evolution◮ Apply the encapsulation principle◮ Standardise the exchanges Examples Multi-level structure◮ “Vertical” decomposition: e.g., LayerVs. “horizontal” decomposition: e.g. Multi-tierVs. both of them: e.g. Middle-tier/Component Leverage the concept of Contract◮ From “simple” interfaces toOffered/server, required/client, and internal and external interfaces✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 132


Introduction to design patterns for middleware 4 Patterns for composition✬✩4.2 Contract: Qualified required/offered interfaces# 32 Four levels of contract1. Syntactic contract: Types of operations, verified statically2. Behavioural contract: Dynamic behaviour (semantics) of operations,assertion-based3. Synchronisation contract: Interactions between operations, synchronisation4. Quality of service contract: extra-functional aspects such as performance,availability, security✫✪✬4.3 Layer or Abstract machine or Protocol stack: Verticaldecomposition✩ Context: Complex “local” system design Problem: Define different levels of abstraction/refinement Solution: Vertical decomposition with levels, and upper and lower interfaces# 33✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 1334 Patterns for composition 4.4 Multi-tier architecture: Horizontal decomposition✬✩4.4 Multi-tier architecture: Horizontal decomposition Context: Complex distributed system; incremental upgrade Problem: Evolution of the client and the server sides, load-balancing, scalability Solution: Horizontal decomposition into tiers, separation of system functionalities# 34✫✪✬4.4.1 Focus on presentation tier: The MVC pattern✩ Context: Management of the client view or user interface Problem: Confusion in the roles of objects prevents evolution. Solution: Separate the data (Model), the HMI on screen (View) and the controllogic (Controller) which is the glue between the two Proposed in 1978-79 by Trygve Reenskaug et al. from XEROX PARC for theSmalltalk language# 35✫✪MVC relies on other behavioral and structural patterns• Observer pattern for the Model-View relationship– Multiple views– As soon as the model is modified, views get updated appropriately• Observer pattern for the Model-Controller relationship– The model may impact controllers: some options (buttons...) are not always available– Controllers must be aware of the modifications on the model• Composite pattern– A composite can be associated to a viewTÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 134


Introduction to design patterns for middleware 4 Patterns for composition– Subviews then correspond to components• Strategy pattern– The way the controller acts upon the model depends on the view– The different behaviors are enabled following the strategy pattern✬4.4.2 MVC pattern vs 3-tier architecture✩# 36 MVC pattern Focus on the presentation layer to improve code evolutivity Triangular architecture: The view sends updates to the controller, the controllerupdates the model, and the view gets updated directly from the model. vs 3-tier architecture style Focus on the distribution of the architecture to favor scalability Linear architecture: The presentation tier never communicates directly with thedata tier. Communication goes through the middle tier.✫✪Originally, MVC concerned only the presentation tier but it tends to be used more and more as a full 3-tierarchitecture where views are the presentation, controllers are the business logic and models correspond tothe data tier. In that case, the controllers become much more complex than envisioned in the original pattern.More reasonable to have the presentation tier with controllers and view from MVC pattern and thebusiness logic tier corresponding to the model of MVC. The data tier then corresponds to the original dataaccess tier.✬4.5 Component/Container: Contract + Factory + Interceptor +extra-functionalities✩# 37 Context: Distributed application accessing extra-functional services Problem: Control life-cycle; separate business/extra-functional parts Solution: Contract to make explicit server and client interfaces Container that implement Factory + Interceptor to manage extra-functionalservices✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 135Introduction to design patterns for middleware✬4.6 Composite with sharing: Component + Verticaldecomposition + Sharing✩# 38 Context Part-whole hierarchies of components Problem Make the client simple◮ Ignore the difference between composite entities and individual components A component can have more than one parent Make it easier to add new kinds of components Make the design overly general Solution Abstract component entity which represents both a primitive or a composite Control the content of composite components Extend the reference/naming system to explicitly express sharing✫✪✬4.6.1 Example of the Fractal Component Model✩ ÃĽ. Bruneton, T. Coupaye, M. Leclercq, V. QuÃľma, and J.-B. StÃľfani “TheFractal Component Model and Its Support in Java” Software–Practice andExperience, 36(11), pp. 1257–1284, September 2006# 39✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 136


Introduction to design patterns for middleware 5 Patterns for coordination✬✩5 Patterns for coordination# 405.2 Naming: White pages service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425.2 Trading: Yellow pages service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425.3 Publish/subscribe or Observer or Event channel: Change-propagation mechanism 445.4 Pipes and filters: Structure for processing streams of data . . . . . . . . . . . . . . . . . . . . . . 45✫✪✬5.1 Naming: White pages service✩# 41 Context: clients and servers distributed over the network Problem Obtain a (distributed) reference to an entity Only the logical name is known by the client Solution The server registers its reference under a logical name to a name server The name server has a “well-known” reference The client retrieves the server’s reference by providing the logical name Logical names are organised as a hierarchy✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 1375 Patterns for coordination5.3 Publish/subscribe or Observer or Event channel: Change-propagation mechanism✬✩5.2 Trading: Yellow pages service# 42 Context: clients and servers distributed over the network Problem Obtain a (distributed) reference to an entity Only a property characterising the server is known by the client: Service name... Solution The client specifies its requets by providing properties of the required service The trader answers by giving a set of server’s references matching the client’squery✫✪✬5.3 Publish/subscribe or Observer or Event channel:Change-propagation mechanism✩# 43 Context Keep the state of cooperating components synchronised Problem Be notified about state changes in a particular entity Number and identities of dependent entities not known a priori Explicit polling not feasible or not efficient Notifiers and notified entities not tightly coupled Solution Notifier also called publisher or subject: Maintains a registry of subscribers Notified entities also called subscribers or observers: Subscribe to notification Push model (publisher sends all changes)Vs. pull model (publisher sends nature of data change and subscriber getsretrieves data)✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 138


Introduction to design patterns for middleware 5 Patterns for coordination✬✩5.3.1 Example of OMG CORBA Event channel# 44✫✪✬5.4 Pipes and filters: Structure for processing streams of data✩# 45 Context: Distributed application processing data streams Problem Flexibility by reordering/recombining processing steps Small processing steps are easier to r<strong>eu</strong>se in a different setting Non-adjacent steps do not share information Solution Each processing step is encapsulated in a filter component Data is passed through pipes between adjacent filters Filters are the processing units of the pipeline◮ Consume data incrementally to achieve low latency and enable parallelism Push mode Vs. pull mode Vs. active mode (pull + push)✫✪TÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 139Introduction to design patterns for middlewareTÃľlÃľcom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 140


Component MiddlewareSophie ChabridonASR/CSC50023 novembre 2014141Component Middleware✬✩Outline# 22 Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Overview of EJB Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 Conclusion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .585 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59✫✪✬1 Foreword✩Structural CompositionsActivity OrchestrationsSCABPELApplication servers− Life cycle (instantiate)− Persistency# 3JEEMessage Oriented MiddlewareJMSWebServices/JavaRMI/CORBASynchronous Distributed RequestssocketsTCP/UDP✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 142


Component Middleware 2 Introduction✬✩2 Introduction# 42.2 Limits of object-oriented programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.2 Motivations for Component Based Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.4 What is a component ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.4 Characterization of a component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.5 Runtime environment of a component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.6 Multi-tier Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .122.7 The 6 Roles in Component Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.0 Main component middleware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16✫✪✬2.1 Limits of object-oriented programming✩# 5 A lot of tasks must be done manually Object instantiation Service invocation via direct access to object reference + explicit method call Definition of dependencies between classes Almost no tool for application deployment (installation of executable files on thevarious sites) Applications structure difficult to understand (= set of files) Difficult to modify or extend an existing application communication mode modification of system/technical services assembly Building an application using black-box classes makes it difficult to introduce new references to other objects to inherit from other classes✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 143Component Middleware 2 Introduction✬✩2.2 Motivations for Component Based DevelopmentProgramming in the large versus programming in the small# 6 Applications are built by assembling existing components Notion of connector : Components are connected with one another defining asoftware architecture Formalism to describe interactions between components Formalism to describe the deployment of components Separation of concerns : Separate functional from non-functional or extra-functionalaspects to allow for more r<strong>eu</strong>sability Focus on application concerns (functional) rather than technical problems(extra-functional)✫✪✬2.3 What is a component ?✩No consensus on a unique definition. Each platform has its own definition !!# 7 According to [Szyperski, 1998]: A unit of composition with contractually specified interfaces and explicit contextdependencies only. A software component can be deployed independently and issubject to composition by third parties. Context dependencies: required interfaces and execution environments(platforms) A binary unit - not source code!◮ This means that a class library is not a component No persistent state - a component is not an instance of itself◮ Much like classes are not objects✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 144i


2 Introduction 2.5 Runtime environment of a component✬✩2.4 Characterization of a componentA software module# 8 That is a contractual specification by exporting some attributes, properties andmethods That provides interfaces to other components and requires some interfaces fromother components That has no persistent state That has pre- and post-conditions That isconfigurable by setting properties That is independently deployable and composable✫✪✬2.5 Runtime environment of a component✩Application ServerApplication ServerContainerContainerComponentComponent Connections# 9 ClientComponentServiceServiceServiceServiceServiceSystem / Middleware✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 145Component Middleware 2 Introduction✬✩2.5.1 Runtime environment of a component (cont.)# 10 Container Encapsulates components Provides system/technical services Maintains connections between components Deals with invocations and events Application server Runtime environment for containers mediator between the containers and the system/middleware✫✪✬2.5.2 Technical services✩# 11 Resource Management Ressource pooling Activation/deactivation mechanism Naming and directory Synchronous/asynchronous communication Transaction Persistence Security✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 146


2 Introduction 2.7 The 6 Roles in Component Development✬✩2.6 Multi-tier Architecture# 12✫✪✬2.7 The 6 Roles in Component Development✩1. Component Provider# 13 Develops components Provides component metadata: structural information (component logical name,transaction demarcation, persistence requirements...) and component externaldependencies Metadata may be expressed in annotations or in an XML deployment descriptor2. Application Assembler Assembles application components into a single deployable unit Defines security roles for application clients, method permissions...3. Deployer Uses information provided by the component provider and the assembler Resolves component dependencies Deploys the application in an operational environment including a container and aserver✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 147Component Middleware✬✩2.7.1 The 6 Roles in Component Development (cont.)4. Server Provider Responsible of distributed transaction management, distributed objets management,low-level system tasks OS vendor, Middleware vendor or DBMS vendor# 145. Container Provider Provides deployment tools and runtime support for components Focus on the development of a scalable, secure, transaction-enabled container6. System Administrator Responsible for the configuration and administration of the enterprise’s computingand networking infrastructure Oversees the well-being of the deployed applications Monitors the log of non-application exceptions an errors logged by the container Takes actions to correct the problems caused by exceptions and errors✫✪✬2.8 Main component middleware✩# 15 Entreprise Java Beans Supported by Oracle Application server : Java EE http://www.oracle.com/technetwork/java/javaee ONE LANGUAGE, MANY PLATFORMS Utilise write once, read everywhere philosophy of Java Must be implemented in Java EJB standard can be seen as a subset of CCM .NET Supported by Microsoft msdn.microsoft.com/net Replaces COM+ and DCOM MANY LANGUAGES, ONE PLATFORM (Windows) CORBA Component Model (CCM) Supported by the Object Management Group (OMG) www.omg.org Extend the EJB model MANY LANGUAGES, MANY PLATFORMS Vendor-n<strong>eu</strong>tral specification✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 148


Component Middleware 3 Overview of EJB Technology✬✩3 Overview of EJB Technology# 163.2 What is EJB ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183.2 Java Community Process (JCP). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .183.3 EJB Container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203.4 Java EE at a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243.5 EJB types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283.6 Main EJB3 Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303.7 Bean development. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .323.8 Session Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .343.9 Entity Bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443.10 Transaction Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56✫✪✬3.1 What is EJB ?✩# 17 Enterprise Java Beans Java component model for distributed enterprise applications, released by Sun in1998 EJB 3.0 specification (2006) - JSR 220 EJB 3.1 specification (2009) - JSR 318 EJB 3.2 specification (2013) - JSR 345 Definitions [Monson-Haefel, 2001, Lafosse, 2011]: EJB are standard server-side components for component transaction monitors(CTM) EJB technology defines a model for the development of r<strong>eu</strong>sable Java servercomponents that encapsulate the business logic of an application✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 1493 Overview of EJB Technology 3.3 EJB Container✬✩3.2 Java Community Process (JCP)# 18 www.jcp.org International developer community whose charter it is to develop and evolve Javatechnology specifications, reference implementations, and technology compatibility kits. Company, organization, or individual can be member✫✪✬3.3 EJB Container✩# 19 Runtime environment for creation and lifecycle management of bean instances Gives access to a set of standardized services to beans Provides a context with: Configuration properties References to other components References to technical services✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 150


3 Overview of EJB Technology 3.3 EJB Container✬✩3.3.1 EJB Container - Provided services# 20 Includes many Java technologies, that can be used independently of EJB Java 2 Platform, Standard Edition v7 (J2SE) APIs RMI-IIOP - remote method invocation based on CORBA InteroperableInter-ORB Protocol JDBC (Java DataBase Connectivity) JSP (Java Server Pages) - Web clients JAXP (Java API for XML Processing) Java IDL - adds CORBA capability to the Java platform✫✪✬3.3.2 EJB Container - Provided services (cont.)✩ Current services are frozen Research initiatives (s.a. Objectweb JOnAS) provide extensible containers withpluggable services# 21 EJB 3.2 APIs(javax package), including Java Persistence (JPA) Asynchronous communication: Java Messaging Service (JMS 2.0), JavaMail 1.4(sending mail only) Connector Transaction: UserTransaction interface of JTA 1.2, Java Transaction Service (JTS)(specification based on CORBA Object Transaction Service) Security: Java Security API Web Services: JAX-RPC 1.1, JAX-WS 2.0, JAX-RS 2.0✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 1513 Overview of EJB Technology 3.4 Java EE at a glance✬✩3.3.3 EJB Container - Provided services (cont.)# 22 Lifecycle service - Java Naming and Directory Interface Instances passivation◮ Temporary saving of a bean when container needs memory Instances pooling◮ For performance reasons, the container can instantiate less beans than thereare clients◮ Then several clients share the same bean◮ Possible only for beans without instance variables Pooling of connections to the Database◮ All the beans of a server share a pool of connections to the DB◮ Connections remain open and are used by beans✫✪✬3.4 Java EE at a glance✩# 23 Java Platform, Enterprise Edition Application server technology based on EJBs Targets scalability, accessibility, security, integrity, and other requirements ofenterprise-class applications Java API for RESTful Web Services (JAX-RS) Contexts and Dependency Injection for the Java EE Platform (CDI) Bean Validation : same set of validations can be shared by all layers of anapplication Java Server Faces (JSF) 2.0 supports Ajax✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 152


3 Overview of EJB Technology 3.4 Java EE at a glance✬✩3.4.1 Java EE Architecture# 24✫✪✬3.4.2 Java EE - 3-tier Architecture✩# 25✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 1533 Overview of EJB Technology 3.5 EJB types✬✩3.4.3 Java EE - 3-tier Architecture (cont.)# 26 Client Heavy weight client - Java application (or possibly other language) Light weight client - Web navigator Application Server Reference implementation : Java EE 7 GlassFish (Oracle) Commercial products : WebSphere (IBM), WebLogic (BEA)... Open source distributions : jBoss, JOnAS (Objectweb), Geronimo, OpenEJB... DBMS (DataBase Management System) Provide storage support for application data Mostly using a relational DBMS (Oracle, SQL Server, PostGreSQL ...)✫✪✬3.5 EJB types✩# 27 Entity Beans Model real-world objects (e.g. Owner, Account) that exist in persistent storage(DBMS or other storage accessible using JDBC (Java Database Connectivity)) Persistent state is maintained through all method and server invocations Identified by a primary key Object-Relational mapping Implementation using JPA (Java Persistence API)✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 154


Component Middleware 3 Overview of EJB Technology✬✩3.5.1 EJB types (cont.)# 28 Session Beans Model client activities Perform a task or process, and are therefore transient Do not exist outside a client session No persistent state Two kinds of session beans : stateless and stateful Manage actions that may cross entity beans or go outside the concern of anentity bean◮ e.g. Teller may authenticate the user and transfer funds between accounts◮ e.g. Statement may include transactions from multiple accounts Message-Driven Beans (since EJB 2.0) Listener processing messages asynchronously Only a bean class. No interface.✫✪✬3.6 Main EJB3 Annotations✩# 29 @EJB - Denotes a reference to an EJB business interface or home interface. @PersistenceContext - Used to express a dependency on an EntityManager. @Stateful - Used to annotate a class as a stateful session bean component. @Stateless - Used to annotate a class as a stateless session bean component. @Remote - Applied to the session bean class or remote business interface todesignate a remote interface of the bean. @Local - Applied to the session bean class or local business interface to designate alocal interface of the bean. @MessageDriven - Specifies a message-driven bean. A message-driven bean is amessage consumer that can be called by its container.✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 155Component Middleware 3 Overview of EJB Technology✬✩Main EJB3 Annotations (cont.)# 30 @TransactionManagement - Declares whether a bean will have container-managedor bean-managed transactions. @TransactionAttribute Applies a transaction attribute to all methods of a businessinterface or to individual business methods on a bean class.Can only be specified if container managed transaction demarcation is used.Can be specified on the bean class or on methods of the class that are methods ofthe business interface.Possible values : MANDAT ORY REQUIRED (default) REQUIRES_NEW SUP P ORT S NOT _SUP P ORT ED NEV ER✫✪✬Main EJB3 Annotations (cont.)✩# 31 @WebService - Used on a class or an interface to define a Web service. @WebMethod - Indicates whether the method is part or not of the interface serviceendpoint interface (SEI) of the web service.Exclude element false by default. @WebServiceRef - Used on the client to reference web services.✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 156


Component Middleware 3 Overview of EJB Technology✬✩3.7 Bean development An EJB has a remote interface to be accessed by clients Describes the provided services (methods) No longer required for session beans# 32 Possibly an EJB may provide an interface for local access Describe the provided services offered to local clients Same as remote services, or different ones (enables optimisation) Can only be used within the same JVM as the EJB Gets compiled by the ejb compiler to create local stubs for container to interposetransactions, access control, etc. on invocations. An implementation class✫✪✬3.7.1 Interfaces✩ Remote Interface @Remote# 33 Interface presented to the outside world (contract definition) specifying thebusiness methods provided by the bean Gets compiled by the ejb compiler to create RMI stubs and skeletons Stubs are used by RMI to translate a method invocation to wire format Skeletons are used by RMI to translate wire format to a method invocation NB: A client application never interacts with a bean class directly; It uses themethods of the bean’s interface.✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 1573 Overview of EJB Technology 3.8 Session Beans✬✩3.8 Session Beans# 34 Model business process being performed by a single client involving one or moreentity beans Life duration linked to client’s one Two types of session bean Stateful session bean◮ maintains the conversational state between a client and the session bean◮ may be serialized out and passivated to conserve system resources◮ will be serialized in and activated when needed in the future◮ e.g. Teller session bean logged into and transfers funds between accounts Stateless session bean◮ does not maintain conversational state◮ to be used for generic tasks, to read persistent data◮ e.g. Statement that is given a list of accounts or an owner to generate atextual report for◮ consumes the least amount of resources among all the bean types✫✪✬3.8.1 Stateless Session Bean - Calculator Example✩ Calculator session bean: Simple calculator with 4 operations Implementation code: Remote business interface (Calculator) Session bean class (CalculatorBean)# 35import javax.ejb.Remote;@Remotepublic interface Calculator {public double add(double n1, double n2);public double sub(double n1, double n2);public double mul(double n1, double n2);public double div(double n1, double n2);}✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 158


3 Overview of EJB Technology 3.8 Session Beans✬✩3.8.2 Stateless Session Bean - Calculator Example -Implementation classPossible to name a bean : @Stateless(name = ”myCalculator”)# 36import javax.ejb.Stateless;@Stateless(name = "myCalculator")public class CalculatorBean implements Calculator {public double add(double n1, double n2) {return n1+n2;}public double sub(double n1, double n2) {return n1-n2;}public double mul(double n1, double n2) {return n1*n2;}public double div(double n1, double n2) {return n1/n2;}}✫✪✬3.8.3 Stateless Session Bean - Calculator Example - Client side✩2 ways to get the reference of the business interface dependency injection:@EJB Calculator myCalc;# 37 look-up in JNDI directory using the lookup method povided by EJBContextinterface and the bean interface nameimport javax.naming.*;public class myClient {public static void main(String args[]) throws Exception {Context myContext = new initialContext();Calculator myCalc =(Calculator) myContext.lookup("myCalculator");double result = myCalc.mul(2,4);}}✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 1593 Overview of EJB Technology 3.8 Session Beans✬✩3.8.4 Stateless Session Bean - No-interface view# 38 When a bean does not have a remote interface, possible to access directly to thebean implementation class via the no-interface view But never use the new operator to acquire the reference A no-interface view is a variant of a local view that exposes the non-static publicmethods of the bean class 2 ways to get the reference of the no-interface view of a session bean dependency injection:@EJB CalculatorBean myCalc; look-up in JNDI directory using the lookup method povided by EJBContextinterface and the bean interface name@Resource SessionContext myContext;...CalculatorBean myCalc =(CalculatorBean) myContext.lookup("myCalculator");✫✪✬3.8.5 Stateful Session Bean - Cart Example✩# 39 Cart session bean: represents a shopping cart in an online bookstore. The bean’s client can add a book to the cart, remove a book, or retrieve the cart’scontents. Implementation code: Remote business interface (Cart) Session bean class (CartBean)✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 160


3 Overview of EJB Technology 3.8 Session Beans✬✩3.8.6 Stateful Session Bean - Cart Example (cont.)import java.util.List;import javax.ejb.Remote;# 40@Remotepublic interface Cart {public void initialize(String person) throws BookException;public void initialize(String person, String id)throws BookException;public void addBook(String title);public void removeBook(String title) throws BookException;public List getContents();public void remove();}✫✪✬3.8.7 Stateful Session Bean - Cart Example - Implementationclass✩import java.util.ArrayList;import java.util.List;import javax.ejb.Remove;import javax.ejb.Stateful;# 41@Statefulpublic class CartBean implements Cart {String customerName;String customerId;List contents;✫public void initialize(String person) throws BookException {if (person == null) {throw new BookException("Null person not allowed.");} else { customerName = person; }✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 161Component Middleware 3 Overview of EJB Technology✬✩3.8.8 Stateful Session Bean - Cart Example - Implementationclass (cont.)# 42...}}✫customerId = "0";contents = new ArrayList();public void addBook(String title) { contents.add(title); }public void removeBook(String title) throws BookException {boolean result = contents.remove(title);if (result == false) {throw new BookException(title + " not in cart.");}}public List getContents() { return contents; }@Removepublic void remove() { contents = null; }✪✬3.8.9 Stateful Session Bean - Cart Example - Client side✩From the client’s perspective, the business methods appear to run locally, but theyactually run remotely in the session bean.# 43cart.create("Duke DeEarl");...cart.addBook("Bel Canto");...List bookList = cart.getContents();...cart.removeBook("Gravity's Rainbow");✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 162


3 Overview of EJB Technology 3.9 Entity Bean✬✩3.9 Entity Bean# 44 Represents a business object in a persistent storage mechanism Can be shared by multiple clients Can be linked to other entity beans (like relations in a relational DBMS) Primary key required Defined using @Id annotation, Possible key types (or of the properties or fields of a composite primary key) :java primitive types (and associated wrapper classes), String, Date✫✪✬3.9.1 Entity Bean (cont.)✩# 45 Object/relational mapping annotations to map entities and entity relationships torelational tables Each EB class is mapped to one relational table table name = class name by default or use annotation @T able(name = ”...”) 2 exclusive modes for the definition of table columns property-based access : annotate getter methods field-based access : annotate attributes✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 1633 Overview of EJB Technology 3.9 Entity Bean✬✩3.9.2 Entity Bean - Example# 46@Entitypublic class Book implements Serializable {private String bookId;private String author;private String title;public Book() { }public Book(String author, String title) {this.author = author;this.title = title; }@Id@GeneratedValue(strategy=GenerationType.AUTO)public String getBookId() { return this.bookId; }}✫public String getTitle() { return this.title; }public void setTitle(String title) { this.title=title; }...✪✬3.9.3 Multiplicities in Entity Relationships✩# 471. One-to-one - Each entity instance is related to a single instance of another entity.2. One-to-many - An entity instance can be related to multiple instances of the otherentities.3. Many-to-one - Multiple instances of an entity can be related to a single instance ofthe other entity.4. Many-to-many - The entity instances can be related to multiple instances of eachother.✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 164


3 Overview of EJB Technology 3.9 Entity Bean✬✩3.9.4 Multiplicities in Entity Relationships - OneToMany example@Entitypublic class Author {private long id;private String name;private Collection books;# 48public Author() { books = new ArrayList(); }public Author(String name) {this.name = name; }@OneToMany(public Collection getBooks() {return books; }public void addBook(String title) {Book aBook = new Book(this.name, title);getBooks().add(aBook);} }✫✪✬3.9.5 Persistence management mode✩# 49 Persistence can be managed in two ways: Container-managed (CMP)◮ Simplest to develop◮ Bean code contains no database access calls Bean-managed (BMP)◮ The client is required to explicitly write persistence logic by providingimplementation methods for Home interface◮ More flexibility in how state is managed between the bean instance and thedatabase◮ Used when deployment tools are inadequate✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 1653 Overview of EJB Technology 3.9 Entity Bean✬✩3.9.6 Entity Manager# 50 Entry point of the persistence service Creates and removes persistent entity instances Finds entities by the entity’s primary key Allows queries to be run on entities Associated with a persistence context Defines the scope under which particular entity instances are created, persistedand removed✫✪✬3.9.7 Container-Managed Entity Manager✩# 51 Propagation of the persistence context automatically to all application componentsthat use the EntityManager instance within a single JTA (Java TransactionArchitecture) transaction. To obtain an EntityManager instance, inject the entity manager into theapplication component:@PersistenceContextEntityManager em;✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 166


3 Overview of EJB Technology 3.9 Entity Bean✬✩3.9.8 Application-Managed Entity Manager# 52 Each EntityManager creates a new, isolated persistence context Life cycle of EntityManager instances managed by the application: TheEntityManager and its associated persistence context are created and destroyedexplicitly by the application. To obtain an EntityManager instance, first get an EntityManagerFactory instance:@PersistenceUnitEntityManagerFactory emf; Then, obtain an EntityManager from the EntityManagerFactory instance:EntityManager em = emf.createEntityManager();✫✪✬3.9.9 How to use the Entity Manager - Example✩import javax.ejb.*;import javax.persistence.*;public class BookDBAO {# 53@PersistenceContextprivate EntityManager em;public void init() {Book b1 = new Book("Charles Beaudelaire","Les Fl<strong>eu</strong>rs du Mal");Book b2 = new Book("Jules Verne","Voyage au centre de la Terre");em.persist(b1);em.persist(b2);}}✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 167Component Middleware 3 Overview of EJB Technology✬✩3.9.10 Persistence Unit - persistence.xml file# 54 Defines the set of all entity classes managed by EntityManager instances in anapplication Represents the data contained within a single data store Packaged with the application archive file XML elements : persistence element: global schema, includes a persistence-unit element persistence-unit element: name of a persistence unit and transaction type optional description element jta-data-source element: specifies the global JNDI name of the JTA data source✫✪✬3.9.11 Persistence Unit - persistence.xml file - Example✩# 55This unit manages orders and customers.It does not rely on any vendor-specific features and cantherefore be deployed to any persistence provider.jdbc/MyOrderDBMyOrderApp.jarcom.widgets.Ordercom.widgets.Customer✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 168


Component Middleware✬✩3.10 Transaction Service# 56 Controls concurrent accesses to data by multiple programs In case of a system failure, transactions make sure that after recovery the data willbe in a consistent state Guarantees ACID properties for transactions Atomicity - Either both operations complete successfully or none Consistency - e.g. an account must never have a negative balance Isolation - several parallel transfers must give the same result as if they wereperformed successively Durability - Account state must be persistent and stored on stable storage Example: banking transfer with debit then credit operations Fully integrated within the EJB server Main advantage compared to the CORBA middleware✫✪✬3.10.1 Transaction Service (cont.)✩# 57 Specifies standard Java interfaces between a transaction manager and the partiesinvolved in a distributed transaction system Resource manager Application server Transactional applications Transaction manager Decides whether to commit or rollback at the end of the transaction in adistributed system and coordinates various resource managers Resource manager Responsible for controlling the access to common resources in the distributedsystem✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 169Component Middleware✬✩4 ConclusionAdvantages# 58 Framework taking in charge an important number of technical services Components are dedicated to business aspects Packaging and deployment made easyRestrictions Only Java Some domains are not yet addresses: real-time or embedded systems, mobilecomputing...✫✪✬5 References✩# 59http://www.idt.mdh.se/kurser/cd5480/2003/lectures/EJB-lecture.pdfhttp://www2.lifl.fr/ seinturi/middleware/javaee.pdf JSR345:https://www.jcp.org/en/jsr/detail?id=345[Lafosse, 2011] Lafosse, J. (2011). Développements n-tiers avec Java EE. ENI Éditions.[Monson-Haefel, 2001] Monson-Haefel, R. (2001). Entreprise Java Beans. O’Reilly.[Szyperski, 1998] Szyperski, C. (1998). Component Software Beyond Object OrientedProgramming. Addison Wesley / ACM Press, New York.✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 170


Prerequisites for developingmulti-tier applications in JavaChantal Taconet et Sophie ChabridonASR/CSC50023 novembre 2014171Prerequisites for developing multi-tier applications in Java 1 Java Annotations✬✩Outline# 21 Java Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4✫✪✬1 Java Annotations✩# 3 Introduced in Java language version 5 (JSR 175) Still possible to provide metada in XML description files Decorate the program by attaching metadata to program elements class method attribute Simplify programming by automatically generating part of the code Annotations are used either at compile time or at runtime At compile time, compilers may generate: documentation, code, file (java-processor proc) At runtime java, frameworks interpret meta-data for adaptation through javareflexive API May require parameters Possible to have several annotations per element✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 172


Prerequisites for developing multi-tier applications in Java 1 Java Annotations✬✩1.1 Java Annotations - Examples You already know annotations through javadoc annotations, which produce htmldocumentation files# 4/***Returns an Image object that can then be painted on the screen.*@param url an absolute URL giving the base location of the image*@param name the location of the image, relative to the url argument*@return the image at the specified URL*@see Image*/public Image getImage(URL url, String name) { Example of JAX-RS annotations, for JAVA RESTful Webservices@GET@Produces("text/html")public String readHTML() {}✫✪✬1.2 Create your own annotation✩# 5 Annotation type declaration = interface declaration with an at-symbol (@)preceding the interface keyword Each method declaration defines an element of the annotation type Method : no parameter, no throws clause. Return types : primitive types, String, Class, enums, annotations, and arrays ofthe preceding types✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 173Prerequisites for developing multi-tier applications in Java 1 Java Annotations✬✩First step, define the annotation @Documented: annotations become part of the public API documentation @Target: kinds of program element to which an annotation type is applicable:TYPE, METHOD, CONSTRUCTOR, FIELD, ANNOTATION_TYPE,LOCAL_VARIABLE, PACKAGE, PARAMETER# 6import java.lang.annotation.*;@Documented@Target(ElementType.METHOD)@Inherited@Retention(RetentionPolicy.RUNTIME)public @interface MethodInfo{String author() default "Pankaj";String date();int revision() default 1;String comments();}✫✪✬✩Second step, annotated java file# 7import java.io.FileNotFoundException;import java.util.*;public class AnnotationExample {@Override@MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 1)public String toString() {return "Overriden toString method";}}@Deprecated@MethodInfo(comments = "deprecated method", date = "Nov 17 2012")public static void oldMethod() {System.out.println("old method, don't use it.");}@SuppressWarnings({ "unchecked", "deprecation" })@MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 10)public static void genericsTest() throws FileNotFoundException {}List l = new ArrayList();l.add("abc");oldMethod();✫✪Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 174


Prerequisites for developing multi-tier applications in Java 1 Java Annotations✬✩Third step, use reflexivity to parse an annotated class# 8import java.lang.annotation.Annotation;import java.lang.reflect.Method;public class AnnotationParsing {public static void main(String[] args) {for (Method method : AnnotationParsing.class.getClassLoader().loadClass(("AnnotationExample")).getMethods()) {// checks if MethodInfo annotation is present for the methodif (method.isAnnotationPresent(MethodInfo.class)) {// iterates all the annotations available in the methodfor (Annotation anno : method.getDeclaredAnnotations()) {System.out.println("Annotation in Method '"+ method + "' : " + anno);}}}✫}MethodInfo methodAnno = method.getAnnotation(MethodInfo.class);if (methodAnno.revision() == 1) {System.out.println("Method with revision no 1 = "}+ method);✪Execution result:java AnnotationParsingAnnotation in Method 'public java.lang.String AnnotationExample.toString()' : @MethodInfo(revision=1, author=Pankaj, \comments=Main method, date=Nov 17 2012)Method with revision no 1 = public java.lang.String AnnotationExample.toString()Annotation in Method 'public static void AnnotationExample.oldMethod()' : @java.lang.Deprecated()Annotation in Method 'public static void AnnotationExample.oldMethod()' : @MethodInfo(revision=1, author=Pankaj, \comments=deprecated method, date=Nov 17 2012)Method with revision no 1 = public static void AnnotationExample.oldMethod()Annotation in Method 'public static void AnnotationExample.genericsTest() throws java.io.FileNotFoundException' : \@MethodInfo(revision=10, author=Pankaj, comments=Main method, date=Nov 17 2012)Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 175Prerequisites for developing multi-tier applications in JavaTélécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 176


Micro ProjectSophie Chabridon, Chantal TaconetASR/CSC50023 novembre 2014177Micro Project1 IntroductionThe aim of the project is to design and realize a mailbox manager. The mailbox manager handles classicaluser mailboxes and a common newsgroup which may be read by every user. A directory manages the users whichmay access the mailbox and their rights to access different mailboxes. Only some users have the right to sendmessages to the common newsgroup.Architecture The general Architecture of the system is presented in Figure 1.Clients and servers aredistributed over the network. A Mail Box Manager manages the mail boxes. There is one mail box by user of the system and one news-boxshared by all the system’s users. A Directory Manager manages the users and their access to the system. In the final version of the system,the Mail Box Manager verifies with the Directory Manager the user rights concerning the access to thecommon news group. A Mail Box Client accesses the Mail Box Manager services. An Administration Client accesses the Directory Manager services to add, remove and modify rights of th<strong>eu</strong>sers.Figure 1: General architecture of the system2 Project UML diagramsAn analysis of the problem (perhaps not your final analysis, you can make different modeling choices), hasgiven the following diagrams.Use Case Figure 2 presents the use case diagram. At the final stage, the “add mailbox” use case may beinvoked by the “create user” use case of the “Directory manager” (the same for respectively “remove mailbox”and “delete user”).Directory class diagram Figure 3 presents the Directory package class diagram.Mailbox class diagram Figure 4 presents the Mailbox package class diagram.Send a message to a newsgroup sequence diagram Figure 5 presents the sequence diagram of th<strong>eu</strong>se case send a message to a newsgroup in its final stage (i.e. with access rights verification).3 Middleware technologies involved in the project The Directory Manager and the Mail Box Manager are developed using JavaEE technology. All themailboxes, the newsgroup and the user rights are persistent.Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 178


Micro ProjectFigure 2: Use Case DiagramFigure 3: Directory Class DiagramTélécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 179Micro ProjectFigure 4: Mailbox Class DiagramFigure 5: Send a message to a newsgroup Sequence DiagramTélécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 180


Micro Project The communication between the clients and the Managers will be realized through Java RMI for theadministration server and Web Services for the mailbox manager.4 Micro Project stepsThe project will be realized in several steps.1. Architectural choices : With the material in the course “Introduction to middleware through design patterns”, identify thedesign patterns involved in the application. For each design pattern, draw a picture presenting it andgive adequate explanations. These pictures have to be included in the final report. JMS (with asynchronous messages) may be a candidate to exchange messages between clients andthe Mailbox Manager, synchronous requests another one. Different architectures and choices may beobtained with and without JMS. In the report you are asked to explain the choice you have donebetween object requests and message qu<strong>eu</strong>e technologies for mailbox messages diffusion. Design the persistent data structures: Do not use SQL keywords in the description of these datastructures. For instance, user and right are reserved SQL keywords and should not be used in yourown data structures. Describe the facade of the services: define its interfaces.2. Design and implement the Directory Manager and the Administration Client. The Administration Client isa test client with a predefined scenario.3. Design and implement the Mailbox Manager and the Mailbox Client (without access rights verification).The Mailbox Client is a test client with a predefined scenario.4. Add access rights verification to the Mailbox Manager.5. Distribute server and clients on different computers.6. Add a RESTful interface to at least one of your application components and develop a client to test thisinterface.7. Write a script to automate the distributed demonstration (NB: you can use ssh to start a command on aremote computer: ssh hostname "cmd").Persistency of mailboxes The application may be started and stopped several times. It is thereforerequired to have persistent mailboxes and user directory whose content is saved in a database. You must use thesame MySQL database as during the labs and administrate it using the phpMyAdmin service.Clients and user interfaces This micro-project is about middleware for distribution not about userinterfaces! We ask for simple clients, i.e., test clients with no interactions and with predefined users and messagesare absolutely sufficient. You are asked to write either test clients with predefined messages or command lineclients (to specify all the parameters on the command line).5 What is expected at the end of the projectThe results of the micro project will be:Report A small report (max. 10 pages) describing your solution and the associated design patterns, the architectureand technology choices, the persistence solution, a short user manual so that we can test yourproject, the encountered difficulties and all information you will judge necessary.Defense An oral presentation of 15 minutes including a demonstration will allow you to describe the main designchoices you made and to show your work in action. Both partners of the team are expected to present somepart of the work.Demonstration A demonstration showing your solution in action. Your implementation has to be original.Some variants on the subject are encouraged, UML diagrams are provided on the subject only as examplesof a design solution. Develop step by step in order to have an operational demonstration.Sources All the material (report, slides of the oral presentation, program SOURCE files) has to be uploaded inmoodle before the deadline and in one archive. The archive will contain a root directory with the name of thestudents who worked on the project (e.g., nameA-nameB.tgz archive contains nameA-nameB/ directory).Be careful :Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 181Micro Project Do not include files that can be generated by ant (e.g. .class); Use ascii7 characters only in the name of files (no accent, no white etc.); Include the build.xml (or the makefile or the pom.xml) used to automate the generation of classesand also to launch the demonstration; If you develop your application with the Eclipse Integrated Development Environment (IDE), makesure that it can be run as a standalone application; Provide a good quality code verified with checkstyle and findbugs.Good work!Télécom SudParis — INF — 3 novembre 2014 — ASR/CSC5002 182


References of all the chapters[Baker, 1997] Baker, S. (1997). CORBA Distributed Objects Using Orbix. Addison Wesley ACM Press Book,United Kingdom.[Box, 1998] Box, D. (1998). Essential COM. Addison Wesley.[Downing, 1998] Downing, T. B. (1998). JAVA RMI: Remote Method Invocation. IDG Books Worldwide,Inc.[Eugster et al., 2003] Eugster, P., Felber, P., Guerraoui, R., and Kermarrec, A.-M. (2003). The many facesof publish/subscribe. ACM Computing Survey, 35(2):114–131.[Fielding, 2000] Fielding, R. (2000). Architectural styles and the design of network-based software architectures,http://www.ebuilt.com/fielding/pubs/dissertation/top.htm.[Henning and Vinoski, 1999] Henning, M. and Vinoski, S. (1999). Advanced CORBA Programming withC++. Addison-Wesley.[Hinze et al., 2009] Hinze, A., Sachs, K., and Buchmann, A. P. (2009). Event-based applications and enablingtechnologies. In DEBS.[Kalin, 2010] Kalin, M. (2010). Java Web Services, Up and Running. O’Reilly.[Krakowiak, 2009] Krakowiak, S. (2009). Middleware Architecture with Patterns and Frameworks.http://sardes.inrialpes.fr/ krakowia/MW-Book/ (.)[Lafosse, 2011] Lafosse, J. (2011). Développements n-tiers avec Java EE. ENI Éditions.[Monson-Haefel, 2001] Monson-Haefel, R. (2001). Entreprise Java Beans. O’Reilly.[Mühl et al., 2006] Mühl, G., Fiege, L., and Pietzuch, P. (2006). Distributed Event Based Systems. Springer.[Object-Managment-Group, 2002] Object-Managment-Group (July 2002). The Common Object RequestBroker: Architecture and Specification version 3.0. OMG Documents formal/02-06-01.[OMG, 1998] OMG (1998). CORBA Services Specification. OMG Document 98-12-09.[OMG, 1999] OMG (1999). CORBA 2.3.1. OMG Document 99-12-0910-07.[Orfali and Harkey, 1998] Orfali, R. and Harkey, D. (1998). Client/Server Programming with JAVA andCORBA. Jonh Wiley & sons, Inc., USA.[Smile, 2009] Smile (2009). Livres blancs/Système et infrastructure/Middleware orientés messages.www.smile.fr/Livres-blancs/Systeme-et-infrastructure/Middleware-orientes-messages.[Szyperski, 1998] Szyperski, C. (1998). Component Software Beyond Object Oriented Programming. AddisonWesley / ACM Press, New York.[Vogel and Duddy, 1998] Vogel, A. and Duddy, K. (1998). Java Programming with CORBA. Jonh Wiley &sons, Inc., USA.183 184

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!