ids 2013oop

68
Practical Workbook Introduction to Distributed Systems 1 st Edition 2013 Department of Computer & Information Systems Engineering NED University of Engineering & Technology, Karachi 75270, Pakistan Name : ________________________ Year : ________________________ Batch : ________________________ Roll No : ________________________ Department: ________________________

Upload: anum

Post on 18-Aug-2015

263 views

Category:

Documents


0 download

DESCRIPTION

cdddffd

TRANSCRIPT

Practical Workbook Introduction to Distributed Systems 1st Edition 2013 Department of Computer & Information Systems Engineering NED University of Engineering & Technology, Karachi 75270, Pakistan Name: ________________________ Year: ________________________ Batch: ________________________ Roll No :________________________ Department: ________________________ INTRODUCTION IntroductiontoDistributedSystemsisaveryimportantcourseofferedinfinalyearof engineering.Inanageofeverincreasinginformationcollectionandtheneedtoevaluateit, buildingsystemswhichutilizetheavailablecomputeresourcesineveryoneshomeand hands shouldbedrivingthedevelopmentofmoresophisticateddistributedcomputing systems. Learning about this area of engineering is the need of the day. The first and second lab sessions discuss Linux local sockets and Linux sockets over network respectivelyindetail.Inthisway,studentsarefamiliarizedwithanotherclassicalinter processcommunicationmechanism.AlltheLinuxsystemcallswiththecomplete implementation of client side & server side algorithms are discussed in first two lab sessions. LabSessionthree,four&fiveintroducesXML.XML'ssetoftoolsallowsdevelopersto createwebpages,allowdeveloperstosetstandardsdefiningtheinformationthatshould appear in a document, it makes it possible to define the content of a document separately from itsformatting,makingiteasytoreusethatcontentinotherapplicationsorforother presentation environments. XML is an international standard and its beneficial to learn it. Inlabsessionsix,programminginjavaisintroduced.InlabsessionsevenandeightJava RemoteMethodInvocation(RMI)isdiscussed.ThisisabriefintroductiontoJavaRemote MethodInvocation (RMI). Java RMI is a mechanism that allows one to invoke a method on an object that exists in another address space (either on same or different machine). Lab session nine discusses indirect communication mechanism with group communication. It coverscompleteprogrammingmodelandimplementationissues.Italsocoversbasicsof JGroup toolkit. Lab session ten deals with implementing & using message queues using Java messagingservice(JMS).ItcoversprogrammingdetailswithJMSincludingthe implementation(withinstallationandexecutionsteps)ofstandardJMSspecification, OpenJMS. CONTENTSLab Session No. ObjectPageNo

1 Socket programming in Linux local sockets 1 2Socket programming in Linux over the network 9 3Getting acquainted with XML 16 4Understanding and creating DTD in XML 20 5Understanding the concept of root elements and attributes in XML 28 6Introduction to Java Programming 34 7 8 Creating a distributed version of the classic Hello World program using Java Remote Method Invocation (RMI) (Part 1) Creating a distributed version of the classic Hello World program using Java Remote Method Invocation (RMI) (Part 2) 38 46 9Understanding the concept of Indirect Communication and exploring group communication mechanism via JGroup Toolkit. 51 10Understanding the concept of message queues via Java Messaging Service (JMS) 57 Introduction to Distributed Systems___Lab Session 01 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 1 Lab Session 01 OBJECT Socket programming in Linux local sockets THEORY Asocketisabidirectionalcommunicationdevicethatcanbeusedtocommunicatewith another process on the same machine or with a process running on other machines. System calls for sockets Theseare the system calls involving sockets: a)socketCreates a socket #include sockfd = socket(int protocol_family, int socket_type, int protocol); TheprotocolmodulesaregroupedintoprotocolfamilieslikeAF_INET,AF_IPX, AF_PACKET and socket types like SOCK_STREAM or SOCK_DGRAM. Protocol Families Name PurposeAF_UNIX, AF_LOCAL Local communicationAF_INETIPv4 Internet protocolsAF_INET6IPv6 Internet protocols SOCK_STREAM provides sequenced, reliable, two-way, connection-based byte streams. An out-of-banddatatransmissionmechanismmaybesupported.SOCK_DGRAMsupports datagrams (connectionless, unreliable messages of a fixed maximum length). The protocol specifies a particular protocol to be used with the socket. Normally only a single protocolexiststosupportaparticularsockettypewithinagivenprotocolfamily,inwhich case protocol can be specified as 0. However, it is possible that many protocols may exist, in which case a particular protocol must be specified in this manner. On success, a file descriptor for the new socket is returned. On error, -1 is returned, and errno is set appropriately. b)closeDestroys a socket #include int close(intfd); close() closes a file descriptor, so that it no longer refers to any file and may be reused. close() returns zero on success. On error, -1 is returned, and errno is set appropriately. Introduction to Distributed Systems___Lab Session 01 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 2 c)connectCreates a connection between two sockets #include int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen); The connect() systemcall connects the socket referred to by the file descriptor sockfd to the address specified by addr. The addrlen argument specifies the size of addr. The format of the address in addr is determined by the address space of the socket sockfd. The sockaddr structure is the basic structure forall system calls and functions that deal with socketaddresses.Allpointerstoothersocketaddressstructuresareoftencasttopointersto sockaddr before use in various functions and system calls: #include struct sockaddr { unsigned short sa_family;// address family, AF_xxx char sa_data[14];// 14 bytes of protocol address }; The Unix domain socket address structure is: #include struct sockaddr_un{ short sun_family;//AF_UNIX char sun_PATH[108]; // path name }; If the socket sockfd is of type SOCK_DGRAM then addr is the address to which datagrams are sent by default, and the onlyaddress from which datagrams are received.If the socketis of type SOCK_STREAM, this call attempts to make a connection to the socket that is bound totheaddressspecifiedbyaddr.Generally,connection-basedprotocolsocketsmay successfully connect() only once; connectionless protocol sockets may use connect() multiple times to change their association. If the connection or binding succeeds, zero is returned. On error,-1 is returned, and errno is set appropriately. d)bindLabels a socket with an address #include int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); When a socket is created with socket(), it exists in a name space (address family) but has no address assigned to it. bind() assigns the address specified to by addr to the socket referred to bythefiledescriptorsockfd.addrlenspecifiesthesize,inbytes,oftheaddressstructure pointed to by addr. Traditionally, this operation is called "assigning a name to a socket". It is normallynecessarytoassignalocaladdressusingbind()beforeaSOCK_STREAMsocket may receive connections. On success, zero is returned. On error, -1 is returned, and errno is set appropriately. Introduction to Distributed Systems___Lab Session 01 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 3 e)listenConfigures a socket to accept conditions #include int listen(int sockfd, int backlog); listen() marks the socket referred to by sockfd as a passive socket, that is, as a socket that will be used to accept incoming connection requests using accept(). The backlog argument defines themaximumlengthtowhichthequeueofpendingconnectionsforsockfdmaygrow.Ifa connectionrequestarriveswhenthequeueisfull,theclientmayreceiveanerrorwithan indicationofECONNREFUSEDor,iftheunderlyingprotocolsupportsretransmission,the request may be ignored so that a later reattempt at connection succeeds. On success, zero is returned. On error, -1 is returned, and errno is set appropriately. f)acceptAccepts a connection and creates a new socket for the connection #include int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen); Theaccept()systemcallisusedwithconnection-basedsockettypes(SOCK_STREAM).It extractsthefirstconnectionrequestonthequeueofpendingconnectionsforthelistening socket, sockfd, creates a new connected socket, and returns a new file descriptor referring to that socket. The newly created socket is not in the listening state. The original socket sockfd is unaffected by this call. The argument addr is a pointer to a sockaddr structure. This structure is filled in with the address of the peer socket, as known to the communications layer. When addr is NULL, nothing is filled in; in this case, addrlen is not used, and should also be NULL. Theaddrlenargumentisavalue-resultargument:thecallermustinitializeittocontainthe size(inbytes)ofthestructurepointedtobyaddr;onreturnitwillcontaintheactualsizeof the peer address. The returned address is truncated if the buffer provided is too small; in this case, addrlen will return a value greater than was supplied to the call. Ifnopendingconnectionsarepresentonthequeue,andthesocketisnotmarkedasnon-blocking, accept() blocks the caller until a connection is present. If the socket is marked non-blockingandnopendingconnectionsarepresentonthequeue,accept()failswiththeerror EAGAIN or EWOULDBLOCK. In order to be notified of incoming connections on a socket, youcanuseselect()orpoll().Areadableeventwillbedeliveredwhenanewconnectionis attempted and you may then call accept() to get a socket for that connection. On success, this returns a nonnegative integer that is a descriptor for the accepted socket. On error, -1 is returned, and errno is set appropriately. Making a server The steps involved in establishing a socket on the server side are as follows: 1.Create a socket with the socket() system call. 2.Bindthesockettoanaddressusingthebind()systemcall.Foraserversocketonthe Internet, an address consists of a port number on the host machine. 3.Listen for connections with the listen() system call. 4.Accept a connection with the accept() system call. This call typically blocks until a client connects with the server. Introduction to Distributed Systems___Lab Session 01 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 4 5.Send and receive data. Data isnt read andwrittendirectly viatheserver socket; instead,each timeaprogram acceptsanew connection, Linux creates a separate socket to use in transferring data over that connection. Making a client The steps involved in establishing a socket on the client side are as follows: 1.Create a socket with the socket() system call. 2.Connect the socket to the address of the server using the connect() system call. 3.Send and receive data. There are a number of ways to do this, but the simplest is to use the read() and write() system calls. Local Sockets Socketsconnectingprocessesonthesamecomputer canusethelocalnamespacerepresentedbythe synonyms AF_LOCAL and AF_UNIX. These are called local sockets or UNIX-domain sockets. Their socket addresses, specified by filenames, are used only when creating connections. Thesocketsnameisspecifiedinstructsockaddr_un.Wemustsetthesun_familyfieldto AF_LOCAL, indicating that this is a local namespace. The sun_pathfield specifies the filename to use and may be, at most, 108 bytes long. Any filename canbeused, buttheprocessmusthavedirectorywritepermissions,which permitadding filesto the directory.Toconnecttoasocket,aprocessmusthavereadpermissionforthefile.Eventhough different computers may share the same file system, only processes running on the same computer can communicate with local namespace sockets. The only permissible protocol for the local namespace is 0.Because it resides in a file system, a local socket is listed as a file. Compilation and Execution Use the following format for compiling the codes: gcc sourcefile.c o outputfile Asaresultyoushouldgettwooutputfiles.Runtheoutputfilesintwoseparateterminals, makingsureyoupassthesocketfilenameasargumenttotheUnixserveratthecommand line. CODING un_server.c //The pathname of the socket address is passed as an argument. #include #include #include #include #include #include Introduction to Distributed Systems___Lab Session 01 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 5 void error(const char *) { perror(msg); exit(0); } int main(intargc, char *argv[]) { int sockfd, newsockfd, servlen, n; socklen_t clilen; struct sockaddr_un cli_addr, serv_addr; char buf[80]; if ((sockfd = socket(AF_UNIX,SOCK_STREAM,0)) < 0) error("creating socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sun_family = AF_UNIX; strcpy(serv_addr.sun_path, argv[1]); servlen=strlen(serv_addr.sun_path)+ sizeof(serv_addr.sun_family); if(bind(sockfd,(struct sockaddr *)&serv_addr, servlen). Closing tags start with .

