Lecture10

advertisement
CS441
CURRENT TOPICS IN
PROGRAMMING LANGUAGES
Lecture 10
George Koutsogiannakis/Summer 2011
1
Topics
• Java Server Pages.
• Distributed Objects.
• Frameworks for Distributed Objects
Architectures.
• Remote Method Invocation.
2
Java Server Pages (JSP)
• Used when there is more non java code embedded than
java code. Otherwise Servlets should be used (when the
code is mostly java).
• A JSP file contains some java code and some HTML or
DHTML or XML code.
• Therefore it is a mixture of scripts with Java code.
– The file has a .jsp extension.
– It is like script file. No compilation is needed.
3
Java Server Pages (JSP)
– It is similar in concept to Microsoft’ s approach to ASP (Active
Server Pages).
– It is preferable for static content although it offers the dynamic
capabilities of servlets.
4
Java Server Pages
• A JSP page services requests as a servlet.
• The web container translates the java code in the JSP file to servlet
code and compiles it automatically. The first time the JSP file is called.
– Any updates to the JSP file are recognized and the code gets recompiled.
– The conversation to a servlet is called the Translation stage.
– JSP files are located in the same directory level as HTML files and applets (under
the root context folder).
– Changes can be made in a JSP file like in a HTML file. It is not necessary to deploy
and redeploy the application!!
• To avoid the delay in having to update the corresponding servlet when changes are made
we can pre-compile the JSP into a servlet outside the web container.
• It can be done with a developing environment that supports this functionality
5
JSP TAGS
• JSP uses different types of tags to encapsulate Java code:
– Directive Tags:
• 3 types of directive tags:
page: used to define the attributes of the web application via keywords like:
language, contentType, import
include: used to specify an external file to be inserted.
taglib: used to specify a custom tag library to be used.
• <%@
% > is the symbol i.e.
<%@ page language=“java” contentType=“text/html” %> or
<%@ include file=“MyFile.html” %> or
<%@ forward file=“MyFile.class” %> or
<%@ taglib uri=“MyTagLib” %> or
<%@ page import=“ java.util.Vector” import =“java.text.DecimalFormat” %>
6
JSP TAGS
– Declaration Tags: used in expressions or scriptlets
• <%! %> i.e.
<%! int count; %> or
<%! Date today=new Date(); %>
– Expression Tags: used to specify Java expressions.
• <%=
%>
<%= price*(1+taxRate) %> or
<% ! today.getMonth() %>
– Scriptlets: used to denote blocks general Java code.
• <%
%>
<% total=0;
for(int i=0; i<=myarray.length-1; i++)
total+ = myarray[i];
%>
7
JSP TAGS
– Actions: used to perform various functions that extend the
standard capabilities of JSP i.e. using JavaBeans.
• <jsp: useBean id=“manager” class=“staff.Personel”
scope=“session” /> Notice the / .
<jsp:plugin
/> used to provide a browser specific
markup for activating an applet.
<jsp:setProperty
/> used to set properties of a JavaBean
<jsp:getProperty
/> used to obatian a JavaBean’s property
– Comments: used for commenting the code.
• <% -- enter the comment -- %> (notice the two dashes after and before %)
8
JSP Implicit Objects
• A number of Implicit Objects are made available by the
server to the JSP file (regardless if they are used or not).
• Implicit objects:
– pageContext: provides access to other objects within the web
application such as :
•
•
•
•
serveltContext: The servlets and JSP context object.
session: The session object for the client.
request: The request object that triggers the JSP file interpretation.
response: The response object returned by the JSP.
– application: allows access to the servlet context by invoking
getServletContext method
– config: allows acess to getRervletConfig method.
9
JSP Implicit Objects
– out: it represents the JspWriter object similar to obtaining the
PrintWriter in servlets ( PrintWriter out=response.getPrintWriter in
servlets--- you get this automatically in JSP).
– There are other implicit objects that are explained in the
Servlet/JSP API.
10
Unified Expression Language
• A new feature was added in JSP to accommodate Java Server Faces (to
be discussed later in the course).
– EL is the unified expression language which is a union of the tags used by
JSP and the tags understood by JSF (Java Server Faces).
– JSP has a life cycle that is based on a request and response concept.
– JSF features supports the UI component model MVC (Model View
Controller) which allows:
•
•
•
•
Conversion and validation of component data.
Propagation of component data to objects.
Handling of component events.
Components can b e JavaBeans or Enterprise Java Beans.
– JSF can present a client with its own custom presentation layer data.
11
Unified Expression Language
• Unified EL supports:
– Immediate evaluation of an expression: JSP engine evaluates the
expression and returns the result immediately when the page is first
rendered. Uses syntax
${ }
– Deferred evaluation of an expression: JSP engines waits unto an
event (s) take place before the final evaluation. Uses syntax
#{ }
12
Example of Simple JSP
•
<html>
<head>
<title> Display Server Time</title>
</head>
<body>
<p> Welcome to JSP:
<% @ page import=“java.util.Calendar” %>
<% Calendar now=Calendar.getInstance();
int hour=now.get(Calendar.HOUR_OF_DAY);
int minute=now.get(Calendar.MINUTE);
if(hour<12)
out.println(“Good Morning the time is:” + “ ”+hour+ “ “ + minute);
else
out.println(“It is past noon”); %>
</p> </body></html>
13
Example of Simple JSP
• The previous script can be saved as
some_name.jsp and be placed in the proper
web application folder of the web server.
• The JSP engine of the web server will
separate the java code from the rest of the
script, create a servlet out of that code and
compile it.
14
Another JSP Example
• In the following example we have a HTML table in some file i.e
myjsp.jsp . In the cell <td> of the table we display the date and time.
<table>
<tr><td>
<p>
<% java.util.Locals locate=request.getLocale();
java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.Long,
java.text.DateFormat.Long, locals);
%>
// output the date
<%>=dateFormat.format(new java.util.Date()) %>
</p></td></tr>
15
JSP calling Other Resources
• Notice that other resources can be called just like with
servlets.
– i.e You can have jsp code calling another jsp file or calling another
servlet .
• <jsp:forward>
– It is an Action that calls another resource
<jsp;forward page=“myanotherjsp.jsp”>
<jsp:param name=“date” value=“<%=new java.util.Date() %>” />
</jsp:forward>
Passes to resource myanotherjsp.jsp file the parameter name whose
value is a Date object.
16
JSP calling Other Resources
• Keep in mind that we can also use the <jsp:
include> Action.
• The difference between forward and include is the
same as in servlets.
– Forward has the called resource take over the response.
Does not return to the calling jsp
– Include transfers execution to the called resource and
returns to the calling jsp to finish and form the
response.
17
JSP Library files
• In addition to the servlet library classes there are specific
classes and interfaces libraries:
– javax.servlet.jsp
– javax.servlet.jsp.tagext
– The above classes and their super classes can be used to generate
custom tags
18
Custom Tag Libraries
• The jsp API allows the creation of custom tags.
• The functionality of the custom tags is defined in Java
classes that implement interface Tag (package
javax.servlet.jsp.tagext)
• A custom tag will encapsulate some functionality that we
want to make available to other programmers who possibly
don’t know Java. They can use our tag in their scripts.
• To create a custom tag we use more advanced concepts.
We will return to it later on in the course.
19
Distributed Objects and RMI
• In this section we want to introduce Remote
Method Invocation and some other Java
tools that allow the creation of Distributed
Systems.
20
Distributed Objects
• Distributed Systems:
– A collection of independent computers that appears to its users as a
single coherent system.
– The computers are also called the nodes of the system.
– Differences between the nodes are hidden from the user (i.e.
different Operating Systems in each node, or different hardware
architectures).
• Notice that the services could had been written in different languages
(each node used a different language to implement the service)
– These systems are easy to expand by adding new nodes.
– Each node can offer a different service to the user.
21
Distributed Objects
• In a distributed objects system everything is treated as an
object.
– Services are accessible to clients via objects.
– Distribution transparency is maintained by the fact that the user
does not know where the object that represents the service is
located.
– Objects encapsulate data which is called the state of the object.
– Objects have operations represented by methods that can be
invoked by the object.
– Operations (methods) are available via interfaces
• The operations are defined in interfaces that have to be available to the clients.
22
Distributed Objects
• Distributed Objects can be supported by languages such as
C++, Java or other OOP languages.
• A distributed object can be:
– Persistent: this means that its state is independent of the server that
executes the service that represents the object. Therefore its state
(data) has been stored in a secondary storage area outside of its
server.
– Transient: this means that the state of the object exists only as long
as the server that represents the object exists (is alive in a runtime
state).
23
Example of Distributed Object
•
Assume that a client located in New York City wants to access Payroll and
Employee services each located in servers in Chicago and Los Angeles
respectively.
Node B
Node A
Payroll
service
Client
Node C
Employee
Service
24
Example of Distributed Object
• In the previous slide Node A acted as a client requesting service (data)
from Nodes B and C.
• Node A, however, can be a node that offers a service to the other nodes
also.
• Therefore the concept of client and server is mixed. At some time later
Node B could be requesting services from Nodes A and C. Thus node
A is a client at that time while nodes A and C act as servers.
• Remember that each service could had used a different programming
language to implement itself.
25
Frameworks for Creating
Distributed Objects Systems
• Java has the following 4 Frameworks:
– RMI (Remote Method Invocation)
• It is available in Java SE.
• Use its own proprietary transport protocol called RMIP
– RMI over IIOP (RMI over Internet Inter Operability Protocol).
• Its is available in Java SE.
– An implementation of CORBA called Java IDL
• It is available in Java SE
• CORBA (Common Object Request Broker Architecture) is a
specification that can be implemented by various vendors (languages)
– JAVA Messaging Service API.
• Available in Java EE
26
Remote Method Invocation (RMI)
• 1.0 DEFINITION
• THE REMOTE METHOD INVOCATION API ENABLES CLIENT
AND SERVER COMMUNICATIONS OVER THE NET
• RMI ALLOWS JAVA (ONLY) OBJECTS , RESIDING ON THE
SAME OR DIFFERENT COMPUTERS ,TO COMMUNICATE
WITH ONE ANOTHER VIA REMOTE METHOD CALLS OVER
THE NETWORK.
– THEREFORE ONLY JAVA TO JAVA COMMUNICATIONS ARE
ALLOWED
• RMI PROVIDES FOR TRANSFER OF OBJECTS VIA OBJECT
SERIALIZATION.
– SERIALIZATION ALLOWS OBJECTS TO CARRY ALL THEIR
ATTRIBUTES (FIELDS) WITH THEM OVER THE NETWORK
27
Remote Method Invocation
(RMI)
• OBJECT SERIALIZATION IS USED TO SEND THE
ARGUMENTS (PROPERTIES) OF A METHOD INVOCATION
FROM THE CLIENT OBJECT TO THE REMOTE OBJECT
• OBJECT SERIALIZATION IS ALSO USED TO RETURN THE
VALUES FROM THE SERVER OBJECT BACK TO THE CLIENT
OBJECT.
• OBJECTS ARE CONVERTED INTO A STREAM OF BYTES
THAT CAN BE TRASMITTED OVER THE NETWORK BY
USING THE ObjectOutputStream CLASS.
• OBJECTS ARE RECONSTRUCTED AFTER TRANSMISSION BY
USING THE ObjectInputStream CLASS.
28
Remote Method Invocation (RMI)
• THE SERIALIZATION USED BY RMI IS TRANSPARENT TO
THE CLIENT AND SERVER OBJECTS.
• APPLICATIONS USING TCP SOCKETS ARE RESPONSIBLE
FOR SERIALIZING AND DESERIALIZING OBJECTS VIA INPUT
AND OUTPUT STREAMS.
• SECURITY IS AN ISSUE.
– JAVA OFFERS SECURITY VIA THE SECURITY PACKAGE.
• OPERATIONS THAT CAN BE INVOKED BY A REMOTE
OBJECT ARE DEFINED IN AN INTERFACE
– THE IMPLEMENTATION OF THE INTERFACE METHOD AT THE SERVER
HAS TO IMPLEMENT THE SERIALIZABLE INTERFACE.
29
Remote Method Invocation (RMI)
• LOCAL OBJECTS ARE OBJECTS THAT EXECUTE ON A
PARTICULAR HOST.
• REMOTE OBJECTS ARE OBJECTS THAT EXECUTE ON ALL
OTHER HOSTS.
• REMOTE OBJECTS HAVE TO BE EXPORTED.
• AN OBJECT EXPORTS ITSELF BY REGISTERING WITH A
REMOTE REGISTRY SERVER. (ALSO REFERRED TO AS
NAMING SERVICE)
• A REMOTE OBJECT THEN CAN INVOKE THE SERVER THAT
HAS IMPLEMENTED THE OPERATIONS FOR TH E OBJECT
(WE WILL REFER IT SIMPLY AS THE SERVER APPLICATION)
• RMI MAKES USE OF STUBS
– A STUB IS A LOCAL OBJECT THAT ACTS AS A PROXY FOR A
REMOTE OBJECT
30
Remote Method Invocation (RMI)
– THE STUB PROVIDES THE SAME METHODS AS THE REMOTE
OBJECT (THE METHODS THAT THE REMOTE OBJECT CAN
OPERATE).
– LOCAL METHODS INVOKE THE METHODS OF THE STUB AS IF
THEY WERE METHODS OF THE REMOTE OBJECT.
31
Remote Method Invocation (RMI)
• RMI AVOIDS THE NEED FOR PROGRAMMERS TO LEARN A
SEPARATE IDL (INTERFACE DEFINITION LANGUAGE) SINCE
ONLY JAVA TO JAVA COMMUNICATIONS ARE ALLOWED.
– IDL IS A LANGUAGE USED AS A INTERMEDIARY DATA TYPES
BETWEEN TWO DIFFERENT LANGUAGES WITH DIFFERENT DATA
TYPES
.
32
Remote Method Invocation (RMI)
• HOW RMI WORKS
Client
Default port 1099
Access to remote object requested
by name. Reference is returned.
Server
Object
registry
stub
Object ‘s method
is invoked
stub
Remote object
implementation
Remote
object
registers its
name
Messages Exchanged in RMI
33
Remote Method Invocation (RMI)
• BEFORE THE CLIENT IS STARTED THE RMI REGISTRY HAS
TO BE STARTED.
– RMI REGISTRY IS A SERVER SIDE NAMING REPOSITORY THAT
ALLOWS REMOTE CLIENTS TO GET A REFERENCE TO A
REMOTE SERVER OBJECT.
• ALSO THE SERVER PROGRAM HAS TO BE STARTED BEFORE
THE CLIENT.
34
RMI Communications
• The server application registers the remote object with the rmiregistry.
• The client contacts the registry and requests information about the
remote object.
– The registry returns a reference to the remote object. That means that
information is sent on:
• IP address of server.
• Port that the server uses for the service (server application).
• An object ID number that this client can use.
• The name of the service (method(s)) that can be invoked.
• Other information.
– Notice that the registry does not have to be on the same machine as the
server application.
– The registry listens on a default port 1099 that can be changed to a
different port number.
35
RMI Communications
•
The client uses the information from the registry to send a request to the
server to execute the service invoked by the object .
– The client also sends information about itself such as its IP address
and its port number.
•
The server executes the service and returns the data to the client.
– Notice that sometimes no data is returned but the response packets are sent
with other information anyway.
– Sometimes the server sends as part of its response a request back to the
client to execute a remote service that the client has. That is called
callback. The server expects a response from the client.
36
RMI Communications
• Communication Layers
Client
Server
Client Application
Server Application
Stub
(Presentation layer)
Stub
(Presentation layer)
Remote Reference
(Session Layer)
Remote Reference
(Session Layer)
RMIP
(Transport Layer)
RMIP
(Transport Layer)
TCP/IP (Network Layer)
TCP/IP (Network Layer)
37
Remote Method Invocation (RMI)
• RMI IS IMPLEMENTED BY 5 PACKAGES:
– java.rmi PROVIDES THE REMOTE INTERFACE, A CLASS FOR
ACCESSING REMOTE OBJECTS AND SECURITY MANAGER FOR
RMI.
– Java.rmi.registry PROVIDES CLASSES AND INTERFACES THAT
ARE USED BY THE REMOTE REGISTRY.
– java.rmi.server PROVIDES CLASSES AND INTERFACES USED TO
IMPLEMENT REMOTE OBJECTS AND STUBS AND TO SUPPORT
RMI COMMUNICATIONS.
– java.rmi.activation SUPPORTS PERSISTENT OBJECT REFERENCES
AND REMOTE OBJECT ACTIVATION
– java.rmi.dgc SUPPORTS RMI DISTRIBUTED GARBAGE
COLLECTOR.
38
Remote Method Invocation (RMI)
• The following steps are needed in order to implement an RMI
distributed application:
1.
Write the interface that defines the method(s) that can be invoked by the
remote object. Compile it.
2. Write the server that implements the interface’ s method(s). Compile it
using the rmic compiler and the regular compiler. The rmic compiler
creates a stub.
Notice that the server must extend UnicastRemoteObject and implement
the interface.
UnicastRemoteObject is the library class responsible for setting up all
network communications under the hood (without the developer having
to write any extra code for that)
1. Write the client program and compile it.
2. Place files as shown in the following diagram.
39
Remote Method Invocation
(RMI)
• Place files as shown.
Client Node
ClientProgram.class
InterfaceFile.class
stub
Server
InterfaceFile.class
ServerProgram.class
stub
40
Remote Method Invocation (RMI)
•
•
EXAMPLE OF AN RMI APPLICATION (TemperatureServerImpl)
LET US DEVELOP AN APPLICATION THAT WILL MONITOR THE
WEATHER INFORMATION OVER THE INTERNET FROM THE
WEATHER BUREAU’ S WEB SITE TWICE A DAY.
• THE APPLICATION , FOR THE SHAKE OF THE PRESENTATION, WILL
RUN LOCALLY (COPY THE PAGE Traveler.html --or an index.htl--OF
THE WEATHER BUREAU’ S SITE TO THE ROOT CONTEXT
DIRECTORY OF TOMCAT THAT YOU CREATED).
• IT IS ASSUMED THAT WE HAVE A LOCAL NETWORK. THE SERVER
GETS THE WEATHER INFORMATION FROM THE INTERNET AND
THE CLIENTS OF THE LOCAL NETWORK CAN ACCESS THE
INFORMATION FROM THE SERVER VIA REMOTE METHOD
INVOCATION
(NOTE: THE COD EFOR THIS EXAMPLE IS AVAILABLE ON THE
COURSE’ S WEB SITE AS WELL AS OTHER RMI EXAMPLES).
41
Remote Method Invocation (RMI)
• SUMMARY OF TEMPERATURESERVER EXAMPLE:
//host:port/RemoteObjectName
client
Info from server
retrieved
whenever client
wishes
internet
Remote server
rmi
Unicast (point-point)
communications
between objects via
method calls.
Aquire
information
from weather
forecast
site and store
it
http
Web server
Weather
forecast site
•Info is stored in an array of objects
•Info is downloaded when
server program starts and gets repeated twice a day.
42
Remote Method Invocation (RMI)
• IMPLEMENTING THE RMI APPLICATION
• AT THE SERVER SIDE:
– REMOTE OBJECTS ARE REFERENCED VIA INTERFACES.
YOU CREATE AN INTERFACE FOR EACH OBJECT.
• THE INTERFACE MUST BE PUBLIC AND MUST EXTEND
INTERFACE Remote .
• DEFINE THE REMOTE METHODS THAT YOU WANT TO
INVOKE WITHIN THE INTERFACE. THE METHODS MUST
THROW RemoteException .
• IN OUR EXAMPLE THERE THE INTERFACE is:
– public interface TemperatureServer extends Remote {
public WeatherInfo [] getWeatherInfo() ;
}
43
Remote Method Invocation
(RMI)
• The CLIENT will invoke method getWeatherInfo() which returns an
array of objects type WeatherInfo.
• Extending the interface Remote implies that our objects can be
remotely accessed by any JVM that has network connection to the
server and the appropriate stubs.
– CREATE A CLASS THAT IMPLEMENTS THE INTERFACE
(TemperatureServerImpl). Notice that by convention the server
uses the name of the interface appended by Impl
• THE CLASS EXTENDS UnicastRemoteObject CLASS (SUBCLASS
OF RemoteServer CLASS). (public classTemperatureServerImpl
extends UnicastRemoteObject implements TemperatureServer)
– UnicastRemoteObject CLASS ALLOWS THE REMOTE OBJECT TO
WAIT FOR A CLIENT CONNECTION ON AN ANONYMOUS PORT
NUMBER.
44
Remote Method Invocation (RMI)
• THE CLASS SHOULD HAVE A CONSTRUCTOR THAT CREATES ,
INITIALIZES THE REMOTE OBJECT
• IT SHOULD IMPLEMENT ALL THE METHODS DEFINED IN THE
REMOTE INTERFACE (public WeatherInfo[] getWeatherInfo () )
• IT SHOULD HAVE A main METHOD THAT CAN BE EXECUTED AS A
REMOTE CLASS.
– IT SHOULD REGISTER A NAME BY WHICH IT CAN BE REMOTELY
REFERENCED WITH THE REMOTE REGISTRY. ( String serverObjectName=
“//localhost/TempServer”; )
– THE NAME OF THE OBJECT USED BY THE MAIN SHOULD BE BOUND TO
THE NAME USED BY THE CLIENT. ( Naming.rebind ( serverObjectName,
temp) ).
– WHERE temp IS AN INSTANCE OF THE SERVER (I.E. TemperatureServerImpl
temp = new TemperatureServerIMpl();)
45
Remote Method Invocation
(RMI)
• CREATE A CLASS WeatherInfo that creates WeatherInfo objects.
• USE rmic COMPILER TO CREATE A STUB AT THE SERVER AFTER
YOU COMPILE THE SERVER WITH THE NORMAL javac COMPILER:
– rmic -v1.2 TemperatureServerImpl.
– THIS COMMAND GENERATED THE FILE TemperatureServerImp_stub.class
– THE stub FILE MUST BE PRESENT IN BOTH THE SERVER DIRECTORY
AND THE CLIENT DIRECTORY IF YOU ARE DOING THE EXAMPLE
LOCALHOST.
46
Remote Method Invocation (RMI)
– START THE REMOTE REGISTRY SERVER. THIS PROGRAM
LISTENS ON THE DEFAULT PORT 1099 FOR INCOMING
REQUESTS TO ACCESS NAMED OBJECTS. ON THE COMMAND
WINDOW TYPE:
– > start rmiregistry
– LEAVE REGISTRY SERVER RUNNING AND MINIMIZE THE DOS
WINDOW .
– START THE SERVER. BOUND REMOTE SERVER OBJECT TO THE
REGISTER. RUN THE COMPILED OBJECT IMPLEMENTATION CLASS ON
ANOTHER DOS WINDOW
» >java TemperatureServerImpl
» This is a server and should be left running. Minimize the window.
47
Remote Method Invocation (RMI)
• AT THE CLIENT
– WRITE A CLIENT PROGRAM THAT WILL CALL THE REMOTE
OBJECT ( THE IMPLEMENTATION OF THE INTERFACE).
– THE IP ADDRESS OF THE MACHINE THAT THE REMOTE OBJECT
RESIDES SHOULD BE USED (OR THE REMOTE HOST’S NAME).
– Naming.lookup ( serverObjectName) IS USED TO INTERACT WITH
THE RMI REGISTRY TO HELP THE CLIENT OBTAIN A
REFERENCE TO THE REMOTE OBJECT.
– A COPY OF THE INTERFACE STUB SHOULD BE COPIED TO THE
SAME DIRECTORY AS THE CLIENT PROGRAM.
• Start the client pr0gram by calling:
• >java TemperatureClient
48
Remote Method Invocation (RMI)
• CLASSES USED:
SERVER
CLIENT
TemperatureClient.class
TemperatureServer.class
TemperatureServerImpl_Stub.class
WeatherInfo.class
TemperatureServer.class
TemperatureServerImpl.class
WeatherInfo.class
TemperatureServerImpl_Stub.class
Where TemperatureServer.class is the interface
49
STUDY GUIDE
• WEB BASED APPLICATION DEVELOPMENT text
Chapter 7
• Read examples on RMI posted on the course’ s web site.
50
Download