ISE 582: Information Technology for Industrial Engineering Instructor: Elaine Chew University of Southern California Department of Industrial and Systems Engineering Lecture 11 JAVA Cup 10: Making Connections Winston & Narasimhan: Chapt 53-55 Project: Submitting + Presenting Send icon and short description ASAP. By Thu, Dec 4, 12noon, send link to: source code, short description (classes, purpose, structure) introduction and user guide. Presentation, Dec 4, 6:30-9:10pm. Each team has 5 minutes. Powerpoint slides optional, no more than 5 slides. 20 November 2003 Web Technology for IE 2
JAVA Cup 10 JAR files for distribution Activating Remote Computations Servlets: Collecting Information 20 November 2003 Web Technology for IE 3 JAR Files for Distribution JAR stands for Java ARchive The Manifest File JAR-ing Class Files JAR-ing Packages JAR-ing Image Files Runing Applications from JAR files More on Manifest Files 20 November 2003 Web Technology for IE 4
Description JAR stands for Java ARchive Reasons to use JAR files: Simplifies program distribution Saves space and time Provides version management Enables security 20 November 2003 Web Technology for IE 5 The Manifest File Needs to be created before JAR file Minimally, needs one line to identify the starting application class: Main-Class: <application-starting class> Main-Class: MovieApplicationTestor Save file as, say, manifest.txt 20 November 2003 Web Technology for IE 6
The Command-line Jar Assume current directory contains all class files needed by your application The jar command is: jar -cmf <manifest-filename> <jar-filename>.jar *.class c = create a new JAR file m = use the following manifest file f = use the file name supplied jar -cmf manifest.txt MovieApplication.jar *.class 20 November 2003 Web Technology for IE 7 Jar-ing Packages Suppose your application is divided into packages (subdirectories): application model view The appropriate jar command is: jar -cmf manifest.txt MovieApplication.jar application model view 20 November 2003 Web Technology for IE 8
Including Image Files If images are in the image subdirectory:??? If images are in current directory:??? 20 November 2003 Web Technology for IE 9 Application Running the Application Command to start application from a jar file: java -jar <jar-filename>.jar java -jar MovieApplication.jar 20 November 2003 Web Technology for IE 10
More on the Manifest File Main-Class: MovieApplicationTestor Class-Path: Entertainment.jar package jar file used by application Name: application/ Specification-Title: "Application specifications" Specification-Version: "3.141" Specification-Vendor: "XYZ, Inc." Implementation-Title: "Application implementation" Implementation-Version: "Build 2.718" Implementation-Vendor: "XYZ, Inc." description Name: model/... Name: view/... 20 November 2003 Web Technology for IE 11 Activating Remote Computations Why use remote computations? RMIs: Description and Example What the Server needs What the Client needs Server-side registry and compilation Client-side modifications Testing the code 20 November 2003 Web Technology for IE 12
Why Use Remote Computations? client server 20 November 2003 Web Technology for IE 13 Example of Remote Computations Search for extraterrestrials - or extra cash Users let home PCs crunch scientific data in down time By Doug Bedell / The Dallas Morning News (12/02/99) Humans use only a fraction of their brain power, and the Internet is no different. The millions of often-idle computers connected to the Net are, in the eyes of some researchers, a wasted resource of criminal proportion. Recently, several groups have developed small programs that can take advantage of idle home and office units, putting them to work on worldwide projects for fun and profit. And the response from the public has been incredible. The Search for Extraterrestrial Intelligence, or SETI, for example, began doling out chunks of radio telescope data to volunteer computers in May. By October, spurred by the success of the movie Contact, it had enlisted more than 1.4 million "volunteer computers" worldwide in the organization's quest to isolate signals emanating from beyond our galaxy 20 November 2003 Web Technology for IE 14
RMIs: Description RMI stands for Remote Method Invocation RMIs enables a client computer to run a method on a server computer server-side instance is method target client-side instance is argument 20 November 2003 Web Technology for IE 15 RMIs: Example public class RatingServer { public int serverrating (Movie m) { System.out.println("RatingServer asked for a rating"); int s = m.getscript(); int a = m.getacting(); int d = m.getdirection(); return 3 * Math.max(Math.max(s, a), d); 20 November 2003 Web Technology for IE 16
Substituting the new rating server-side instance is method target client-side instance is argument movie.rating() becomes (new RatingServer()).serverRating(movie) 20 November 2003 Web Technology for IE 17 import java.rmi.*; import java.math.*; Test Program public class ClientStub { public static void main(string args[]) { Movie movie = new Movie(2, 3, 8, Lord of the Rings"); RatingServer ratingserver = new RatingServer(); int rating = ratingserver.serverrating(movie); System.out.println("The server returned a rating of " + rating); --- Result --- RatingServer asked for a rating The server returned a rating of 24 20 November 2003 Web Technology for IE 18
What the Server needs RatingServer needs to know all the methods and method signatures for the Movie class. where can this be found? Introduce serializability in Movie classes why do you think this is necessary? 20 November 2003 Web Technology for IE 19 What the Server needs: E.g. import java.io.*; public interface MovieInterface extends Serializable { // Setters public abstract void setscript (int i) ; public abstract void setacting (int i) ; public abstract void setdirection (int i) ; // Getters public abstract int getscript () ; public abstract int getacting () ; public abstract int getdirection () ; public abstract String gettitle () ; public abstract String getposter () ; // Miscellaneous methods public abstract int rating () ; public abstract void changed () ; 20 November 2003 Web Technology for IE 20
What the client needs ClientStub needs to know that serverrating exists in ServerRating class where can this information be found? Introduce the Remote interface informs compiler that method is to be called by a client and run on a server 20 November 2003 Web Technology for IE 21 What the client needs: E.g. import java.io.*; import java.rmi.*; public interface RatingServerInterface extends Remote { public abstract int serverrating(movieinterface m) throws RemoteException ; 20 November 2003 Web Technology for IE 22
Modified RatingServer import java.rmi.*; public class RatingServer implements RatingServerInterface { public int serverrating (MovieInterface m) throws RemoteException { System.out.println("RatingServer asked for a rating"); int s = m.getscript(); int a = m.getacting(); int d = m.getdirection(); return 3 * Math.max(Math.max(s, a), d); 20 November 2003 Web Technology for IE 23 Modified ClientStub import java.rmi.*; import java.math.*; public class ClientStub { public static void main(string args[]) throws RemoteException { Movie movie = new Movie(2, 3, 8, Lord of the Rings"); RatingServerInterface ratingserver = new RatingServer(); int rating = ratingserver.serverrating(movie); System.out.println("The server returned " + rating); 20 November 2003 Web Technology for IE 24
Further Modifications import java.rmi.*; import java.rmi.server.*; public class RatingServer extends UnicastRemoteObject implements RatingServerInterface, Serializable { public RatingServer () throws RemoteException { super(); public int serverrating (MovieInterface m) throws RemoteException { System.out.println("RatingServer asked for a rating"); int s = m.getscript(); int a = m.getacting(); int d = m.getdirection(); return 3 * Math.max(Math.max(s, a), d); 20 November 2003 Web Technology for IE 25 The Registry Clients / servers communicate via a registry running on the server. Need a connection with server s registry program to create a RatingServer instance that can receive method calls from a client. Connect via Naming.rebind( //<hostname>/<name>, <remotely-accessible-instance> ) host-identifier usually is localhost Rebind and RatingServer constructors throw exceptions. Call using try-catch statements. 20 November 2003 Web Technology for IE 26
In RatingServer Class yada yada yada public static void main(string[] args) { try { Naming.rebind("//localhost/ratingService", new RatingServer()); System.out.println("Rating server connected to server"); catch (Exception e) { System.err.println("RatingServer exception: " + e.getmessage()); e.printstacktrace(); yada yada yada 20 November 2003 Web Technology for IE 27 Server-side Compilation Compile the java program on the server side twice using: javac RatingServer.java rmic RatingServer 20 November 2003 Web Technology for IE 28
Client-side modifications Client-side program now needs to access the remote instance of the RatingServer class Naming.lookup(//<hostname>/<name>) Use try-catch to deal with thrown exceptions Compile with javac 20 November 2003 Web Technology for IE 29 In ClientStub yada yada yada public static void main(string args[]) { Movie movie = new Movie(2, 3, 8, Lord of the Rings"); try { String computer = "whitney.ai.mit.edu"; System.out.println( Client asking, +computer+",for rating"); RatingServerInterface ratingserver=(ratingserverinterface) (Naming.lookup("//" + computer +"/ratingservice")); int rating = ratingserver.serverrating(movie); System.out.println(computer+ returned "+rating); catch (Exception e) { System.err.println("Rating client exception: " + e.getmessage()); e.printstacktrace(); yada yada yada 20 November 2003 Web Technology for IE 30
Testing the Code Client start ClientStub using java ClientStub Server start registry on window1 using rmiregistry command start server program on win2 using java RatingServer 20 November 2003 Web Technology for IE 31 Description Calling a servlet from an HTML link Servlet Startup Defining a Servlet How a Servlet gets Form values Managing Multiple Requests Servlets Storing Information on Client Computer 20 November 2003 Web Technology for IE 32
Servlets: Description A servlet is a program activated by a client browser and run on a servlet server How is this different from an applet? Servlet stands for server+applet, a little server-side application Two ways to call a servlet: Specify servlet name in an HTML link Use HTML forms 20 November 2003 Web Technology for IE 33 Calling servlets from an HTML link Click on link, http://whitney.ai.mit.edu/servlet/startcritic A file, servlets.properties, contains a table that relates servlet names to class names: E.g. startcritic.code=getcriticformservlet Servlet server looks up startcritic in file to find GetCriticFormServlet A GetCriticFormServlet instance is constructed The init() method is called The doget() method is called HTML-decorated text is returned to browser 20 November 2003 Web Technology for IE 34
Servlet Communication Diagram Browser Servlet name identified in location field Servlet Server Servlet doget method servlets.properties file 20 November 2003 Web Technology for IE 35 Servlet Startup Where you put your servlets and servlets.properties file depends on the servlet server you happen to use The ritual to start up the servlet server also depends on your server. Example: startserver stopserver 20 November 2003 Web Technology for IE 36
Extend the HttpServlet class Defining a Servlet Define a shadowing doget() method. Method has two parameters: request (information about the request) response (information to return to browser) Servlet returns information contained in response instance to client 20 November 2003 Web Technology for IE 37 Servlet Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetCriticFormServlet extends HttpServlet { public void doget (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter output = response.getwriter(); output.println( <HTML><HEAD><TITLE> "); output.println( Movie Vote! "); output.println( </TITLE></HEAD><BODY> "); output.println( </BODY></HTML> "); output.flush(); 20 November 2003 Web Technology for IE 38
How a Servlet gets Form values Form has to specify: < form method=get action=<servlet> > < input type=? name=?? value=??? > Servlet deploys the getparameter method, for example: String title = request.getparameter( title ); String script = request.getparameter( script ); String action = request.getparameter( action ); 20 November 2003 Web Technology for IE 39 Managing Multiple Requests If your servlet writes info to a file, what if one client s work is underway when another arrives? Avoid multiple-thread toe stomping by having your servlets implement SingleThreadModel interface 20 November 2003 Web Technology for IE 40
Storing Info on Client Computer To store information on a client computer, you have your servlet establish cookies on the client computer Cookies have names and values (Strings) Cookie cookie = new Cookie( votes, 0 ); Add cookie to the response instance response.addcookie(cookie); // do before accessing writer Cookie size is limited (a few kilobytes) Cookies die when they get too old cookie.setmaxage(60*60*24*365); 20 November 2003 Web Technology for IE 41 Accessing Cookies Cookies [] cookies = request.getcookies(); for (int i = 0; i < cookies.length; ++i) { if("votes".equals(cookies[i].getname())) {... cookies[i].getvalue()... Same name can have multiple values E.g. One user can evaluate many movies Browsers are not obliged to store an indefinite number of movies To be safe, do not store more than 10 Cookies are not servlet-specific Can be used to communicate among servlets Cookies are URL-specific 20 November 2003 Web Technology for IE 42
What Have You Learnt How to create your homepage How to create HTML forms The basics of UML notation What it means to be object-oriented Encapsulation, inheritance, polymorphism 20 November 2003 Web Technology for IE 43 What Have You Learnt How to create classes, instances and methods, including: get / set methods constructors How to create programs that solve problems. Techniques include: Loops, recursion, conditional statements How to work with basic data structures: Characters and Strings stressed Arrays and Vectors desserts 20 November 2003 Web Technology for IE 44
What Have You Learnt Good programming practices Enforcing abstraction using private and public variables Enforcing requirements using abstract methods and classes Documenting programs using interfaces Modularizing programs using compilation units and packages Use JAR files for program distribution 20 November 2003 Web Technology for IE 45 What Have You Learnt How to read / write from / to files using Input / output streams Buffers / tokenizers How to create GUIs Drawing lines in windows Writing text in windows Creating forms that fire events Creating choice lists Incorporating images 20 November 2003 Web Technology for IE 46