CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 13 George Koutsogiannakis/Summer 2011 1 Topics • Performance comparison between RMI and RMI over IIOP. • Example of Applet and Servlet Communications. • Example of applet/servlet/RMI over IIOP server communications. • Java Beans in Standard Edition jdk. • Using Net Beans 2 RMI and RMI over IIOP Performance • In general RMI over IIOP is slower than RMI because of : – The IDL conversions needed. – The additional layers in the architecture of RMI over IIOP. • It is, however, depended on the amount of data transferred during each invocation, and the type of data being transferred. – IIOP packets can carry more data than RMI packets (approximately 80% more). – The set up for the packets is, however, greater for IIOP than it is for RMI (because of the additional layers). 3 RMI and RMI over IIOP Performance – There is a point where for large amounts of data transfers IIOP can become more efficient than RMI but it also depends on the number of invocations that need to be made. – Because of the Distributed Garbage Collector RMI invocations can take a longer time than RMI over IIOP invocations. – Therefore for large amounts of data to be transferred over a small number of invocations ,RMI over IIOP may be more effective. 4 RMI and RMI over IIOP Performance Time increases RMI over IIOP RMI Size of data increases This graph applies for a specific data type of data 5 Example of Applet and Servlet Communications • The following example illustrates how an applet (client side execution) can communicate with a servlet (server side execution). – The example web application is called LoginAppletNORMI and it is posted on the examples page of the course ‘s web site. • Architecture: Web Server Web App: LoginAppletNORMI LoginApplet.html LoginApplet.jar WEB-INF web.xml classes TestLoginServlet .class 6 Example of Applet and Servlet Communications • Develop web application outside Tomcat in some folder with the name of the web application: – i.e. folder name: LoginAppletNORMI • jar the applet .class files and place them in the web application folder. • Make sure that you have the directory structure required for a web application: – i.e WEB-INF folder with the web.xml inside and another folder name d: classes. – Place the servlet class in the classes folder. – You can also create a folder named lib and place a copy of the jar file there. 7 Example of Applet and Servlet Communications • Create a war file: – Open a DOS window with the path inside the web application folder. Type the command: >C:\web application folder> jar LoginAppletNORMI.war . – Notice that the name of the war file war file is the same as the name of the web application folder. • Go to: http://localhost:8080/manager and log in as an administrator. – At the bottom of the page browse to where the war file is located and then press deploy. – You web application is now deployed in Tomcat. 8 Example of Applet and Servlet Communications • You can now test it by: – Opening a Browser instance and typing: http://localhost:8080/LoginAppletNORMI/Login Applet.html. 9 Example of Applet and Servlet Communications • LoginApplet.html file: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Untitled</title> </head> <body><p>I am calling Applet</p> <applet code="LoginApplet.class" archive="LoginApplet.jar” Width="500" Height="500"></applet> </body> </html> 10 Example of Applet and Servlet Communications LoginApplet.java code: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; public class LoginApplet extends JApplet { Container c; JTextField ltf=new JTextField();; String login; JButton exitbutton, submitbutton; 11 Example of Applet and Servlet Communications public void init() { c=getContentPane(); ltf.setEditable(true); BorderLayout bl=new BorderLayout(); setLayout(bl); c.add(ltf, BorderLayout.NORTH); exitbutton=new JButton("Exit"); MyPanel mp=new MyPanel(); c.add(exitbutton, BorderLayout.SOUTH); c.add(mp, BorderLayout.CENTER); Handler h=new Handler(); ltf.addActionListener(h); submitbutton.addActionListener(h); exitbutton.addActionListener(h); } 12 Example of Applet and Servlet Communications class MyPanel extends JPanel { public MyPanel() { submitbutton=new JButton("Submit"); add(submitbutton); } } 13 Example of Applet and Servlet Communications class Handler implements ActionListener { public void actionPerformed(ActionEvent e){ if(e.getSource()==exitbutton){ System.exit(0); } else if(e.getSource()==submitbutton){ System.out.println("Inside handler for submit button"); try{ login=ltf.getText(); URL url=new URL("http://localhost:8080/LoginAppletNORMI /TestLoginServlet?loginname="+login); URLConnection uc=url.openConnection(); uc.setDoOutput(true); uc.setDoInput(true); ltf.setText("I sent info to servlet"); InputStreamReader instream=new InputStreamReader(uc.getInputStream()); BufferedReader in=new BufferedReader(instream); ltf.setText("I am reading input stream now"); 14 Example of Applet and Servlet Communications String line; while((line=in.readLine())!=null) { ltf.setText(line); } in.close(); System.out.println("I finished try block. Name="+" "+login); } catch(MalformedURLException exception){ltf.setText("Malformed exc."); } catch(IOException exception){ltf.setText("IO exc."+exception.getMessage());} System.out.println("I finished actionPerformed"); } } } } 15 Example of Applet and Servlet Communications TestLoginServlet.java code: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class TestLoginServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String login=req.getParameter("loginname"); res.setContentType("text/html"); PrintWriter out=res.getWriter(); if(login.equals("george")) out.println("The servlet verifies that your name is:"+login); else out.println("Wrong login name. Please try again"); out.close(); } } 16 Example: ServletLoginApplet web application • This example simulates the communications between an applet and a servlet which acts as a client for an RMI over IIOP server. • The applet sends a request to the servlet. • The servlet in turn is a client to an RMI server. It sends a request to the RMI server. The RMI server returns a response to the servlet which in turn sends a response to the applet. 17 Example: ServletLoginApplet web application • This application requires that: – Deployment in Tomcat of the web application part • A signed jar file for the applet. • A html file that calls the signed applet via the archive attribute of the applet tag. • A servlet under the WEB-INF/classes path. • The class ReverseInterface.class under the WEB-INF/classes path. – This is the interface file from the RMI over IIOP server 18 Example: ServletLoginApplet web application • The stub file from the RMI over IIOP server called: _ReverseInterface_stub.class under the path WEB-INF/classes • A web.xml file under the WEB-INF folder. – Deploy using a war file as in previous example. – The RMI over IIOP server classes (interface, implementation class tie class etc.) should reside in a path outside of Tomcat. 19 Example: ServletLoginApplet web application • To test the web application certain tasks have to be done in the proper sequence: – From the folder where the RMI over IIOP server is located start an instance of the naming service (registry): C:\........>tnameserv –ORBInitialPort – Next start the RMI over IIOP server: C:\>……>java Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory -Djava.naming.provider.url=iiop://localhost:900 ReverseInterfaceImpl 20 Example: ServletLoginApplet web application – Next, start an instance of the Browser and type: http://localhost:8080/ServletRMIIIOP/IIOPLoginApplet.html 21 Example: ServletLoginApplet web application Applet streams (POST HTTP request) URL url=new URL("http://localhost:8080/ServletRMIIIOP/IIOPTestLoginServlet"); qr="qr="+URLEncoder.encode(query); textarea.append("\n"+"The applet displays"+qr+"\n"); URLConnection uc=url.openConnection(); uc.setDoOutput(true); uc.setDoInput(true); uc.setUseCaches(false); ByteArrayOutputStream bytestream=new ByteArrayOutputStream(512); PrintWriter out=new PrintWriter(bytestream,true); out.print(qr); out.flush(); //POST requests are required to have Content Length String lengthString=String.valueOf(bytestream.size()); uc.setRequestProperty("Content-Length", lengthString); uc.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); bytestream.writeTo(uc.getOutputStream()); out.flush(); out.close(); 22 Example ServletLoginApplet web application InputStreamReader in=new InputStreamReader(uc.getInputStream()); int chr=in.read(); while(chr!=-1) { textarea.append(String.valueOf((char)chr)); chr=in.read(); } in.close(); System.out.println("I finished try. Name="+" "+query); } catch(MalformedURLException exception){textarea.setText(e.toString()); } catch(IOException exception){textarea.setText(e.toString());} System.out.println("I finished actionPerformed"); } 23 Example: ServletLoginApplet web application Servelt code: import javax.naming.*; import java.util.*; public class IIOPTestLoginServlet extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String qr=req.getParameter("qr"); String loginmod="The name is:"+" "+qr+" "+"Therefore the servlet works with doPost"; res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println(loginmod); out.println("The servlet captured the value of qr="+qr); 24 Example: ServletLoginApplet web application ReverseInterface r; Hashtable env=new Hashtable(); env.put("java.naming.factory.initial", "com.sun.jndi.cosnaming.CNCtxFactory"); env.put("java.naming.provider.url", "iiop://localhost:900"); try{ out.println("TRYING TO CONTACT REGISTRY"); Context initialNamingContext=new InitialContext(env); out.println("obtained InitialContext"); r=(ReverseInterface)PortableRemoteObject.narrow( initialNamingContext.lookup("Reverse"), ReverseInterface.class); out.println("The registry lookup was successful"); out.println("the opposite of "+qr+"is"+r.reverseString(qr)); } catch (Exception e) { out.println("Error executing remote method or lookup 1:30 p.m."); out.println(e.toString());} out.close(); } 25 Example ServletLoginApplet web application RMI over IIOP server import java.rmi.Remote; import java.rmi.RemoteException; public interface ReverseInterface extends Remote { String reverseString(String originalstring) throws RemoteException; } 26 Example ServletLoginApplet web application import java.rmi.*; import java.rmi.server.*; //add the lines below import javax.rmi.PortableRemoteObject; import javax.naming.*; import java.net.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; public class ReverseInterfaceImpl extends PortableRemoteObject implements ReverseInterface { public ReverseInterfaceImpl() throws RemoteException { super(); } 27 Example ServletLoginApplet web application public String reverseString(String originalstring) throws RemoteException { int length=originalstring.length(); StringBuffer temp=new StringBuffer(length); for (int i=length; i>0; i-- ) { temp.append(originalstring.substring(i-1,i)); } return temp.toString(); } 28 Example ServletLoginApplet web application public static void main(String[] args){ try{ ReverseInterfaceImpl r= new ReverseInterfaceImpl(); Context initialNamingContext=new InitialContext(); System.out.println("Binding server to registry.."); initialNamingContext.rebind("Reverse",r); System.out.println("Object was registered"); } catch(Exception e) { System.out.println("Error while binding object 11:00am"); System.out.println(e.toString()); } System.out.println("The RMI server is up and Running!"); } } 29 Example ServletLoginApplet web application Command to start RMI over IIOP server: C:\.....>java -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory -Djava.naming.provider.url=iiop://localhost:900 ReverseInterfaceImpl Command to compile server with rmic compiler: C:\......>rmic -iiop ReverseInterfaceImpl Notice that the rmic command should be done after the server file has been compiled with the normal javac compiler. 30 Java Beans • The Java Beans architecture is based on the component model. – Components are self sustained reusable software modules. • The idea behind Java Beans is that we can introduce customization of the component during run time (dynamically). • Java Beans Architecture promotes reusability but it is different than inheritance. Inheritance is introduced at compilation time. Any changes result to recompilation. – Java Beans, however, have their properties changed by another class dynamically during run time. – A java Bean can be used by another Java Bean thus resulting in a new Java Bean which is the combination of the two. • Java Beans expose their properties to other Beans. 31 Java Beans • Internal workings of the Java Bean are hidden from the user. • All the user needs to know is what functionality the Bean offers and what interface it provides. – The user can access and set properties of the Bean as needed during run time. • In Java Standard Edition Beans are supported via the packages: – java.beans – java.beans.beancontext • Other languages have similar concept to Beans such as Delphi and Visual Basic. 32 Java Beans Bean A Bean B Bean C Bean C combines the functionality of Bean A and Bean B 33 Java Beans • To write a Java Bean we need: – Rules that ensure consistency in writing interfaces: i.e accessor method names begin with get, mutator methods begin with set. • Bean properties must use get /set followed by the property’s name i.e. String LastName; public String getLastName(); • Properties of a Bean can be: – – – – – Simple: String LastName ( contains a single value) . Indexed: to keep track of the values of a group of properties. Bound: alert other objects when its value changes. Constrained: notifies other objects of impending changes Read/Write, read-only, write-only 34 Java Beans – An event handling model. – Persistence. Retaining information about the state of an object. – Introspection: Discover how to access other Java Bean components. – We need support from a Builder IDE. The IDE will allow connection of Java Beans to produce the final application. Such an IDE can be NetBeans. 35 Java Beans • Introspector class – java.beans.Introspector provides a standard way for building tools to learn about the properties, events and methods supported by a target java bean. – The introspector will analyze the bean’s class and superclass looking for its accessor and mutator methods, event methods and so on. – Introspection will also look for explicit information that can be provided about a Bean via a BeanInfo class provided by the developer of the Bean. 36 Java Beans 37 Java Beans • For example, the builder tool in the previous slide shows a calculator component that is built from: – 16 button components, – a text field component, – and a panel upon which the buttons and a text display are placed. – In addition, you can see five invisible components. These specific components hold values or strings used by the calculator for intermediate calculations, operation codes, and display strings, as well a boolean flag to determine when evaluation of a new expression is started. • The calculator shown becomes itself a component that can be integrated in another application 38 Java Beans • More information about Java Beans is provided in the Java Beans Specification available at: http://java.sun.com/javase/technologies/desktop/javabeans/docs/spec. html 39 Java Beans • To create a simple Bean and import it in a tool like Net Beans : – Create the Java Bean program. Notice that all Java Bean classes must be serializable. – Create a Manifest File – Jar the files – Import into the tool Note: A Java Bean can also be created outside the builder tool by having the developer write the code for it. 40 Creating A Java Bean programmatically • Java Beans are normally stored and distributed in jar files. – The jar file must contain a manifest file which describes the contents of the jar file. • Contents are defined under specific headers in the manifest file. • The manifest file is read by the IDE (Builder) tool when we load the Bean on the IDE. • To create the manifest file we can use a text editor i.e Main-Class: folder1.folder2.MyBean Name: folder1.folder2.MyBean.class Java-Bean: True • The file needs to be saved as manifest.tmp. >jar cmf manifest.tmp MyBean.jar MyBean.class • The jar utility uses the file manifest.tmp to create the file MANIFEST.MF and place it in a directory called META-INF inside the jar. Note: The jar file can also become an executable. In other words we can execute the program just by double clicking on the icon of the jar file (at least in 41 Windows platforms). Creating A Java Bean programmatically • To confirm the file is in the jar use the command: >jar tvf MyBean.jar • The jar file can also be executed via the command: > java –jar MyBean.jar 42 Development Environments • There are Development Environments for learning purposes. – A tool like that was the BDK-Bean Development Kit (not available any more) offered by SUN – Another tool like that offered is the BeanBuilder available at: https://bean-builder.dev.java.net/ • Neither of these tools is suitable for a production environment 43 Net Beans IDE • An IDE that allows the creation of GUIs via drop and drag actions. • The creation of Enterprise Java Beans. • A small example of how the Net Beans IDE can be used to create a GUI is described in file: netbeansGUI.doc posted in the examples page of the course’ s web site. 44 Net Beans IDE • Install NetBeans 6.5 or higher from the netbeans.org site. Use the choice that includes all. • Before installation make sure: – That you have installed Java SDK with EE. 45 Net Beans IDE • During installation of NetBeans: – Make sure that you choose the customization choice: • Add Tomcat as part of the installation – Make sure that you choose the SDK/jdk path as the jdk to be used by NetBeans. • Check PATH variable to make sure that is shown as SDK/bin 46 Net Beans IDE • Make sure that you record all port numbers and passwords. – The Tomcat passwords need to be recorded. If for some reason you forget you can recover the Tomcat passwords from file: C:\Users\YourUserNamefor your system\.netBeans\6.5\apatche-tomcat6.0.18_base\conf\tomcat-users.xml 47 Net Beans IDE • After NetBeans installation is completed: – Go to services and right click to add the GlassFish 2 server as a server (or GlassFish 3). – You will be asked to create a Domain for your applications. Choose “Create Personal Domain”. 48 Net Beans IDE • Create a Folder C:\GlassFishDomains in windows explorer first. • In the NetBeans window type: C:\GlassFishDomains\Domains • The system will create the folder Domains and place the required files in it. • You will be asked to create a password to access the administrative console of GlassFish. 49 Net Beans IDE • Make a note of the system paths to the various installations. • Make a note of port numbers – i.e due to conflicts with exiting usages of port numbers Tomcat make work in port 8084 now. • If you deploy a web application using GlassFish, then you do not need to deploy it in Tomcat also. 50 Net Beans IDE • Notice that under services Tomcat and GlassFish appear as separate services. – i.e. You can deploy a web service that does not have beans in it in Tomcat and not bother with GlassFish. – You will deploy on Tomcat using the manager page of Tomcat and a war file. 51 Study Guide • Study slides. • Suggest that you experiment with Bean Builder tool. • Download and start experimenting with Net Beans 52