Second, markup must nest properly. Markup tags divide into parents and children. Parent markup encloseschildmarkup.Achild'sopeningandclosingtagsmustbecontainedwithinitsparent's opening and closing tags. You can have

...but not... ...or... Third, if markup contains no content, it must begin with < and end with /> like . So if you declareyour XML version, begin and end opening tags with < and > and closing tags with ,andinsurechildmarkupnestscompletelywithinparentmarkup.Startempty markup with < and end it with />.Introduction to Distributed Computer SystemsLab Session 04 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 24

This XML is well-formed. wellform.xml is the simplest XML possible. If you need more power, you need valid XML. Using your text editor, type in:

]> &STATEMENT;

childsecond

Saveitas valid.xml.ValidXMLismorecomplexthanthewell-formedXMLused in simple.xml Description:, fills the same role it did in simple.xml. The second line, ., shows a DTD's most basic part, the element.

An element defines markup's name and form. declares: The markup tag's name (PARENT).The name of any child markup found within it (CHILD). Introduction to Distributed Computer SystemsLab Session 04 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 25

Howoftenitandanychildmarkupwithinitareneededandcanappear.(Bothareoptional and can appear more than once, as indicated by the *).

Thenextline,,liststhechildrenofthechild CHILD. It lists: The element's name (CHILD). The name of its children (MARK and NAME). That some of its children appear once or not at all (MARK, as indicated by the ?). That one of the children must appear one or more times (NAME, as indicated by the +). You can have

Orbut never showstheelementvalue EMPTY.Thisindicatesmarkup containing no content like... ...or... from simple.xml.

The following line, , tells us: The element name (NAME). That the children of the element must appear sequentially (as indicated by the comma). That these choices may be made more than once or not at all (as indicated by the *).

Thenexttwolinescontain #PCDATA. #PCDATA indicateswhenmarkupcontainscontent. This can be anything and does not have to follow the same rules as markup.

The following line contains another DTD fundamental, the attribute. An attribute is a description given to an element to further define it. Attributes are declared in attribute lists. The attribute list in valid.xml is

