2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6 Design of Distributed Software Distributed Software Technologies SUN Remote Procedure Call (RPC) JAVA Remote Method Invocation (RMI) Common Object Request Broker Architecture (CORBA) Web Centric Architecture Servlets Java Server Pages (JSP) Enterprise Java Beans (EJB) Web Services .Net Remoting Design of Distributed Software 2 Schema ODS ODS - Ontwerp van geDistribueerde Software Week 1 - 23/09 VM Intro (Bart) Week 2 - 30/09 VM Vervolg intro + RMI Hfdst2 1.-4. (Bart) Week 3 - 07/10 VM Hfstk 3 - part 1 (Filip) Week 4 - 14/10 VM Hfstk 3 - part 2 (Filip) Lab Sessie 1 CORBA/RMI * Week 5 - 21/10 VM Hfstk 4 (Bart) Lab Sessie 2 Web Centric * Week 6 - 28/10 VM Hfstk 5 (Bart) Lab Sessie 3 Web Services * Week 7 - 04/11 VM Hfstk 6+9 (Filip) Project Sessie 1 * Week 8 - 11/11 = verlof //////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Week 9 - 18/11 VM Hfstk 7+8 (Bart) Project Sessie 2 * Week 10 - 25/11 Project Sessie 3 (groep A) * Project Sessie 3 (groep B) * Week 11 - 02/12 VM Hfdstk 10 (Filip) , Week 12 - 09/12 , Feedback Design of Distributed Software NM Vervolg Hfdst 2 (Filip) (Aud. Zuiderpoort) 3 2.5 CORBA : Common Object Request Broker Architecture Design of Distributed Software 2.5 Outline Introduction + Motivation Corba Framework Basic Architecture Corba Object Model Corba Object Refs Basic Corba Example Corba Implementations Advanced Architecture Portable Object Adapter Extended Corba Example Design of Distributed Software 5 Situating CORBA Socket Interface: no concept of methods, objects no services: Binding service, Activation Service, Persistent object storage service, Object location service, Transaction service, Event service support for multiple programming languages JAVA RMI/ C RPC concept of methods, objects services: Binding service, Activation Service, “light” Persistent object storage service single programming language Design of Distributed Software 6 CORBA: Basic Idea Need for middleware that allows applications to communicate irrespective of their programming language and that offers all required services Recognized by OMG in 1989 OMG = Object Management Group Industry Group of over 800 participants Their goal : design middleware that allows applications to communicate irrespective of (i) their programming language, (ii) their hardware and software platforms and (iii) the networks they communicate over. Design of Distributed Software 7 CORBA ORB OMG introduced ORB ORB = Object Request Broker Software component which helps a client to invoke a method on an object Timeline : Design of Distributed Software 8 CORBA framework components IDL = Interface Definition Language CORBA Architecture GIOP = General Inter-Orb protocol CDR = Common Data Representation Object Reference Definition ORB Core, Object Adapter, Skeletons, Client stubs/proxies, Implementation repository, Interface repository, Dynamic Invocation Interface, Dynamic Skeleton Interface IOR = Interoperable Object Reference CORBA Services Naming, Event, Notification, Security, Transaction, Concurrency, Trading Design of Distributed Software 9 RMI : architecture a proxy_b Remote Ref. Mod. communication client • proxy • 1 proxy per remote object • local representative of remote object • implements all methods of remote interface • handles (un)marshalling Remote Ref Module : •remote object reference table Design Distributed Software • tableof of local proxies dispatcher skeleton b Remote Ref. Mod. communication server • dispatcher • typically 1 per class • identify message to invoke in skeleton • skeleton • typically 1 per class • (un)marshalling • invokes method on remote object • sends reply 10 CORBA : architecture a proxy_b dispatcher Object Adapter ORB Core client • ORB Core • cfr Communication Module • Provides interface: • start/stop ORB • convert between remote objects and strings • provide argument lists for requests using dynamic invocation Design of Distributed Software skeleton b ORB Core server • Object Adapter • Remote Ref + Dispatcher • creates remote object references for CORBA objects • dispatches each invocation to the appropriate servant • activates objects • Portable Object Adapters = POAs11 CORBA architecture (2) Skeletons generated by IDL compiler remote method invocations are dispatched via appropriate skeleton to a particular servant unmarshals the arguments marshals exceptions and results Client Stubs/proxies generated by IDL compiler marshals the arguments unmarhals exceptions and results Design of Distributed Software 12 CORBA RMI : Object Model CORBA’s object model : A B C D E Differences with Java RMI : Clients are not necessarily objects CORBA object: implements an IDL interface has a remote object reference able to respond to invocations of methods on its IDL interface No class objects in CORBA Data structures of various types and complexity can be passed as arguments Design of Distributed Software 13 CORBA Objects data A Client Method 1 Method 2 Method 3 CORBA Object Design of Distributed Software 14 CORBA IDL interface example #ifndef __ECHO_IDL__ #define __ECHO_IDL__ echo.idl : /** * The Echo interface which is basically an interface that contains an echo operation and an accompanying operation. * @author AT&T omniORB, adapted by Filip De Turck * @version $Revision: 1.6 $, $Date: 2001/06/26 00:26:46 $ **/ interface echo { /** * Echoes the string received * @param mesg The received string which has to be echoed * @return The echoed string, which has to be <U>freed by the caller</U> **/ string echoString(in string mesg); /** * @return The number of times the <code> echoString </code> operation is called **/ long }; times_called(); Design of Distributed Software #endif 15 CORBA RMI : IDL CORBA IDL IDL interface specifies a name and a set of methods that clients can request Parameters and results: in, out, inout keywords Passing CORBA objects, primitive and constructed types Type Object: common supertype of all IDL interface types Exceptions: defined in interfaces and thrown by their methods Invocation semantics: at-most-once maybe semantics by oneway keyword Design of Distributed Software 16 CORBA RMI : pseudo objects CORBA implementations provide some interfaces to the functionality of the ORB pseudo objects: Cannot be passed as arguments IDL interface Implemented as libraries Example: ORB interface represents the functionality that programmers need to access: init method : to initialize the ORB connect method : to register CORBA objects with the ORB shutdown method : to stop CORBA objects conversion between remote object references and strings Design of Distributed Software 17 CORBA client and server example IDL compiler : *.idl files IDL compiler (idlj) echo.idl $ idlj -fall –oldImplBase echo.idl Design of Distributed Software Java Interface files echo.java Server Skeletons _echoImplBase.java Proxy Classes or Client Stubs _echoStub.java Java classes for structs Helper and Holder classes echoHelper.java 18 Java interface file /** * echo.java . * Generated by the IDL-to-Java compiler * from echo.idl */ public interface echo extends org.omg.CORBA.Object { public String echoString(String mesg); public int times_called(); } // interface Echo Design of Distributed Software 19 Servant Class Implementation import org.omg.CORBA.*; class echoServant extends _echoImplBase { private ORB theORB; private int counter; public echoServant(ORB orb) { theOrb = orb; counter = 0; } public String echoString(String mesg) { counter++; String p = mesg; return p; } public int times_called() { return counter; } } Design of Distributed Software 20 Servant Classes Extends the corresponding skeleton class Implements the interface methods Uses the method signatures defined in the equivalent Java interface ORB private attribute: to connect new CORBA objects to the ORB (connect method) or shutdown objects (shutdown method) Design of Distributed Software 21 Server Class Implementation import org.omg.CORBA.*; public class echoServer { public static void main(String args[]) throws org.omg.CORBA.UserException { try{ java.util.Properties props = System.getProperties(); ORB orb = ORB.init(args, props); echoServant echoRef = new echoServant(orb); orb.connect(echoRef); System.out.println(“echoServer ready and waiting ..."); orb.run(); } catch (Exception e) { System.err.println("ERROR: " + e); e.printStackTrace(System.out); } System.out.println(“Echo Server Exiting..."); } //main } // class Design of Distributed Software 22 CORBA server Java class with Main method Creates and initializes the ORB Creates an instance of Servant class Registers it to the ORB (through the connect method) Waits for incoming client requests Design of Distributed Software 23 Client Implementation import org.omg.CORBA.*; public class echoClient { public static void main(String args[]) java.util.Properties props = System.getProperties(); org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, props); if (args.length == 0) { System.err.println("usage: java echoClient <object reference>\n"); System.exit(1);} try { org.omg.CORBA.Object obj = orb.string_to_object(args[0]); if (obj==null) { System.err.println("Got a nil reference.\n"); System.exit(1);} Echo echoRef = echoHelper.narrow(obj); String src = "Hello!"; String answer = echoRef.echoString(src); System.out.println("I said:\""+src+"\"."+ " The Object said:\""+answer+"\“."); System.out.println("The function echoString on the object is called already "+ echoRef.times_called()+" time(s)"); } catch(Exception ex) { System.err.println("Caught an exception!!.\n"); } orb.destroy(); System.exit(0); } //mainDesign of Distributed Software } // class 24 Client Program Creates and initializes the ORB Narrow method to cast Object to particular required type Invokes the methods Catch CORBA System exceptions Objects cannot be passed by value in CORBA Design of Distributed Software 25 Running the server and client Start orbd : Start the Echo server : UNIX command shell : $ orbd MS-DOS system prompt : start orbd UNIX command shell : $ java echoServer MS-DOS system prompt : start java echoServer Result: echoServer ready and waiting ... Run the client application : $ java echoClient ior_server ResuIt: I said: “Hello!“. The Object said: “Hello!“. Design of Distributed Software 26 Chapter Outline Introduction + Motivation Corba Framework Basic Architecture Corba Object Model Corba Object Refs Basic Corba Example Corba Implementations Advanced Architecture Portable Object Adapter Extended Corba Example Design of Distributed Software 27 CORBA implementations Interesting URLs : http://cmeerw.org/freeorbwatch http://dmoz.org/Computers/Programming/ Component_Frameworks/CORBA/ Object_Request_Brokers/ http://java.sun.com/developer/ onlineTraining/corba/corba.html http://java.sun.com/j2se/1.5.0/docs/ guide/idl/index.html Design of Distributed Software 28 Portable Object Adapter Object dispatcher Adapter skeleton b ORB Core object adapter : connects a request using an object reference with the proper code to service that request server Portable Object Adapter (POA): Allow programmers to construct object implementations that are portable between different ORB products. Allow a single servant to support multiple object identities simultaneously. Design of Distributed Software 29 Example: Echo Servant with POA import org.omg.CORBA.*; import org.omg.PortableServer.POA; class echoServant extends echoPOA { private ORB theOrb; private int counter; public echoServant(ORB orb) { theOrb = orb; counter = 0; } public String echoString(String mesg) { counter++; String p = mesg; return p; } public int times_called() { return counter; } } Design of Distributed Software 30 Example: Echo Server with POA import org.omg.CORBA.*; Import org.omg.PortableServer.*; public class echoServer { public static void main(String args[]) throws org.omg.CORBA.UserException { try{ // create and initialize the ORB ORB orb = ORB.init(args, null); // get reference to rootpoa POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA")); // create servant and register it with the ORB echoServant eS = new echoServant(orb); //activate the server object rootpoa.activate(echoServantRef); // get and narrow object reference from the servant org.omg.CORBA.Object ref = rootpoa.servant_to_reference(eS); echo echoRef = echoHelper.narrow(ref); // wait for invocations from clients orb.run(); } catch (Exception e) { System.err.println("ERROR: " + e); e.printStackTrace(System.out); } System.out.println(“Echo Server Exiting..."); } //main Design of Distributed Software } // class 31 Server Implementation with POA 1. Get the root POA org.omg.CORBA.Object obj = orb.resolve_initial_references("RootPOA"); POA rootpoa = POAHelper.narrow(obj); 2. Create the servant instance echoServant echoServantRef = new echoServant(orb); 3. Activate the server object rootpoa.activate(echoServantRef); 4. Create the object reference from the POA org.omg.CORBA.Object ref = rootpoa.servant_to_reference(echoServantRef); 5. Narrow the object reference echo echoRef = echoHelper.narrow(ref); 6. Wait for incoming requests from clients orb.run() Design of Distributed Software 32 Interface Definition Language Additional keywords (compared to C++): interface, any, attribute, in, out, inout, readonly, raises module : group interfaces and idl types in logical units C++ preprocessing capabilities Design of Distributed Software 33 Interface Definition Language (2) Attributes IDL types: short, long, unsigned short, usigned long, float, double, char, boolean, octet, any const keyword Object = common supertype arrays or sequences in arguments : typedef ! cfr public class fields in Java readonly : only getter method is provided Inheritance: multiple inheritance is allowed scoped names to make distinction between types Design of Distributed Software 34 More advanced IDL example: Whiteboard.idl struct Rectangle{ long width; long height; long x; long y; } ; struct GraphicalObject { string type; Rectangle enclosing; boolean isFilled; }; interface Shape { long getVersion() ; GraphicalObject getAllState() ; // returns state of the GraphicalObject }; typedef sequence <Shape, 100> All; interface ShapeList { exception FullException{ }; Shape newShape(in GraphicalObject g) raises (FullException); All allShapes(); // returns sequence of remote object references long getVersion() ; }; Design of Distributed Software • 35 IDL module Modules allow interfaces and associated definitions to be grouped. A module defines a naming scope. module Whiteboard { struct Rectangle{ ...} ; struct GraphicalObject { ...}; interface Shape { ...}; typedef sequence <Shape, 100> All; interface ShapeList { ...}; }; Design of Distributed Software 36 2.6 Invocations in JEE Architecture 1. 2. 3. 4. 5. 6. 7. Introduction Servlets Java Server Pages Java Server Faces (JSF) Apache Struts Invocation of Enterprise Java Beans (EJB) Ajax Design of Distributed Software Web centric architectures 1. Introduction HTTP request webclient webserver HTTP response Thin client : • web browser • plug-ins Advantages • ubiquitous and uniform client • no network blockages (firewalls) for HTTP (port 80) • huge user base Design of Distributed Software 38 Protocol messages : HTTP 1. Introduction Application level message formats and behavior Request Response • GET (data encoded in URL) • POST (data encoded in message) • header • requested content (URL) • HTTP version • response types accepted (MIME, language) • client browser • connection type • POST • content of request • content length • REPLY • header • status (success/failure) • response data + MIME type (Multipurpose Internet Mail Extensions) Stateless protocol • 1 transaction for each request/response pair • each request/response pair INDEPENDENT of others Design of Distributed Software 39 Addressing resources : URL 1. Introduction <protocol>://<hostname>:<port>/<fully qualified pathname>?<parameters> <protocol> : http, https, ftp, telnet, … <hostname> : IP-address or DNS-name <port> : port for webserver (default : http : 80, https: 343) <fully qualified pathname> : directory + file name (default index.html) <parameters> : normally used to specify (name, value)-pairs ? : separates resource name from parameters + : represents space & : separate (name,value) pairs = : binds value to name % : escape character followed by 2 hex-symbols representing ASCII value elections! e.g. http://www.spy.cia.com:80/reports/interest?subject=elections%21 Design of Distributed Software 40 Standard interaction 1. Introduction Retrieving a (HTML) document HTTP GET webclient webserver HTTP REPLY Typical interactions 1. Connect : client opens connection with server 2. Request : client sends message to identify resource/service 3. Response : server sends message to respond to request 4. Disconnect : close client-server connection Design of Distributed Software 41 1. Introduction Dynamic content : CGI • Common Gateway Interface • URL • specifies (small) program • gives input through URL-parameters • program generates html-output (or output for plug in) HTTP POST webclient HTTP REPLY webserver INVOKE CGI-program • Performance/resource issues • new separate process for each request • programs often in scripting languages (e.g. Perl) • resources (e.g. database connections) created/destroyed per request Design of Distributed Software 42 Dynamic content : HTML for CGI 1. Introduction HTML <FORM>-tag • METHOD-field : specifies HTTP message type • ACTION-field : specifies URL (without parameters) • parameters specified in subsequent INPUT fields <html> <head> <title> Personal ID </title> </head> <body> <FORM METHOD="GET" ACTION="http://java.sun.com/prog/enter"> <P>Enter first name <INPUT NAME="first"></INPUT></P> <P>Enter family name <INPUT NAME="family"></INPUT></P> <INPUT TYPE="submit“ VALUE=“Submit Query"> </FORM> </body> http://java.sun.com/prog/enter?first=John+F.&family=Kennedy </html> Design of Distributed Software 43 1. Introduction Servlets and JSP • Plug-in object at server side • Runs separate thread per request • Shares resources with other servlets • Servlet life cycle managed by container process (single process, single JVM) : Created/destroyed/activated/passivated HTTP POST webclient HTTP REPLY webserver INVOKE webclient Servlet Container Design of Distributed Software 44 1. Introduction Servlets and JSP • Servlet disadvantage : • pages contain static + dynamic data • static data created dynamically -> not optimal • Solution • mix static and dynamic code in single webpage • compile webpage to extract servlets and static portions • configure webserver to • automatically invoke servlets to create dynamic content • merge dynamic and static content to response to client JSP : Java Server Page passive JSP compiler HTML code active passive Design of Distributed Software Servlet class Actually : JSP = Servlet 45 1. Introduction EJB • Server side component technology to code application logic • model business logic • model business objects (“database record”) Web tier webclient webserver Servlet Engine Application client Design of Distributed Software Persistent Storage tier Entreprise Systems Tier Application logic Client tier Business tier Middle Tier 46 EJB 1. Introduction • Session beans • Transient, DO NOT survive server shutdown • Associated with ONE client (at any given time) Stateless session beans • no state between successive invocations Stateful session beans • state info kept consistent between invocations • Entity beans • Persistent, DO survive server shutdown • State persists method calls/server shutdown • Can be shared between multiple clients Container Managed Persistence (CMP) Bean Managed Persistence (BMP) Design of Distributed Software 47 Web Centric Architecture Client Webserver Application Server 1. Introduction Database system Web container webserver applet applet browser EJB container Servlet JSP EJB Web container services • component life cycle management • handle communication with webserver HTTP <-> servlet • session tracking Design of Distributed Software EJB container services • component life cycle management • transaction service • persistence service • security handling • resource pooling 48 Servlet life cycle 2. Servlets If webcontainer receives request for non-instantiated servlet 1. Load Servlet class 2. Instantiate object of Servlet class 3. Initialize Servlet -> call init() method 4. Invoke service()-method to handle request 5. Handle any new requests by invoking service() 6. If idle-time > timeout or request by admin Remove servlet from webcontainer -> call destroy() method (clean up) Design of Distributed Software 49 2. Servlets Servlet life cycle Application Server Request webserver Response ServletContext Servlet Servlet Servlet Servlet Web container • Single Servlet instance handles all requests for given Servlet class (exception : SingleThreadModel) • Servlet invoked per request • Servlet state does not survive requests • “long lived” storage : - through ServletContext object (e.g. Session persistence) - in database (persistent storage) GenericServlet : protocol neutral Servlet HttpServlet : has access to HTTP specifics Design of Distributed Software 50 Servlet types 2. Servlets GenericServlet abstract public void service(ServletRequest req,ServletResponse res) throws ServletException, IOException • method called for each request • method not synchronized by default ! HttpServlet Inherits from GenericServlet Overrides service-method - automatically dispatches to HTTP-message related methods public void doGet(HttpServetRequest req,HttpServletResponse res) throws ServletException, IOException public void doPost(HttpServetRequest req,HttpServletResponse res) throws ServletException, IOException Design of Distributed Software 51 A GenericServlet 2. Servlets import java.io.*; import javax.servlet.*; public class RandomGenericServlet extends GenericServlet { public void service(ServletRequest req,ServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("<HTML><HEAD><TITLE>RandomGenericServlet Output </TITLE></HEAD>"); out.println("<BODY> Your random number is : "+ ((int)(Math.random()*10))+"</BODY>"); out.println("</HTML>"); out.close(); } } • Override service()-method • Set MIME-content type BEFORE writing to Response-object Design of Distributed Software 52 An HttpServlet 2. Servlets import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class RandomHttpServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("<HTML><HEAD><TITLE>RandomGenericServlet Output </TITLE></HEAD>"); out.println("<BODY> Your random number is : "+ ((int)(Math.random()*10))+"</BODY>"); out.println("</HTML>"); out.close(); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { doGet(req,res); } • No service-method } • Override doXXX()-methods XXX=Get,Post,Put,Trace,Delete,Options Design of Distributed Software 53 Servlet framework methods 2. Servlets Automatically called methods public void init(ServletConfig config) • called by container when Servlet is loaded • if overriden : first statement should be super.init(config) • calls init() method (better to override init() !) public void init() • called by init(ServletConfig) • code non-standard initialization here (e.g. Open database connection) public void destroy() • called by container when Servlet unloaded or timeout • locate clean-up code here (close file handles, database connections, sockets, etc.) • DANGER : make this method thread-safe !!! public abstract void service(ServletRequest req, ServletResponse res) • called when request received • overriden in HttpServlet class to dispatch to HTTP-related methods Convenience method public void log(String log) : write (error)message to container specific log file Design of Distributed Software 54 2. Servlets Servlet environment ServletContext I ServletRequest Servlet ServletResponse Servlet Servlet Web container Servlet XML deployment Description Application I XML deployment Description Application II ServletContext II Servlet configuration - static info used for deploying the Servlet - initialisation parameters Servlet context - object allowing to interact with web application - used to track sessions ! Servlet request/response - request holds input parameters for Servlet Design of Distributed Software 55 ServletConfig 2. Servlets Servlet config object passes servlet-specific info (NO request specific info) public ServletConfig getServletConfig() public String getServletInfo() info on author, version, ... (override to supply info) public String getServletName() returns Servlet instance name (as known to container) public String getInitParameter(String parName) ALWAYS type String (Servlet should parse) public Enumeration getInitParametersNames() returns Enumeration of names for all known init parameters init parameters - parameter (name,value)-pairs stored in war-file - initialized when servlet is loaded - setting init-parameters is server dependent Design of Distributed Software 56 ServletConfig 2. Servlets Intialize database connection public void init() { String dbHost=getInitParameter(“host”); int port=Integer.parseInt(getInitParameter(“dbport”)); String user=getInitParameter(“user”); String pass=getInitiParameter(“password”); // initialize connection to database } Show all init-parameters public String getServletInfo() { String res=“”; Enumeration e=getInitParameterNames(); while(e.hasMoreElements()) res+=(String)(enum.nextElement()); return res; } Design of Distributed Software 57 2. Servlets ServletContext Servlet context object serves as interface to container One context per web application If distributed web application : one context per JVM per web application public ServletContext getServletContext() public ServletContext getServletContext(String uri) returns context object for uri specified servlet public String getInitParameter(String parName) public Enumeration getInitParametersNames() public RequestDispatcher getRequestDispatcher(String path) returns RequestDispatcher for given path public RequestDispatcher getNamedDispatcher(String name) returns RequestDispatcher for referred servlet public Object getAttribute(String name) return Object with given name public Enumeration getAttributeNames() return names for all context attributes public void removeAttribute(String name) removes named attribute from context public void setAttribute(String name,Object obj) add attribute obj, name it “name” Design of Distributed Software Same as for config object, But for CONTEXT wide init Parameters (shared between servlets) 58 ServletRequest 2. Servlets - request holds input parameters for Servlet - created by container and handed to service()-method Same as for context object, public Object getAttribute(String name) But for Request Scope public Enumeration getAttributeNames() Attributes public void removeAttribute(String name) public void setAttribute(String name,Object obj) public String getServerName() public int getServerPort() public String getRemoteAddress() public String getRemoteHoser() public BufferedReader getReader() // buffered char reader public ServletInputStream getInputStream() // binary reader public String getProtocol() public int getContentLength() public String getParameter() Request encoded parameters -request body – POST public String[] getParameterValues() -URL encoded - GET public Enumeration getParameterNames() public Map getParameters() // name – value map Design of Distributed Software 59 2. Servlets HttpServletRequest public String getHeader(String name) public Enumeration getHeaders(String name) public Enumeration getHeaderNames() public String getMethod() public Cookie[] getCookies() public HttpSession getSession() public HttpSession getSession(boolean create) Session management http://somehost:80/directory/servlet/pathinfo?query public String getPathInfo() public String getQueryString() Design of Distributed Software 60 HttpServletRequest : headers User-Agent Referer Host Accept Accept-Charset Accept-encoding Accept-Language Authorization Connection Pragma 2. Servlets information on client side software URL from which Servlet is accessed Internet host and port of requested resource comma-separated list of MIME-types accepted by the client character set accepted by client accepted content-encoding (mainly compression) e.g. “compress”, “deflate”, “gzip” preferred language by client software (e.g. “en”, “de”,”en-us”,...) used to authorize user (server specific) options for this connection (“close”, “keep-alive”) destined for intermediary (e.g. “no-cache” -> no proxy caching) Design of Distributed Software 61 HttpServletRequest : headers 2. Servlets import java.util.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HeaderServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("<HTML><HEAD><TITLE>HeaderServlet Output</TITLE></HEAD>"); Enumeration names=req.getHeaderNames(); out.println("<H1>Request Headers</H1>"); while(names.hasMoreElements()) { String headerName=(String)names.nextElement(); String headerValue=req.getHeader(headerName); out.println("<B>"+headerName+" : </B>"+headerValue+"<BR>"); } out.println("</HTML>"); out.close(); } public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { doGet(req,res); } } Design of Distributed Software 62 HttpServletRequest : headers 2. Servlets View Source <HTML><HEAD><TITLE>HeaderServlet Output</TITLE></HEAD> <H1>Request Headers</H1> <B>accept : </B>image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*<BR> <B>accept-language : </B>nl-be<BR> <B>accept-encoding : </B>gzip, deflate<BR> <B>user-agent : </B>Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)<BR> <B>host : </B>localhost:8080<BR> <B>connection : </B>Keep-Alive<BR> </HTML> Design of Distributed Software 63 HTML parameter encoding 2. Servlets In FORM-tag Field type Value Example text hidden checkbox String or null(empty) String or null(empty) checked : String either “on”,”true”,”yes” OR assigned tag value unchecked : null String String or null String or null (empty) name=Kennedy sessionID=12234 box=on box=John radio select option textarea Design of Distributed Software name=John car=Fiat text=this is some sample text 64 Retrieving parameters 2. Servlets <html><head><title> Personal ID </title></head> <body> <FORM METHOD="GET" ACTION="http://localhost:8080/process/input"> <P>Enter name <INPUT TYPE="text" NAME="name" SIZE=20></INPUT></P> <P>Occupation :<BR> <INPUT TYPE="checkbox" NAME="USpres">US president<BR> <INPUT TYPE="checkbox" NAME="NMBS">NMBS manager<BR> <INPUT TYPE="checkbox" NAME="prime">Belgian Prime Minister<BR> </P> <P>Sex : <BR> <INPUT TYPE="radio" NAME="sex" VALUE="male" CHECKED>male<BR> <INPUT TYPE="radio" NAME="sex" VALUE="female">female<BR> <P>Select your favourite car : <BR> <SELECT NAME="cars"> <OPTION VALUE="volvo">Volvo <OPTION VALUE="saab">Saab <OPTION VALUE="fiat">Fiat • input to be processed on http://localhost:8080/process/input <OPTION VALUE="audi">Audi • using doGet()-method </select> • parameter names : name, USpres, NMBS, prime, ... </P> <P>Your comments :<BR> <TEXTAREA NAME="comments" ROWS="5" COLS="30"> </TEXTAREA> </P> <INPUT TYPE="submit" VALUE="Submit ID card"> </FORM> </body> Design of Distributed Software 65 </html> Retrieving parameters 2. Servlets Browser output Design of Distributed Software 66 Retrieving parameters 2. Servlets import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ProcessInput extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("<HTML><HEAD><TITLE>Echo back to confirm.</TITLE></HEAD>"); out.println("<BODY>"); out.println("You have entered following data :<BR>"); out.println("Your name : "+req.getParameter("name")+"<BR>"); out.print("Your occupations : "); if(req.getParameter("USpres")!=null) out.print("US president "); if(req.getParameter("NMBS")!=null) out.print("NMBS manager "); if(req.getParameter("prime")!=null) out.print("Belgian Prime Minister "); out.println("<BR>"); out.println("Your sex : "+req.getParameter("sex")+"<BR>"); out.println("Your favourite car : "+req.getParameter("cars")+"<BR>"); out.println("Your comments : "+req.getParameter("comments")+"<BR>"); out.println("</BODY>"); out.println("</HTML>"); out.close(); } } Design of Distributed Software 67 Retrieving parameters 2. Servlets Browser output Design of Distributed Software 68 ServletResponse 2. Servlets Webcontainer • retrieves ServletResponse object • translates to HTTP and manages connection public void setContentType(String type) • sets MIME-type of response (e.g. “text/html”) • MIME type MUST be set before generating output public void setContentLength(int len) public ServletOutputStream getServletOutputStream() // binary output public PrintWriter getWriter() // formatted character output public Enumeration getInitParameters() Design of Distributed Software 69 HttpServletResponse 2. Servlets public void addHeader(String name,String value) public void setHeader(String name,String value) public boolean containsHeader() public void addDateHeader(String name,long date) // ms since January 1, 1970 public void setDateHeader(String name,long date) // ms since January 1, 1970 public sendError(int http_statuscode) public sendError(int http_statuscode,String message) e.g. sendError(404,”Can not find this file here.”) public sendRedirect(String url) e.g. sendRedirect(http://newhost/index.html) public setStatus(int http_statuscode) e.g. setStatus(404) public void addCookie(Cookie c) Session management Design of Distributed Software 70 HttpServletResponse : headers Age Allow Content-Encoding Content-Language Content-Length Content-Type Date Expires Last-Modified Refresh Server WWW-Authenticate 2. Servlets time elapsed since response generated (control caching) list of supported http methods for requested document type of encoding used for (e.g. compressed) response natural language used for the response number of bytes of the document’s body MIME-type of response Current date and time (GMT) date and time (GMT) when content becomes stale (can not be cached any longer) date and time (GMT) since last update (used for cache control) number of seconds before document should be reloaded server info for authorization, server specific Design of Distributed Software 71 Servlet collaboration 2. Servlets Sharing data Within same application : use ServletContext attributes With another application/context ON SAME SERVER : • use database • use external object (on same or different server) • use ServletContext of other application ServletContext ownContext= getServletContext(); ServletContext otherContext=ownContext.getContext(“/otherapp/index.html”); Object parameter=otherContext.getAttribute(“foreignAttribute”); Sharing control Use RequestDispatcher to forward/include to component contents Design of Distributed Software 72 Servlet chaining / forwarding 2. Servlets • make sure all headers are set appropriately before forwarding requests • through RequestDispatcher-object Use getRequestDispatcher()-methods forward(ServletRequest request, ServletResponse response) -> forward request to other resource, hand off control -> response NOT committed to client ! include(ServletRequest request, ServletResponse response) -> include contents to response of this servlet, original servlet stays in control // … String destination=“/servlet/NewServlet”; RequestDispatcher dispatcher= req.getRequestDispatcher(destination); dispatcher.forward(req,res); // … Design of Distributed Software 73 Servlet forwarding : example 2. Servlets Check credentials Process input text ValidServlet forward valid invalid Known to webserver as “valid” HTML-input form Fields : name, password, text ProcessServlet Known to webserver as “process” Web application “forward” contains : • HTML-input form “index.html” • Servlet “valid” instance of class ValidServlet.class • Servlet “process” instance of class ProcessServlet.class forward.war Design of Distributed Software 74 Servlet forwarding : example <html> <head> <title> Forward </title> </head> 2. Servlets index.html <body> <FORM METHOD="GET" ACTION="http://localhost:8080/forward/valid"> <P>Enter user name <INPUT TYPE="text" NAME="user" SIZE=20></INPUT></P> <P>Password <INPUT TYPE="password" NAME="pass" SIZE=20></INPUT></P> <P>Enter text to send to database :<BR> <TEXTAREA NAME="text" ROWS="5" COLS="30"> </TEXTAREA> </P> <INPUT TYPE="submit" VALUE="Submit Text"> </FORM> </body> </html> Design of Distributed Software 75 Servlet forwarding : example 2. Servlets ValidServlet.java public class ValidServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { String user=req.getParameter("user"); String pass=req.getParameter("pass"); if(user.equals("user")&&pass.equals("secret")) { RequestDispatcher dispatcher=req.getRequestDispatcher("process"); dispatcher.forward(req,res); } else { res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("<HTML><HEAD><TITLE>Answer from ValidServlet.</TITLE></HEAD>"); out.println("<BODY>"); out.println("You failed to supply valid credentials.<BR>"); out.println("</BODY>"); out.println("</HTML>"); out.close(); } } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { doGet(req,res); } } Design of Distributed Software 76 Servlet forwarding : example 2. Servlets ProcessServlet.java public class ProcessServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { String text=req.getParameter("text"); res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("<HTML><HEAD><TITLE>Answer from ProcessServlet.</TITLE></HEAD>"); out.println("<BODY>"); out.println("Following text has been submitted :<BR>"+text); out.println("</BODY>"); out.println("</HTML>"); out.close(); } public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { doGet(req,res); } } Design of Distributed Software 77 3. JSP Java Server Pages • allows to use convenient syntax for static portions • JAVA-scriptlets to code dynamic parts • intuitive interaction with Java Beans components • jsp-file is compiled in single Servlet Application Server request ServletContext Deployed JSP/Servlet reply Servlet class JAVA-compiler Servlet Web container war-file Servlet source JSP-compiler JSP-file Design of Distributed Software 78 A Simple Example import java.io.*; import javax.servlet.*; 3. JSP Servlet version public class RandomGenericServlet extends GenericServlet { public void service(ServletRequest req,ServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("<HTML><HEAD><TITLE>Servlet Output </TITLE></HEAD>"); out.println("<BODY> Your random number is : "+ ((int)(Math.random()*10))+"</BODY>"); out.println("</HTML>"); out.close(); } <%@page contentType="text/html"%> } JSP-version <html> <head><title>JSP output</title></head> <body> Your random number is : <%=((int)(Math.random()*10))%> </body> </html> Design of Distributed Software 79 Object Scoping 3. JSP Recap from Servlets : Application scope all JSP-pages and resources sharing same ServletContext e.g. String myString=“example variable”; getServletContext.setAttribute(“example”,myString); Session scope all resources in current HttpSession e.g. HttpSession session=req.getSession(true); sess.setAttribute(“example”,myString); Request scope this request only e.g. req.setAttribute(“example”,myString); Page scope this page only (no servlet equivalent) (default for JSP) Design of Distributed Software 80 3. JSP Syntax Declarations application scope declarations • variables and methods • OUTSIDE servlet service()-method • syntax : <%! the declarations request scope declarations • variables local to service()-method • comes INSIDE servlet service()-method • syntax : same as scriptlets <% the declarations %> Scriptlet Piece of java-code for service()-method syntax : <% the java code %> public class TheServlet { public void service(…) { %> } } Escaping Literal sequence <\% %\> \’ \” Design of Distributed Software meaning <% %> ‘ (for single quote in single quoted attribute) “ (for double quote in double quoted attribute) 81 Syntax 3. JSP Expressions Dynamically generated output • evaluate Java-expression • apply toString() if necessary • send to JSP output stream (end hence ServletOutputStream) • syntax : <%= the java expression %> (no ; !) Comments HTML-comments • visible in browser (“view source”) • embedded scriptlets/expressions in HTML-comments are executed/evaluated • syntax : <!-the comment --> Java-comments • standard java-comment in scriptlets • do not appear in HTML-output • syntax : <% // the comment %> (or multi-line comment syntax) JSP-comments • ignored by the JSP-compiler (do not appear) • syntax : <%-the comment --> Design of Distributed Software 82 3. JSP Syntax Directives Messages to the JSP engine Syntax : <%@ directive attribute=“value” %> page Attributes contentType extends import info errorPage isErrorPage session meaning sets MIME-type of response <%@ page contentType=“text/html” %> specify superclass of JSP’s associated Servlet <%@ page extends=“com.SuperServlet” %> specify packages to import <%@ page import=“java.util.*” %> sets ServletInfo variable <%@ page info=“Hello Servlet echoes request” %> specify jsp to redirect in case of uncaught exception <%@ page errorPage=“ErrPage.jsp” %> indicate if this page is error page for other page, true or false <%@ page isErrorPage=“true” %> true or false : participate in session ? <%@ page session=“false” %> Design of Distributed Software 83 3. JSP Syntax include Include other file (jsp, html, textfile, …, in current jsp) • static include (at JSP-compile time) • includes interpreted in “cut and paste” fashion <%@ page include=“jspfiles/MyJSP.jsp” %> taglib Inclusion of Custom Tag Libraries Extension mechanism for JSPs Implicit objects Objects made available to JSP-page Name application config exception page request response session Design of Distributed Software meaning ServletContext ServletConfig Exception object (only for error pages) this HttpServletRequest HttpServletResponse HttpSession 84 3. JSP Syntax Actions Statement jsp:include meaning dynamic include of resource <jsp:include page=“myjsps/included.jsp” flush=“true” /> second attribute MUST be true forward request to other resource (specified as URL) <jsp:forward page=“other.jsp” /> must be resource of same application jsp:forward forwarding WITH parameters : <jsp:forward page=“other.jsp” > <jsp:param name=“parname” value=“parval”/> </jsp:forward> jsp:plugin include Applet using Java-plugin <jsp:plugin type=”applet” code=“myApplet.class” with=“100” height=“200” > <jsp:params> <jsp:param name=“car” value=“Volvo” /> </jsp:params> </jsp:plugin> Design of Distributed Software 85 Syntax 3. JSP Actions : interaction with JavaBeans Instantiating a Bean <jsp:usebean id=“beanInstanceName” scope=“the scope” beandetails /> Scope attribute : valid values “page” (default), “request”, “session”, “application” beandetails: attributes : class Bean class file (usually required) type dynamic typing (cast) beanName class file, can be expression If bean already exists with this name and scope, the bean is not re-instantiated Bean class MUST have no-arg public constructor ! <jsp:usebean id=“myBean” scope=“session” class=“MyBean.class” type=“Object.class”/> = Object myBean=(Object) new MyBean(); Design of Distributed Software 86 Syntax 3. JSP Actions : interaction with JavaBeans Bean properties <jsp:getProperty name=“beanInstanceName” property=“propertyname”/> Property value converted to String <jsp:setProperty name=“beanInstanceName” property=“propertyname” value=“propValue” /> <jsp:setProperty name=“beanInstanceName” property=“propertyname” param=“requestParameterName” /> How to transform requestParameter (always String) to BeanProperty ? • if PropertyEditor available : setAsText() used • primitives : valueOf(String) used <jsp:setProperty name=“beanInstanceName” property=“propertyname” /> -> sets property according to matching request parameter <jsp:setProperty name=“beanInstanceName” property=“*” /> -> sets all properties according to request parameters Design of Distributed Software 87 3. Application design Technologies Different technologies to execute code JSP Enterprise Java Beans Design of Distributed Software Servlet Database Stored procedures 88 Typical technology role Business Logic Database system JDBC Presentation 3. Application design JSP : intuitive graphical representation Servlet : execute business logic (e.g. data validation) Enterprise Java Beans : local storage Stored procedure (SQL) : optimize database access Design of Distributed Software 89 Java Server Faces (JSF) 4. Java Server Faces Java-based Web application framework Goal: simplify development of user interfaces for Java EE applications. The state of UI components is saved when the client requests a new page and then is restored when the request is returned. JSF uses JavaServer Pages (JSP) for its display technology. There is a server side event model (e.g. ActionListeners and ValueChangedListener). After compilation and deployment of the application, the clientserver interaction takes place the same way as with Servlets/JSP. http://java.sun.com/javaee/javaserverfaces/ http://java.sun.com/javaee/5/docs/tutorial/doc/bnaph.html Design of Distributed Software 90 Apache Struts 5. Apache Struts Open-source web application framework for developing Java EE web applications. It uses and extends the Java Servlet API to encourage developers to adopt a model-view-controller (MVC) architecture. Goal: to separate the model (application logic that interacts with a database) from the view (HTML pages presented to the client) and the controller (instance that passes information between view and model). Struts provides the controller (a servlet known as ActionServlet) and facilitates the writing of templates for the view or presentation layer (typically in JSP, but XML/XSLT is also supported). The web application programmer is responsible for writing the model code, and for creating a central configuration file struts-config.xml which binds together model, view and controller. After compilation and deployment of the application, the client-server interaction takes again place the same way as with Servlets/JSP. http://struts.apache.org/ http://struts.apache.org/2.0.11.2/docs/tutorials.html Design of Distributed Software 91 Invocation of EJBs 6. Invocation of EJBs Enterprise Java Beans are Java objects, run inside a JEE application server. The application server is responsible for the life cycle management of the objects. Enterprise Java Beans run inside the same application server can easily obtain a reference of each other and invoke methods. Remote clients (i.e. run outside the application server, either standalone or in another application server) can obtain a reference to an Enterprise Java Bean (through a JNDI service, as described in the next chapter) and invoke its methods. In terms of invocation, there is no distinction between session beans or entities. Design of Distributed Software 92 Ajax 7. Ajax AJAX = Asynchronous JavaScript and XML based on xHTML and CSS, the Document Object Model, XML and XSLT, the XMLHttpRequest object for asynchronous communication with the back-end server and JavaScript to bind everything together. JavaScript code can communicate directly with the server, through the JavaScript XMLHttpRequest object. This object allows to send or retrieve information to or from a server over HTTP. At the client side, JavaScript takes care of creating the XMLHttpRequest object, sending or retrieving information through it and processing the results. http://www.w3schools.com/ajax/ Design of Distributed Software 93