This tells you: The element the attribute list is attached to (MARK).Thatthefirstattribute(NUMBER)isuniquetext(asindicatedby ID)andrequired(as indicated by #REQUIRED).Thatthesecondattribute(LISTED)isregulartext(asindicatedby CDATA)andfixed(as indicated by #FIXED).Thatthethirdattribute(TYPE)isachoice(asindicatedbythe |)betweentwovalues "natural" and "adopted") and what the default choice is ("natural").Introduction to Distributed Computer SystemsLab Session 04 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 26

The result is: where,oftheattributes of MARK,"1"isrequiredandunique,"yes"isregulartextandfixed,and"natural"isthe chosen, default choice.

VALID.XML next brings up a third DTD part, the entity. Theentity points to a something that can be inserted at any point in the XML document. The line inserts This is well-formed XML whenever &STATEMENT appears.

The DTD then closes with]> and the rest of the XML document follows it as outlined. EXERCISES a.Is this a "well formed" XML document? Jaseem Kashif Reminder Don't forget to take me to ARENA this weekend! b.Is this a "well formed" XML document? Kashif Jaseem Reminder Don't forget me for dinner this weekend! c.Which statement is true? All XML elements must be lower case All the statements are true All XML documents must have a DTD All XML elements must be properly closed d.Is this a "well formed" XML document? Farrukh Jaseem Introduction to Distributed Computer SystemsLab Session 04 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 27 e.Is this a "well formed" XML document? Farrukh Jaseem Introduction to Distributed Computer SystemsLab Session 05 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 28 Lab Session 05 OBJECTIVE Understanding the concept of root elements and attributes in XML THEORY Inanymarkuplanguage,thefirstelementtoappeariscalledthe"rootelement",whichdefines what kind of document the file will be. In an HTML file, the tag is the root element. An HTML file will always have the HTML element as the root element, while in an XML file, it can be anything. An element is the basic building block of HTML and XML documents. Elements are identified by a tag. The tag consists of angle brackets and content, and looks like this: Syed Jaseemuddin In HTML, you use a pre-defined set of elements. In XML you create your own set of elements. Attributesarelikeadjectives,inthattheyfurtherdescribeelements.Eachattributehasaname and a value.Attributes contain anattribute values. The value might be a number, a word, or a URL. Attribute values follow the attribute and an equal sign. In XML, attribute values are always surrounded by quotation marks. Attributes are entered as part of the tag, like this: Syed Jaseemuddin Youuseatagtoidentifyapieceofdatabyelementname.Tagsusuallyappearinpairs, surroundingthedata.Theopeningtagcontainstheelementname.Theclosingtagcontainsa slash and the element's name, like this: Syed Jaseemuddin TheDTDdefinestheelements,attributes,andrelationshipsbetweenelementsforanXML document.ADTDisawaytocheckthatthedocumentisstructuredcorrectly,butyoudonot need to use one in order to use XML, as debated earlier. Now the root element, also referred to as the "document", dictates what kind of XML document it is. When creating an HTML file that is XML complaint, the root element will be . The rootelement must bethefirst element inanXMLdocumentandtherecanonlybe one root element per file! ThecoreofanXMLdocumentcomesfromtheelementsthatarecontainedwithintheroot element.Eachelementrepresentsadifferenttypeofdatathatisbeingstoredinthedocument. The element might represent paragraph text, while the element may contain data for a GIF image. Althoughnotrequired,elementsoftenhaveattributesthatareassociatedwiththem.XML attributesaresimilartoHTMLattributesinthattheyhaveaname:valuerelationship.An Introduction to Distributed Computer SystemsLab Session 05 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 29 example attribute foran element might be "src", which representsthe source location of the image. XML Element & Attribute Code: Inadditiontotheinformationstoredintheelementitself(attributes),thebulkofdatainXML usually appears between the opening and closing tag of an XML element.This is often referred to as the XML's "content". Below, we have an imaginary XML document that stores a story. XML Code: Jill Doe The Truth About the Family Here's a story of a polite person, Jaseem, who... ...he became the lecturer at NED... Can you tell which element is the root element in the above XML code? AsspecifiedearlierthatinanXMLfile,therecanonlybeonerootelement.Therootelement mustencapsulateallotherelements-meaning;theseotherelementsmustshowupafterthe opening root tag and before the closing root tag. Here is an example of an XML document with the root element "phonebook". Notice how the root element "phonebook" surrounds the other elements in XML file. Below is a brokenXMLfile.Trytoseeifyoucanfindwhatiswrongwiththisfilebeforereadingthe caption below. Introduction to Distributed Computer SystemsLab Session 05 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 30 Youshouldhavenoticedthattherootelement"phonebook"didnotcontainallotherelements becausetheclosingnametagisnotbetweentherootelementtagsand AnotherruleforXMLfilesisthatonly one rootelementperfileisallowed.Ourprevious example followed this rule, but our example below does not because it has two root elements. Whatarethetworootelements?Ifyousaidthetworootelementswere"phonebook"and "diary",thenyougotitright!Phonebookisthefirstelementtoappearinthisfile,soitis automatically a root element. After the phonebook element is closed, no other elements should follow because XML can only haveonerootelementperfile.Becausethe"diary"elementdidnotfollowthisrule,it transformed this XML file into a lawless, rule-breaking file! EXERCISES a.... Above XML is a compressed XML document for food menu This is how it looks like after expanding: Belgian Waffles $5.95 two of our famous Belgian Waffles with plenty of real maple syrup 650 Strawberry Belgian Waffles $7.95 light Belgian waffles covered with strawberries and whipped cream 900 Berry-Berry Belgian Waffles $8.95 Introduction to Distributed Computer SystemsLab Session 05 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 31 light Belgian waffles covered with an assortment of fresh berriesand whipped cream 900 French Toast $4.50 thick slices made from our homemade sourdough bread 600 Homestyle Breakfast $6.95 two eggs, bacon or sausage, toast, and our ever-popular hash browns 950 Identify the root elements if any. b.Write an XML CD catalogue document having CATALOG as the root element and following sub-elements: [Assume their attributes if possible.] Sub-elements: TITLE, ARTIST, COUNTRY, COMPANY, PRICE and YEAR Note: Should cover at least 10 different titles. Introduction to Distributed Computer SystemsLab Session 05 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 32 c.Write an XML Students catalogue document having UNDERGRAD as the root element and following sub-elements: [Assume their attributes yourself.] Sub-elements: NAME, DEPARTMENT, YEAR etc. as per your convenience. Note: Should cover at least 10 different names. Introduction to Distributed Computer SystemsLab Session 05 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 33 Introduction to Distributed Computer SystemsLab Session 06 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 34 Lab Session 06 OBJECTIVE I ntroduction to J ava Programming THEORY Theobjectsthatinteractinadistributedsystemneedtobedealtwithinwaysthatareintrinsically differentfromobjectsthatinteractinasingleaddressspace.Thesedifferencesarerequiredbecause distributedsystemsrequirethattheprogrammer beawareof latency, haveadifferentmodel of memory access, and take into account issues of concurrency and partial failure. Why Java? Java is not restricted to any onemedium, domain or technology. It is an ideal language for development ontheserver.Itsgarbagecollectionsupportremovesthetiresomeneedfordeveloperstoconcern themselveswiththeownershipsemanticsforobjects,atthecostofsomeperformance.Itssimplistic syntaxreducesthelearningcurvefordevelopersnewtoJavaanditssimilaritytoC++allowsforeasy migration of C++ developers to Java. ClassLoaders ClassLoaders are one of the most powerful technologies in Java; by allowing us, as developers, to control from where code can be loaded, we can now distribute applications in ways that we couldnt dream about five years ago. Consider a system in which customized behavior needs to be developed for a series of clients, varying not only on a per-client basis, but on a per-entity basis within the client. For example, an insurance company wantstoperformdifferenttasksonthecall-centerrepresentativesPCduringaninsurancesalescall, depending on what data is entered. Some sample ideas might be: Pop up a message box reminding the rep to suggestive-sell life-insurance policies to callers over the age of 30 Introduce new specials on various policies, but only if the candidate fits a particular criteria Remindthecallcenterrepofthemonthscurrentinternalpromotionalprogram,reminding him/her to undertake particular actions based on the reps proximity to the promotional target Realistically, these sorts of monthly changes could drive a developer mad a new release every month? Recording, retesting, everything, every month? Instead of coding these sorts of mutable rules directly within the application code, a custom ClassLoader is set up. Create the custom ClassLoader at a particular point during the call and load code associated with thiscalldirectlyfromthedatabase,or fromasocket,solongasthecodeiscomingfromacodesource separatefromtheapplicationitself.Thisallowsthedeveloperstochangethecodeassociatedwiththe database without having to modify the existing code base. On-the-fly code upgrades For years, developers have been searching for ways to upgrade code without bringing the server (or any clients using the code at the time of upgrade) completely down. Java allows us to do this sort of dynamic, on-the-fly upgrade. Your First Java Program Let us lead you into the world of Java programming by taking you through the three basic steps required togetasimpleprogramrunning.TheJavasystemisacollectionofapplicationsnotunlikeanyofthe otherapplicationsthatyouareaccustomedtousing(suchasyourwordprocessor,e-mailprogram,or Introduction to Distributed Computer SystemsLab Session 06 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 35 internetbrowser).Aswithanyapplication,youneedtobesurethatJavaisproperlyinstalledonyour computer. You also need an editor and a terminal application. Programming in Java We break the process of programming in Java into three steps:1.Createtheprogrambytypingitintoatexteditorandsavingittoafilenamed,say, MyProgram.java.2.Compile it by typing "javac MyProgram.java" in the terminal window.3.Run (or execute)it by typing "java MyProgram" in the terminal window. Thefirststepcreatestheprogram;thesecondtranslatesitintoalanguagemoresuitableformachine execution (and puts the result in a file named MyProgram.class); the third actually runs the program. Creating a Java program:. A program is nothing more than a sequence of characters, like asentence,aparagraph,orapoem.Tocreateone,weneedonlydefinethatsequence charactersusingatexteditor.HelloWorld.javaisanexampleprogram.Typethese characters into your text editor and save it into a file namedHelloWorld.java. public class HelloWorld { public static void main(String[] args) {System.out.println("Hello World"); } } CompilingaJavaprogram:Atfirst,itmightseemtoyouasthoughtheJava programminglanguageisdesignedtobebestunderstoodbythecomputer.Actually,to thecontrary,thelanguageisdesignedtobebestunderstoodbytheprogrammer(that's you).AcompilerisanapplicationthattranslatesprogramsfromtheJavalanguagetoa language more suitable for executing on the computer. It takes a text file with the.java extensionasinput(yourprogram)andproducesafilewitha.classextension(the computer-languageversion).TocompileHelloWorld.javatypetheboldfacedtext below at the terminal. (We use the % symbol to denote the command prompt, but it may appear different depending on your system.) % javac HelloWorld.java If you typed in the program correctly, you should see no error messages. Otherwise, go back and make sure you typed in the program exactly as it appears above. ExecutingaJavaprogram:Onceyoucompileyourprogram,youcanrunit.Thisisthe excitingpart,wherethecomputerfollowsyourinstructions.Torunthe HelloWorldprogram, type the following at the terminal: %java HelloWorld If all goes well, you should see the following response: Hello World EXERCISES a.Write a program TenHelloWorlds.java that prints "Hello World" ten times? Introduction to Distributed Computer SystemsLab Session 06 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 36 b.Describe what happens if, in HelloWorld.java, you omit: i.publicii.staticiii.voidiv.args Introduction to Distributed Computer SystemsLab Session 06 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 37 c.Describewhathappensif,inHelloWorld.java,youmisspell(by,say,omittingthesecond letter)i.publicii.staticiii.voidiv.args d.Itypedinthefollowingprogram.Itcompilesfine,butwhenIexecuteit,Igettheerror java.lang.NoSuchMethodError: main. What am I doing wrong? Public class Hello { Public static void main() { System.out.println(Doesnt execute); Introduction to Distributed Computer SystemsLab Session 07 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 38 Lab Session 07 OBJECTIVE Creating a distributed version of the classic Hello World program using J ava Remote Method I nvocation (RMI ) (Part 1) THEORY ThedistributedHelloWorldexampleusesanapplettomakearemotemethodcalltoanRMI server,runningonthehostfromwhichtheappletwasdownloaded.Whentheappletruns, "Hello World" is displayed on the client browser. This lab session is organized in three steps:1.The steps to write the source files and the HTML file2.The steps to compile and deploy class files and the HTML file3.The steps to start the RMI registry, server, and applet The first step will be covered inLab session7 and rest of the two stepswill be covered inLab session 8. The files needed for this example are:Hello.java - a remote interfaceHelloImpl.java-aremoteobjectimplementationthatimplements examples.hello.Hello HelloApplet.java - an applet that invokes the remote method, sayHello hello.html - the HTML page that references the applet The source and HTML files Because the Java programming language requires a mapping between the fully-qualified package name of a class and the directory path to that class, you should decide on package and directory namesbeforeyoubeginwritinganycodewrittenintheJavaprogramminglanguage.This mapping allows the compiler for the Java programming language to know the directory in which tofindtheclassfilesmentionedinaprogram.Fortheprogramsinthisexample,thepackage name is examples.hello and the source directory is $HOME/mysrc/examples/hello. TocreatethedirectoryforyoursourcefilesinMicrosoftWindowsplatforms,youwouldgoto the directory of your choice, and type:mkdir mysrc mkdir mysrc\examples mkdir mysrc\examples\hello There are three tasks to be completed in this session:1.Define the functions of the remote class as an interface written in the Java programming language2.Write the implementation and server classes3.Write a client program that uses the remote service Introduction to Distributed Computer SystemsLab Session 07 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 39 The functions of the remote class as an interface written in the Java programming language IntheJavaprogramminglanguage,aremoteobjectisaninstanceofaclassthatimplementsa Remote interface. Your remote interface will declare each of the methodsthat you would like to call from other Java virtual machines (JVMs). Remote interfaces have the following characteristics: Theremoteinterfacemustbedeclaredpublic.Otherwise,aclientwillgetanerror when attempting to load a remote object that implements the remote interface, unless that client is in the same package as the remote interface.The remote interface extends the java.rmi.Remote interface.Eachmethodmustdeclarejava.rmi.RemoteException(orasuperclassof RemoteException)initsthrowsclause,inadditiontoanyapplication-specific exceptions.Thedatatypeofanyremoteobjectthatispassedasanargumentorreturnvalue(either directly or embedded within a local object) must be declared as the remote interface type (for example, Hello) not the implementation class (HelloImpl). Hereistheinterfacedefinitionfortheremoteinterface,examples.hello.Hello.The interface contains just one method, sayHello, which returns a string to the caller: package examples.hello; import java.rmi.Remote; import java.rmi.RemoteException; public interface Hello extends Remote { String sayHello() throws RemoteException; } Remote method invocations can fail in very different ways from local method invocations (due to network-relatedcommunicationproblemsandserverproblems),remotemethodswillreport communication failures by throwing a java.rmi.RemoteException. The implementation and server classes At a minimum, a remote object implementation class must:i.Declare that it implements at least one remote interfaceii.Define the constructor for the remote objectiii.Provide implementations for the methods that can be invoked remotely A "server" class, in this context, is the class which has a main method that creates an instance of the remote object implementation, and binds that instance to a name in the rmiregistry. The classthatcontainsthismainmethodcouldbetheimplementationclassitselforanotherclass entirely. Inthisexample,the mainmethodispartofexamples.hello.HelloImpl.Theserver program needs to:i.Create and install a security manager Introduction to Distributed Computer SystemsLab Session 07 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 40 ii.Create one or more instances of a remote objectiii.RegisteratleastoneoftheremoteobjectswiththeRMIremoteobjectregistry,for bootstrapping purposes An explanation of each of the preceding six steps follows the source for HelloImpl.java: package examples.hello; import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.RMISecurityManager; import java.rmi.server.UnicastRemoteObject; publicclassHelloImplextendsUnicastRemoteObject implements Hello { public HelloImpl() throws RemoteException { super(); } public String sayHello() { return "Hello World!"; } public static void main(String args[]) { // Create and install a security manager if (System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } try { HelloImplobj = new HelloImpl(); //Bindthisobjectinstancetothename "HelloServer" Naming.rebind("//myhost/HelloServer", obj); System.out.println("HelloServer bound in registry"); } catch (Exception e) { System.out.println("HelloImpl err: " + e.getMessage()); e.printStackTrace(); } } } Implement a remote interface IntheJavaprogramminglanguage,whenaclassdeclaresthatitimplementsaninterface,a contract is formed between the class and the compiler. By entering into this contract, the class is promisingthatitwillprovidemethodbodies,ordefinitions,foreachofthemethodsignatures Introduction to Distributed Computer SystemsLab Session 07 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 41 declaredinthatinterface.Interfacemethodsareimplicitlypublicandabstract,soifthe implementationclassdoesn'tfulfillitscontract,itbecomesbydefinitionanabstractclass, and the compiler will point out this fact if the class was not declared abstract. Theimplementationclassinthisexampleisexamples.hello.HelloImpl.The implementationclassdeclareswhichremoteinterface(s)itisimplementing.Hereisthe HelloImplclass declaration: public class HelloImpl extends UnicastRemoteObject implements Hello { As a convenience, the implementation class can extend a remote class, which in this example is java.rmi.server.UnicastRemoteObject.Byextending UnicastRemoteObject, the HelloImplclass can be used to create a remote object that:Uses RMI's default sockets-based transport for communicationRuns all the time Define the constructor for the remote object Theconstructorforaremoteclassprovidesthe samefunctionalityastheconstructorforanon-remote class: it initializes the variables of each newly created instance of the class, and returns an instance of the class to the program which called the constructor. Inaddition,theremoteobjectinstancewillneedtobe"exported".Exportingaremoteobject makes it available to accept incoming remote method requests, by listening for incoming calls to theremoteobjectonananonymousport.Whenyouextend java.rmi.server.UnicastRemoteObjectorjava.rmi.activation.Activatable, your class will be exported automatically upon creation. If you choose to extend a remote object from any class other than UnicastRemoteObject or Activatable,youwillneedtoexplicitlyexporttheremoteobjectbycallingeitherthe UnicastRemoteObject.exportObjectmethodorthe Activatable.exportObjectmethodfromyourclass'sconstructor(oranother initialization method, as appropriate). Becausetheobjectexportcouldpotentiallythrowajava.rmi.RemoteException,you mustdefineaconstructorthatthrowsaRemoteException,eveniftheconstructordoes nothing else. If you forget the constructor, javac will produce the following error message: HelloImpl.java:13:Exceptionjava.rmi.RemoteExceptionmustbe caught, or it must be declared in the throws clause of this method.super();^ 1 error Here is the constructor for the examples.hello.HelloImpl class: public HelloImpl() throws RemoteException {Introduction to Distributed Computer SystemsLab Session 07 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 42 super();} Thesupermethodcallinvokestheno-argumentconstructorof java.rmi.server.UnicastRemoteObject, which exports the remote object. Theconstructormustthrowjava.rmi.RemoteException,becauseRMI'sattempt toexportaremoteobjectduringconstructionmightfailifcommunicationresourcesare not available. Provide an implementation for each remote method Theimplementationclassforaremoteobjectcontainsthecodethatimplementseachofthe remotemethodsspecifiedintheremoteinterface.Forexample,hereistheimplementationfor the sayHello method, which returns the string "Hello World" to the caller: public String sayHello() throws RemoteException { return "Hello World!"; } Arguments to, or return values from, remote methods can be any data type for the Java platform, including objects, as long as those objects implement the interface java.io.Serializable. Mostofthecoreclassesinjava.langandjava.utilimplementtheSerializable interface. Create and install a security manager Themain methodoftheserverfirstneedstocreateandinstallasecuritymanager:eitherthe RMISecurityManageror one that you have defined yourself. For example: if (System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } A security manager needs to be running so that it can guarantee that the classes that get loaded do not perform operations that they are not allowed to perform.If no security manager is specified no class loading, by RMI clients or servers, is allowed, aside from what can be found in the local CLASSPATH.Inthisexample,asecuritymanagerisnotinstalledintheclientcodebecause appletsusethesecuritymanageralreadyinstalledintheclientbrowser.Iftheclientwerean application rather than an applet, however, you would need to use the same procedure as is used above to install a security manager in the client. A security manager is required in any JVM that needstodownloadcode,andRMIclientsneedtodownloadRMIstubs(aswellasanyother custom classes or interfaces needed to communicate with the RMI server). Create one or more instances of a remote object Themainmethodoftheserverneedstocreateoneormoreinstancesoftheremoteobject implementation which provides the service. For example: HelloImpl obj = new HelloImpl(); Theconstructorexportstheremoteobject,whichmeansthatoncecreated,theremoteobjectis ready to accept incoming calls. Introduction to Distributed Computer SystemsLab Session 07 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 43 Register the remote object For a caller (client, peer, or applet) to be able to invoke a method on a remote object, that caller must first obtain a reference to the remote object. For bootstrapping, the RMI system provides a remote object registry that allows you to bind a URL-formatted name of the form "//host/objectname" to the remote object, where objectname is a simple string name. TheRMIregistryisasimpleserver-sidenameservicethatallowsremoteclientstogeta referencetoaremoteobject.ItistypicallyusedonlytolocatethefirstremoteobjectanRMI clientneedstotalkto.Thenthatfirstobjectwouldinturnprovideapplication-specificsupport for finding other objects. Forexample,thereferencecanbeobtainedasaparameterto,orareturnvaluefrom,another remote method call. Once a remote object is registered on the server, callers can look up the object by name, obtain a remoteobjectreference,andthenremotelyinvokemethodsontheobject.Forexample,the following code binds the name "HelloServer" to a reference for the remote object: Naming.rebind("//myhost/HelloServer", obj); Note the following about the arguments to the rebind method call: The first parameter is a URL-formatted java.lang.String, representing the location and name of the remote object.oNo protocol needs to be specified in the URL-formatted string.oYouwillneedtochangethevalueofmyhosttobethenameorIPaddressof yourservermachine;otherwise,theremoteobjecthostdefaultstothecurrent host. For example, "HelloServer" is a valid name string that refers to a remote object bound to the name HelloServer, running on the local host.oOptionally,aportnumbercanbesuppliedintheURL-formattedstring. Specifyingtheportnumberisnecessarywhentheregistrythatneedstobe contactedisrunningonaportotherthanthedefaultport,1099.Forexample, "//myhost:1234/HelloServer"isavalidnamestringforthe HelloServer remote object, reachable through an RMI registry that is running on the host myhost and is listening for incoming calls on port 1234.Thesecondparameterisareferencetotheobjectimplementation,onwhichremote methods will be invoked.Once an object is exported, the RMI runtime substitutes a reference to the remote object's stub for the actual remote object reference specified by the obj argument. When a client performs a lookup in a server's remote object registry, a serialized instance of the stub for the implementation is returned. Write a client program that uses the remote service The applet in this example remotely invokes the sayHello method in order to get the string "Hello World!" to display when the applet runs. Here is the code for the applet:package examples.hello; Introduction to Distributed Computer SystemsLab Session 07 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 44 import java.applet.Applet; import java.awt.Graphics; import java.rmi.Naming; import java.rmi.RemoteException; public class HelloApplet extends Applet { String message = "blank"; // "obj" is the identifier that we'll use to refer// to the remote object that implements the "Hello"// interfaceHello obj = null; public void init() {try {obj = (Hello)Naming.lookup("//" +getCodeBase().getHost() + "/HelloServer");message = obj.sayHello();} catch (Exception e) {System.out.println("HelloApplet exception: " + e.getMessage());e.printStackTrace();}} public void paint(Graphics g) {g.drawString(message, 25, 50);}} 1.First,theappletgetsareferencetotheremoteobjectimplementation(advertisedas "HelloServer")fromtheserverhost'srmiregistry.LiketheNaming.rebind method, the Naming.lookup method takes aURL-formatted java.lang.String. Inthisexample,theappletconstructstheURLstringbyusingthegetCodeBase method in conjunction with the getHost method. Naming.lookup takes care of the following tasks:oConstructingaregistrystubinstance(tocontacttheserver'sregistry)usingthe hostname and port number supplied as arguments to Naming.lookup oUsingtheregistrystubtocalltheremotelookupmethodontheregistry,using the URL's name component ("HelloServer")The registry returns the HelloImpl_Stub instance bound to that nameThelookupmethodreceivestheremoteobject's(HelloImpl)stub instanceandloadsthestub class(examples.hello.HelloImpl_Stub)fromtheCLASSPATH or the applet's codebaseoNaming.lookupreturns the stub to its caller (HelloApplet)2.The applet invokes the remote sayHello method on the server's remote objectoRMI serializes and returns the reply string "Hello World!"oRMI deserializes the string and stores it in a variable named message.Introduction to Distributed Computer SystemsLab Session 07 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 45 3.The applet paint invokes the method, causing the string "Hello World!" to be displayed in the drawing area of the applet. The URL-formatted string that is passedas a parameter to theNaming.lookup method must includetheserver'shostname.Otherwise,theapplet'slookupattemptwilldefaulttotheclient, and the AppletSecurityManagerwill throw an exception because the applet cannot access the local system, but is instead limited to only communicating with the applet's host. Here is the HTML code for the web page that references the Hello World applet: Hello World Hello World Note the following:ThereneedstobeanHTTPserverrunningonthemachinefromwhichyouwantto download classes.ThecodebaseintheHTMLfilespecifiesadirectorybelowthedirectoryfromwhich the web page was itself loaded. Using this kind of relative path is usually a good idea. For example,ifthecodebasedirectory(wheretheapplet'sclassfileslive),referencedby theapplet'sHTML,wasinthedirectoryabovetheHTMLdirectory,youwouldusethe relative path, "../".Theapplet'scodeattributespecifiesthefully-qualifiedpackagenameoftheapplet,in this example examples.hello.HelloApplet: code="examples.hello.HelloApplet" Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 46 Lab Session 08 OBJECTIVE Creating a distributed version of the classic Hello World program using J ava Remote Method I nvocation (RMI ) (Part 2) THEORY The lab session 2 was organized in three steps:1.The steps to write the source files and the HTML file2.The steps to compile and deploy class files and the HTML file3.The steps to start the RMI registry, server, and applet The first step was covered in Lab session 7 and the rest of the two steps are to be covered in this Lab session. Compile and Deploy Class Files and HTML Files Thesourcecodeforthisexampleisnowcompleteandthe $HOME/mysrc/examples/hello directory has four files:Hello.java contains the source code for the Hello remote interface. HelloImpl.javacontainsthesourcecodefortheHelloImplremoteobject implementation and the RMI server for the applet.HelloApplet.java contains the source code for the applet.hello.html is the web page that references the Hello World applet. Inthissection,youwillcompilethe.javasourcefilestocreate.classfiles.Youthenrun the rmic compiler to create stubs and skeletons. A stub is a client-side proxy for a remote object whichforwardsRMIcallstotheserver-sidedispatcher,whichinturnforwardsthecalltothe actual remote object implementation. When you use the javac and rmic compilers, you must specify where the resulting class files should reside. For applets, all files should be in the applet's codebase directory. For our example, this directory is $HOME/public_html/myclasses. Some web servers allow accessing a user's public_html directory via an HTTP URL constructed as "http://host/~username/". If your web server does not support this convention, you coulduseafileURLoftheform"file:/home/username/public_html"fortesting, but this approach will limit you to communicating between a client and server that have access to thesamephysicalfilesystem.Asanalternative,youcanuseanHTTPURLbysettingupa minimal web server on your system. There are four tasks to complete in this section:1.Compile the source files2.Use rmic to generate stubs and skeletons3.Move the HTML file to the deployment directory4.Set paths for runtimeIntroduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 47 Compile the source files Makesurethatthedeploymentdirectory$HOME/public_html/myclassesandthe developmentdirectory$HOME/mysrc/examples/helloareeachaccessiblethroughthe local CLASSPATH on the development machine before attempting to compile. To compile the source files, run the javac command as follows:javac -d$HOME/public_html/myclasses Hello.javaHelloImpl.javaHelloApplet.java Thiscommandcreatesthedirectoryexamples/hello(ifitdoesnotalreadyexist)inthe directory $HOME/public_html/myclasses. The command then writes to that directory the filesHello.class,HelloImpl.class,andHelloApplet.class.Thesearethe remote interface, the implementation, and the applet respectively. Use rmic to generate skeletons and/or stubs To create stub and skeleton files, run the rmic compiler on the fully-qualified package names of compiledclassfilesthatcontainremoteobjectimplementations,likemy.package.MyImpl. Thermiccommandtakesoneormoreclassnamesasanargumentandproducesclassfilesof the form MyImpl_Skel.class and MyImpl_Stub.class. Bydefault,intheJava2SDK,v1.2andlater,rmicrunswiththe-vcompatflagon,which produces stubs and skeletons that support access to:1.Unicast (not Activatable) remote objects from 1.1 clients and2.All types of remote objects from 1.2 (and later) clients Ifyouwillneverneedsupportfor1.1clients,rmiccanberunwiththe-v1.2option.For example, to create the stub and skeleton for the HelloImpl remote object implementation, run rmic like this: rmic -d$HOME/public_html/myclassesexamples.hello.HelloImpl The"-d"optionindicatestherootdirectoryinwhichtoplacethecompiledstubandskeleton classfiles.Sotheprecedingcommandcreatesthefollowingfilesinthedirectory $HOME/public_html/myclasses/examples/hello: HelloImpl_Stub.class HelloImpl_Skel.class Thegeneratedstubclassimplementsexactlythesamesetofremoteinterfacesastheremote object itself. This means that a client can use the Java programming language's built-in operators forcastingandtypechecking.ItalsomeansthatremoteobjectswrittenfortheJavaplatform support true object-oriented polymorphism. Move the HTML file to the deployment directory To make the web page that references the applet visible to clients, the hello.html file must be moved from the development directory to the applet's codebase directory. For example: Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 48 mv$HOME/mysrc/examples/hello/hello.html$HOME/public_html/ Set paths for runtime Make sure that the $HOME/public_html/myclasses directory is available through the server's local CLASSPATH when you run the HelloImpl server. Start the RMI registry, server, and applet There are three tasks to complete in this section:i.Start the RMI registryii.Start the serveriii.Run the applet Start the RMI registry The RMI registry is a simple server-side name server that allows remote clients to get a reference to a remote object. Typically, it is used only to locate the first remote object an application needs totalkto.Thenthatobjectinturnwouldprovideapplication-specificsupportforfindingother objects. Before you start the rmiregistry, you must make sure that the shell or window in which you will run the registry either has no CLASSPATH set or has a CLASSPATH that does not include thepathtoanyclassesthatyouwantdownloadedtoyourclient,includingthestubsforyour remote object implementation classes. Ifyoustartthermiregistry,anditcanfindyourstubclassesinitsCLASSPATH,itwill ignoretheserver'sjava.rmi.server.codebaseproperty,andasaresult,yourclient(s) will not be able to download the stub code for your remote object. Tostarttheregistryontheserver,executethermiregistrycommand.Thiscommand produces no output and is typically run in the background. For example, on Microsoft Windows 95 systems:startrmiregistry (Use javaw if start is not available.) Bydefault,theregistryrunsonport1099.Tostarttheregistryonadifferentport,specifythe portnumberfromthecommandline.Forexample,tostarttheregistryonport2001ona Microsoft Windows NT system:startrmiregistry 2001 If the registry is running on a port other than 1099, you'll need to specify the port number in the name handed to the URL-based methods of the java.rmi.Naming class when making calls to the registry. For example, if the registry is running on port 2001 in this example, the call required to bind the name "HelloServer" to the remote object reference would be: Naming.rebind("//myhost:2001/HelloServer", obj); Youmuststopandrestarttheregistryanytimeyoumodifyaremoteinterfaceoruse modified/additional remote interfaces in a remote object implementation. Otherwise, the type of the object reference bound in the registry will not match the modified class. Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 49 Start the server When starting the server, the java.rmi.server.codebase property must be specified, so that the stub class can be dynamically downloaded to the registry and then to the client. Run the server, setting the codebase property to be the location of the implementation stubs. Because the codebasepropertyinthisexamplereferencesadirectory,makesurethatanyotherclassesthat mayneedtobedownloadedhavealsobeeninstalledinthedirectoryreferencedby java.rmi.server.codebase. A stub class is dynamically downloaded to a client's virtual machine only when theclass is not alreadyavailablelocallyandthejava.rmi.server.codebasepropertyhasbeenset properly to specify where the class files are located on the server. There are four things that need to go on the same command line: the "java" command, followed bytwopropertyname=valuepairs(forthecodebaseproperty,notethattherearenospaces fromthe"-D"allthewaythoughthelast"/")andthenthefully-qualifiedpackagenameofthe server program. There should be a space just after the word "java", between the two properties, and just before the word "examples" (which is very hard to see when you view this as text, in a browser,oronpaper).ThefollowingcommandshowshowtostarttheHelloImplserver, specifying the java.rmi.server.codebase and java.security.policy properties: java -Djava.rmi.server.codebase=http://myhost/~myusrname/myclasses/ -Djava.security.policy=$HOME/mysrc/policyexamples.hello.HelloImpl In order to run this code on your system, you'll need to change the location of thepolicy file tobethelocationofthedirectoryonyoursystem,whereyou'veinstalledtheexamplesource code. Note:Inthisexample,forsimplicity,wewilluseapolicyfilethatgivesglobalpermissionto anyone from anywhere. Do not use this policy file in a production environment. ThecodebasepropertywillberesolvedtoaURL,soitmusthavetheformof "http://aHost/somesource/" or "file:/myDirectory/location/" or, due to the requirementsofsomeoperatingsystems,"file:///myDirectory/location/"(three slashes after the "file:").PleasenotethateachoftheURLstringsabovehasatrailing"/".Thetrailingslashisa requirementfortheURLsetbythejava.rmi.server.codebaseproperty,sothe implementation can resolve (find) your class definition(s) properly. If you forget the trailing slash on the codebase property, or if the class files can't be located at the source (they aren't really being made available for download) or if you misspell the property name,you'llgetthrownajava.lang.ClassNotFoundException.Thisexceptionwill bethrownwhenyoutrytobindyourremoteobjecttothermiregistry,orwhenthefirst client attempts to access that object's stub. If the latter case occurs, you have another problem as well because the rmiregistrywas finding the stubs in its CLASSPATH. The output should look like this:HelloServer bound in registry Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 50 Run the applet Oncetheregistryandserverarerunning,theappletcanberun.Anappletisrunbyloadingits web page into a browser or appletviewer, as shown here:appletviewer http://myhost/~myusrname/hello.html & After running the applet viewer, you will see output similar to the following on your display: Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 51 Lab Session 09 OBJECTIVE Understanding the concept of I ndirect Communication and exploring group communication mechanism via J Group Toolkit. THEORY Indirect Communication Indirectcommunicationisdefinedascommunicationbetweenentitiesinadistributedsystem throughanintermediarywithnodirectcouplingbetweenthesenderandthereceiver(s).The precise nature of the intermediary varies from approach to approach. The techniques that areall based on a direct coupling between a sender and a receiver, and this leads to a certain amount of rigidity in the system in terms of dealing with change. To illustrate this,considerasimpleclient-serverinteraction.Becauseofthedirectcoupling,itismore difficult to replace a server with an alternative one offering equivalent functionality. Similarly, if theserverfails,thisdirectlyaffectstheclient,whichmustexplicitlydealwiththefailure.In contrast,indirectcommunicationavoidsthisdirectcouplingandhenceinheritsinteresting properties. The literature refers to two key properties stemming from the use of an intermediary: Space uncoupling, in which the sender does not know or need to know the identity of the receiver(s),andviceversa.Becauseofthisspaceuncoupling,thesystemdeveloperhas manydegrees of freedom in dealing withchange: participants(senders or receivers)can be replaced, updated, replicated or migrated. Time uncoupling, in which the sender and receiver(s) can have independent lifetimes. In otherwords,thesenderandreceiver(s)donotneedtoexistatthesametimeto communicate.Thishasimportantbenefits,forexample,inmorevolatileenvironments where senders and receivers may come and go. Group Communication Group communication provides our first example of an indirect communication paradigm. Group communicationoffersaservicewherebyamessageissenttoagroupandthenthismessageis delivered to all members of the group.In this action, the sender is not aware of the identities of the receivers. Group communication represents an abstraction over multicast communication and may be implemented over IP multicast or an equivalent overlay network, adding significant extra valueintermsofmanaginggroupmembership,detectingfailuresandprovidingreliabilityand ordering guarantees. The Programming Model Ingroupcommunication,thecentralconceptisthatofagroupwithassociatedgroup membership, whereby processes may join or leave the group. Processes can then send a message to this group and have it propagated to all members of the group with certain guarantees in terms of reliability and ordering. Thus, group communication implements multicast communication, in which a message is sent to all the members of the group by a single operation. Communication to Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 52 allprocessesinthesystem,asopposedtoasubgroupofthem,isknownasbroadcast,whereas communication to a single process is known as unicast. Theessentialfeatureofgroupcommunicationisthataprocessissuesonlyonemulticast operationtosendamessagetoeachofagroupofprocesses(inJavathisoperationis aGroup.send (aMessage)) instead of issuing multiple send operations to individual processes. Process Groups and Object Groups Most work on group services focuses on the concept of process groups, that is, groups where the communicating entities are processes. Such services are relatively low-level in that: Messages are delivered to processes and no further support for dispatching is provided. Messagesaretypicallyunstructuredbytearrayswithnosupportformarshallingofcomplex data types (as provided, for example, in RPC or RMI). The level of service provided by process groups is therefore similar to that of sockets. In contrast, objectgroupsprovideahigher-levelapproachtogroupcomputing.Anobjectgroupisa collectionofobjects(normallyinstancesofthesameclass)thatprocessthesamesetof invocations concurrently, with each returning responses. Client objects need not be aware of the replication. They invoke operations on a single, local object, which acts as a proxy for the group. Theproxyusesagroupcommunicationsystemtosendtheinvocationstothemembersofthe object group. Object parameters and results are marshalled as in RMI and the associated calls are dispatched automatically to the right destination objects/methods. Other Key Distinctions Awiderangeofgroupcommunicationserviceshasbeendeveloped,andtheyvaryinthe assumptions they make: ClosedandOpenGroups:Agroupissaidtobeclosedifonlymembersofthegroupmay multicast to it. A process in a closed group delivers to itself any message that it multicasts to the group. A group is open if processes outside the group may send to it. (The categories open and closedalsoapplywithanalogousmeaningstomailinglists).Closedgroupsofprocessesare useful,forexample,forcooperatingserverstosendmessagestooneanotherthatonlythey should receive. Open groups are useful, for example, for delivering events to groups of interested processes. OverlappingandNon-OverlappingGroups:Inoverlappinggroups,entities(processesor objects)maybemembersofmultiplegroups,andnon-overlappinggroupsimplythat membershipdoesnotoverlap(thatis,anyprocessbelongstoatmostonegroup).Notethatin real-life systems, it is realistic to expect that group membership will overlap. Implementation Issues Reliability and Ordering In Multicast In group communication, all members of a group must receive copies of the messages sent to the group,generallywithdeliveryguarantees.Aswellasreliabilityguarantees,group communication demands extra guarantees in terms of the relative ordering of messages delivered to multiple destinations.Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 53 FI FO Ordering: First-in-first-out (FIFO) ordering (also referred to as source ordering) is concerned with preserving the order from the perspective of a sender process, in that if a processsendsonemessagebeforeanother,itwillbedeliveredinthisorderatall processes in the group. CausalOrdering:Causalorderingtakesintoaccountcausalrelationshipsbetween messages, in that if a message happens before another message in the distributed system thisso-calledcausalrelationshipwillbepreservedinthedeliveryoftheassociated messages at all processes. Total Ordering: In total ordering, if a message is delivered before another message at one process, then the same order will be preserved at all processes. Group Membership Management Providinganinterfaceforgroupmembershipchanges:Themembershipservice providesoperationstocreateanddestroyprocessgroupsandtoaddorwithdrawa processtoorfromagroup.Inmostsystems,asingleprocessmaybelongtoseveral groups at the same time (overlapping groups).Failure detection: The service monitors the group members not only in case they should crash,butalsoincasetheyshouldbecomeunreachablebecauseofacommunication failure. The detector marks processes as Suspected or Unsuspected. The service uses the failuredetectortoreachadecisionaboutthegroupsmembership:itexcludesaprocess from membership if it is suspected to have failedor to have become unreachable. Notifyingmembersofgroupmembershipchanges:Theservicenotifiesthegroups memberswhenaprocessisadded,orwhenaprocessisexcluded(throughfailureor when the process is deliberately withdrawn from the group) Performing group address expansion: When a process multicasts a message, it supplies thegroupidentifierratherthanalistofprocessesinthegroup.Themembership managementserviceexpandstheidentifierintothecurrentgroupmembershipfor delivery. The JGroup Toolkit JGroupsisatoolkitforreliablegroupcommunicationwritteninJava (http://www.jgroups.org/index.html).JGroupssupportsprocessgroupsinwhichprocessesare abletojoinor leaveagroup,sendamessagetoallmembersofthegrouporindeedtoasingle member,andreceivemessagesfromthegroup.Thetoolkitsupportsavarietyofreliabilityand orderingguarantees,whicharediscussedinmoredetailbelow,andalsooffersagroup membership service. The architecture of JGroups has the following main components of the JGroups implementation: Channelsrepresentthemostprimitiveinterfaceforapplicationdevelopers,offeringthe core functions of joining, leaving, sending and receiving. Building blocks offer higher-level abstractions, building on the underlying service offered by channels. Protocol Stack provides the underlying communication protocol, constructed as a stack of protocol layers. JGroup API Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 54 The API of JGroups is very simple. The code is always the same, regardless of the protocol stack used. To be able to send/receive messages, a channel has to be created. The reliability of a channel is specifiedviaXML,whichthencausesthecreationoftheunderlyingprotocolstack.The example below creates a channel and sends/receives 1 message: JChannel channel=new JChannel("/home/bela/udp.xml"); channel.setReceiver(new ReceiverAdapter() { public void receive(Message msg) { System.out.println("received msg from " + msg.getSrc() + ": " + msg.getObject()); } }); channel.connect("MyCluster"); channel.send(new Message(null, "hello world")); channel.close(); The channel's configuration is defined in the constructor. In the sample code, we use an XML file with an absolute path. If we use a relative path, then the file is looked up on the classpath.The XML file contains a list of protocols to be used by the new channel.Tojoinacluster,connect()iscalled.Itreturnswhenthememberhassuccessfullyjoinedthe cluster named "MyCluster", or when it has created a new cluster (if it is the first member).Then a message is sent using the send() method. A message contains the receiver's address (null =allclusternodes)andabytebuffer.Intheexample,thestring"helloworld"issettobethe message's contents. It is serialized into the message's byte buffer.Sincethemessageissenttoallmembers,thesenderwillalsoreceiveit.Thisisdoneviathe receive() callback, which was registered with the channel before.Finally,thememberclosesthechannelandthusleavesthecluster.Thisresultinanotification being sent to all members who are registered for membership change notifications.JGroup DemosStudentsareadvisedtovisitthesesites:http://www.jgroups.org/manual/html_single/#d0e226 andhttp://www.jgroups.org/demos.htmlinordertohaveaninsightofinstallation& configuration of toolkit and also to have clear understanding of different examples present in the demonstration. Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 55 Exercises Q.1) Explain briefly Indirect Communication with at least two examples. Why do we need Group Communication? Q.2)ExploreJ GroupToolkit.DiscussitskeyfeaturesalsoexplainitsFlexibleProtocol Stack. Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 56 Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 57 Lab Session 10 OBJECTIVE Understanding the concept of message queues via J ava Messaging Service (J MS) THEORY Message queues (or more accurately, distributed message queues) are another important category ofindirectcommunicationsystems.Whereasgroupsandpublishsubscribeprovideaone-to-many style of communication, message queues provide a point-to-point service using the concept ofamessagequeueasanindirection,thusachievingthedesiredpropertiesofspaceandtime uncoupling.Heresenderplacesthemessageintoaqueue,anditisthenremovedbyasingle process.MessagequeuesarealsoreferredtoasMessage-OrientedMiddleware.Thisisamajor classofcommercialmiddlewarewithkeyimplementationsincludingIBMsWebSphereMQ, Microsofts MSMQ and Oracles Streams Advanced Queuing (AQ). The Programming Model Theprogrammingmodelofferedbymessagequeuesisverysimple.Itoffersanapproachto communication in distributed systems through queues. In particular, producer processes can send messages to a specific queue and other (consumer) processes can then receive messages from this queue. Three styles of receive are generally supported: A blocking receive, which will block until an appropriate message is available; Anon-blockingreceive(apollingoperation),whichwillcheckthestatusofthequeue and return a message if available, or a not available indication otherwise; A notify operation, which will issue an event notification when a message is available in the associated queue. A number of processes can send messages to the same queue, and likewise a number of receivers can remove messages from a queue. The queuing policy is normally first-in-first-out (FIFO), but mostmessagequeueimplementationsalsosupporttheconceptofpriority,withhigher-priority messages delivered first. Consumer processes can also select messages from the queue based on properties of a message. Java Messaging Service (JMS) The Java Messaging Service (JMS)is a specification of a standardized wayfor distributed Java programstocommunicateindirectly.Awidevarietyofimplementationsofthecommon specification are now available, including Joram from OW2, Java Messaging from JBoss, Suns OpenMQ,ApacheActiveMQandOpenJMS.Otherplatforms,includingWebSphereMQ,also provide a JMS interface on to their underlying infrastructure. JMS distinguishes between the following key roles: AJMSclientisaJavaprogramorcomponentthatproducesorconsumesmessages,aJMS producer is a program that creates and produces messages and a JMS consumer is a program that receives and consumes messages. A JMS provider is any of the multiple systems that implement the JMS specification. Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 58 A JMS message is an object that is used to communicate information betweenJMS clients (from producers to consumers). Figure 1.1 JMS API Programming Model Programming with JMS The programming model offered by the JMS API is captured in Figure 1.1 TointeractwithaJMSprovider,itisfirstnecessarytocreateaconnectionbetweenaclient program and the provider. This is created through a connection factory (a service responsible for creatingconnections with the required properties). The resultant connection is a logical channel betweentheclientandprovider;theunderlyingimplementationmay,forexample,mapontoa TCP/IPsocketifimplementedovertheInternet.Notethattwotypesofconnectioncanbe established, a TopicConnectionor a QueueConnection, thus enforcing a clear separation between the two modes of operation within given connections. Connections can be used to create one or moresessionsasessionisaseriesofoperationsinvolvingthecreation,productionand consumptionofmessagesrelatedtoalogicaltask.Theresultantsessionobjectalsosupports operationstocreatetransactions,supportingall-or-nothingexecutionofaseriesofoperations. Thereisacleardistinctionbetweentopicsessionsandqueuesessionsinthata TopicConnectioncan support one or more topic sessions and a QueueConnectioncan support one or more queue sessions, but it is not possible to mix session styles in aconnection. The session objectiscentraltotheoperationofJMS,supportingmethodsforthecreationofmessages, message producers and message consumers. InJMS,amessageconsistsofthreeparts:aheader,asetofpropertiesandthebodyofthe message.Theheadercontainsalltheinformationneededtoidentifyandroutethemessage. Propertiesarealluser-definedandcanbeusedtoassociateotherapplication-specificmetadata Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 59 elementswithamessage.Forexample,ifimplementingacontext-awaresystem,theproperties can be used to express additional context associated with the message, including a location field. In JMS, the body can be any one of a text message, a byte stream, a serialized Java object, stream of primitive Java values or a more structured set of name/value pairs. Getting Started with OpenJMS OpenJMSisanopensourceimplementationofSunMicrosystems'sJavaMessageServiceAPI 1.1 Specification. Downloads & I nstallation BeforeyoucanstartusingOpenJMS,youneedtodownloadtheOpenJMSdistributiontoyour system. OpenJMS releases are available in both install and source archives from the SourceForge downloadpage.(http://openjms.sourceforge.net/downloads.html)Forconvenience,theyare providedinzipandtar/gzipformats.TheseincludetheOpenJMSserver,theOpenJMSclient JARS,3rdpartyJARSrequiredbytheclientandserver,thecompletesetofdocumentation, scripts to run the server on Windows and UNIX and sample programs. After you have downloaded a distribution, you need to install this on your system before you can start using OpenJMS (http://openjms.sourceforge.net/adminguide/install.html).OpenJMS will run on any platform where there is a suitable Java 2 runtime environment. Then you need to unpack install archive. The install archive contains everything required to run OpenJMS on your system. The archive has a single top-level directory named openjms-0.7.7-beta-1 with all the OpenJMS related files beneath that. Installarchiveswitha.zipextensioncanbeunpackedusingwinzip,orthejartool(distributed with the Java 2 SDK). E.g.:jarxvf openjms-0.7.7-beta-1.zip Install archives with a .tar.gz extension can be unpacked with gzip and tar. E.g.: gzip -cd openjms-0.7.7-beta-1.tar.gz | tar xvf - The OpenJMS server uses the following Environment variables. JAVA_HOME Java Development Kit installation directory. OPENJMS_HOME OpenJMS installation directory. Running OpenJ MS Once you've installed OpenJMS, you need to start the OpenJMSserver.To start the OpenJMS server, open a command prompt and type: cd %OPENJMS_HOME%\bin startup(I n Windows) cd $OPENJMS_HOME/bin startup.sh(I n UNI X) Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 60 Executing Programs OpenJMSisdistributedwithanumberofexampleprogramsthatdemonstratewritingsimple applications using JMS. Building the examples Helper scripts are provided to compile the examples with the appropriate class path. To run these, open a command prompt and type: cd %OPENJMS_HOME%\examples\basic build(I n Windows) cd $OPENJMS_HOME/examples/basic build.sh(I n UNI X) Running the examples Helper scripts are also provided to run the examples. To run these, open a command prompt and type:run(I n Windows) run.sh (I n UNI X) Example Code Sender.java importjavax.jms.*; importjavax.naming.*; public class Sender { public static void main(String[] args) { Context context = null; ConnectionFactory factory = null; Connection connection = null; String factoryName = "ConnectionFactory"; String destName = null; Destination dest = null; int count = 1; Session session = null; MessageProducer sender = null; String text = "Message "; try { // create the JNDI initial context. context = new InitialContext(); // look up the ConnectionFactory factory = (ConnectionFactory) context.lookup(factoryName); Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 61 // look up the Destination dest = (Destination) context.lookup(destName); // create the connection connection = factory.createConnection(); // create the session session = connection.createSession( false, Session.AUTO_ACKNOWLEDGE); // create the sender sender = session.createProducer(dest); // start the connection, to enable message sends connection.start(); for (int i = 0; i < count; ++i) { TextMessage message = session.createTextMessage(); message.setText(text + (i + 1)); sender.send(message); System.out.println("Sent: " + message.getText()); } } catch (JMSException exception) { exception.printStackTrace(); } catch (NamingException exception) { exception.printStackTrace(); } finally { // close the context if (context != null) { try { context.close(); } catch (NamingException exception) { exception.printStackTrace(); } } // close the connection if (connection != null) { try { connection.close(); } catch (JMSException exception) { exception.printStackTrace(); } } } } } Receiver.java Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 62 importjavax.jms.*; importjavax.naming.*; public class Receiver { public static void main(String[] args) { Context context = null; ConnectionFactory factory = null; Connection connection = null; String factoryName = "ConnectionFactory"; String destName = null; Destination dest = null; int count = 1; Session session = null; MessageConsumer receiver = null; try { // create the JNDI initial context context = new InitialContext(); // look up the ConnectionFactory factory = (ConnectionFactory) context.lookup(factoryName); // look up the Destination dest = (Destination) context.lookup(destName); // create the connection connection = factory.createConnection(); // create the session session = connection.createSession( false, Session.AUTO_ACKNOWLEDGE); // create the receiver receiver = session.createConsumer(dest); // start the connection, to enable message receipt connection.start(); for (int i = 0; i < count; ++i) { Message message = receiver.receive(); if (message instanceofTextMessage) { TextMessage text = (TextMessage) message; System.out.println("Received: " + text.getText()); } else if (message != null) { System.out.println("Received non text message"); } } } catch (JMSException exception) { Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 63 exception.printStackTrace(); } catch (NamingException exception) { exception.printStackTrace(); } finally { // close the context if (context != null) { try { context.close(); } catch (NamingException exception) { exception.printStackTrace(); } } // close the connection if (connection != null) { try { connection.close(); } catch (JMSException exception) { exception.printStackTrace(); } } } } } Exercises Q.1) Explain the basic building blocks of JMS API Programming Model. Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 64 Q.2) Give the step by step flow of example programs discussed in this lab session. Introduction to Distributed Computer SystemsLab Session 10 NED University of Engineering & Technology Department of Computer & I nformation Systems Engineering 65